<template>
  <view class="supplychainon-wrapper">
    <headerCom headerTitle="供应链列表" @headerJump="headerJump"></headerCom>
    <view class="headers-box">
      <searchVue
        placeholder="请输入商品名称"
        @search="onHandleSearch"
      ></searchVue>
      <tablist
        class="mt"
        :category="category"
        :curruntActive="curruntActive"
        @tabs="tabsHandleClick"
      ></tablist>
    </view>
    <view class="content-wrapper">
      <template v-if="list.length > 0">
        <ProductCard
          class="mrb"
          v-for="(item, index) in list"
          :key="index"
          :data="item"
          @status-change="handleStatusChange"
          @edit-price="handleEditPrice"
          @edit-activity="handleEditActivity"
        />
      </template>
      <template v-else>
        <emptyDataVue style="top: initial" />
      </template>
      <view
        v-if="tihsi == 0 && list.length > 0"
        class=""
        style="margin: 0rpx 0 30rpx 0; color: #999999; font-size: 26rpx"
      >
        —— 已经到最底部了哦 ——
      </view>
    </view>
    <priceEditModal
      v-if="isshow"
      :product-data="productObjData"
      :merInfo="merInfo"
      @close="priceEditModalClose"
      @confirm="confirm"
    />
    <!-- 弹窗主体 -->
    <uni-popup
      ref="popup"
      type="center"
      :is-mask-click="false"
      background-color="#rgba(0,0,0,0.5)"
    >
      <view class="popup-container" :class="[isOpen ? 'popup-show' : '']">
        <!-- 标题区 -->
        <view class="popup-header">
          <text class="title">活动设置</text>
        </view>
        <!-- 内容区 -->
        <view class="content-wrapper-popup">
          <view class="form-item">
            <uni-data-checkbox
              mode="button"
              icon="left"
              v-model="formData.radio"
              :localdata="rangeData"
            ></uni-data-checkbox>
          </view>
          <!-- 秒杀区块 -->
          <view class="form-item">
            <uni-data-checkbox
              mode="button"
              icon="left"
              v-model="formData.radios"
              :localdata="rangeData1"
              @change="onSwitchChange"
            ></uni-data-checkbox>
          </view>

          <!-- 价格输入 -->
          <view class="form-item">
            <view class="item-label">秒杀价格</view>
            <uni-easyinput
              v-model="formData.seckill_price"
              :errorMessage="isEmpty"
              focus
              placeholder="输入价格"
              :adjust-position="false"
              @change="changeInput"
              type="digit"
            ></uni-easyinput>
          </view>
          <!-- 时间选择 -->
          <view class="form-item">
            <view class="item-label">时间设置</view>
            <uni-datetime-picker
              type="datetime"
              v-model="formData.seckill_date"
              @change="onDateChange"
            />
          </view>
        </view>

        <!-- 操作按钮 -->
        <view class="action-btns">
          <button class="btn prev-step" @click="closePopup">取消</button>
          <button class="btn submit-btn" @click="handleSubmit">提交</button>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
import headerCom from "../../shop/components/headers/headers.vue";
import searchVue from "./search/search.vue";
import tablist from "./tablist.vue";
import ProductCard from "./ProductCard.vue";
import emptyDataVue from "../../shop/components/emptyData/emptyData.vue";
import priceEditModal from "./price-edit-modal.vue";
import {
  getSupplyChainList,
  getSupplyChainTab,
  postchangeshow,
  Addseckill, //活动
} from "@/commit/product.js";
import { getBaseInfo } from "@/commit/user.js";
export default {
  components: {
    headerCom,
    searchVue,
    tablist,
    ProductCard,
    emptyDataVue,
    priceEditModal,
  },
  data() {
    return {
      page: 1,
      limit: 10,
      tihsi: "",
      list: [],
      keywords: "",
      is_panudn: true,
      productData: {},
      curruntActive: 0,
      category: [],
      type: 1,
      isshow: false,
      formData: {
        radio: "1",
        radios: "1",
        seckill_price: "",
        seckill_date: "",
        product_id: "",
      },
      isOpen: false,
      rangeData: [
        { value: "1", text: "大仓活动" },
        { value: "2", text: "平台活动" },
      ],
      rangeData1: [{ value: "1", text: "秒杀" }],
      isEmpty: false,
      dataObj: {},
      productObjData: {},
      merInfo: {},
    };
  },
  async onLoad(options) {
    this.curruntActive = options.indexs || options.tabIndex || "0";
    this.type = options.type || 1;
    await this.getSupplyChainTabData();
    await this.getSupplyChainListData();
  },
  onPullDownRefresh() {
    uni.showLoading({
      title: "加载中",
    });
    this.page = 1;
    this.is_panudn = true;
    this.list = [];
    this.getSupplyChainListData();
  },
  onReachBottom() {
    if (this.is_panudn == true) {
      this.page++;
      this.getSupplyChainListData();
    } else {
      return;
    }
  },
  methods: {
    getBaseInfoData() {
      getBaseInfo()
        .then((res) => {
          if (res.data.status === 200) {
            // console.log(res.data.data)
            this.merInfo = res.data.data || {};
          } else {
            this.merInfo = {};
          }
        })
        .catch((err) => {
          uni.showToast({
            title: res.data.message || "获取失败",
            mask: true,
          });
        });
    },
    async initData() {
      await this.getSupplyChainTabData();
      await this.getSupplyChainListData();
    },
    async tabsHandleClick({ index, item }) {
      this.indexs = index;
      this.curruntActive = index;
      this.list = [];
      this.type = item.type || 1;
      this.page = 1;
      this.is_panudn = true;
      uni.pageScrollTo({ scrollTop: 0, duration: 0 });
      await this.getSupplyChainListData();
    },
    async getSupplyChainTabData() {
      try {
        const res = await getSupplyChainTab();
        if (res.data.status === 200) {
          this.category = res.data.data || [];
        }
      } catch (error) {}
    },
    async getSupplyChainListData() {
      uni.showLoading({
        title: "加载中",
      });
      try {
        const res = await getSupplyChainList({
          page: this.page,
          limit: this.limit,
          keyword: this.keywords,
          type: this.type,
          spec_type: null, //商品规格 null 0 1
        });
        uni.stopPullDownRefresh();
        if (res.data.status === 200) {
          this.tihsi = res.data.data.list.length || 0;
          console.log(this.tihsi, "this.tihsi");
          if (res.data.data.count > 0) {
            if (this.page == 1) {
              this.list = res.data.data.list;
            } else {
              this.list = this.list.concat(res.data.data.list);
            }
          } else {
            if (this.page == 1) {
              this.list = [];
            }
            this.is_panudn = false;
          }
          uni.hideLoading();
        }
      } catch (error) {}
    },
    headerJump() {
      uni.switchTab({ url: "/shop/productManagementModule/index" });
    },
    async onHandleSearch(val) {
      this.keywords = val;
      await this.getSupplyChainListData();
    },
    handleStatusChange(row) {
      let ids = [];
      ids.push(row.product_id);
      uni.showLoading({
        title: "状态更改中",
      });
      postchangeshow({ ids: ids, is_show: row.is_show })
        .then((res) => {
          if (res.data.status === 200) {
            uni.showToast({
              title: res.data.message,
              icon: "none",
            });
            this.getSupplyChainTabData();
            this.getSupplyChainListData();
          }
        })
        .catch((err) => {
          uni.hideLoading();
          uni.hideToast();
        });
    },
    handleEditPrice(data) {
      this.productObjData = data;
      this.isshow = true;
      document.body.style.overflow = "hidden";
      this.getBaseInfoData();
    },
    priceEditModalClose() {
      this.isshow = false;
       document.body.style.overflow = "visible";
    },
    confirm() {
      this.isshow = false;
      this.initData();
    },
    handleEditActivity(data) {
      this.dataObj = data;
      this.isEmpty = false;
      this.showPopup();
    },
    showPopup() {
      this.isOpen = true;
      this.$refs.popup.open();
    },
    closePopup() {
      this.isOpen = false;
      this.formData.radio = "1";
      this.formData.radios = "1";
      this.formData.seckill_price = "";
      this.formData.seckill_date = "";
      this.$refs.popup.close();
    },
    onDateChange(data) {
      this.formData.seckill_date = data;
    },
    convertToISOString(dateStr) {
      // 将输入的日期时间字符串中的空格替换为 'T'，以符合 ISO 8601 格式
      const isoFormatStr = dateStr.replace(" ", "T");
      // 创建 Date 对象
      const date = new Date(isoFormatStr);
      // 将 Date 对象转换为 ISO 8601 格式的字符串
      return date.toISOString();
    },
    async handleSubmit() {
      // 提交逻辑
      this.formData.product_id = this.dataObj.product_id;
      let params = JSON.parse(JSON.stringify(this.formData));

      if (
        params.seckill_price == "" ||
        params.seckill_price == null ||
        params.seckill_price == undefined
      ) {
        uni.showToast({
          title: "请输入秒杀价格",
          icon: "none",
        });
        this.isEmpty = true;
        return;
      }
      if (
        params.seckill_date == "" ||
        params.seckill_date == null ||
        params.seckill_date == undefined
      ) {
        uni.showToast({
          title: "请选择秒杀时间",
          icon: "none",
        });
        return;
      }
      params.seckill_date = this.convertToISOString(params.seckill_date);

      this.isEmpty = false;
      uni.showLoading({
        title: "秒杀活动添加中",
      });
      console.log(params);
      try {
        const res = await Addseckill(params);
        if (res.data.status == 200) {
          uni.showToast({
            title: "秒杀活动添加成功",
            icon: "none",
          });
          this.closePopup();
          this.initData();
        }
      } catch (error) {
      } finally {
        uni.hideLoading();
        uni.hideToast();
      }
    },
    changeInput(val) {
      if (val) {
        this.isEmpty = false;
      }
    },
  },
};
</script>
<style>
page {
  background-color: #f7f8fc;
  /* height: 100%; */
}
</style>
<style lang="scss" scoped>
.supplychainon-wrapper {
  .headers-box {
    position: fixed;
    top: 88rpx;
    left: 0;
    width: 100%;
    z-index: 33;
  }
  .content-wrapper {
    width: calc(100% - 52rpx);
    height: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    margin: 340rpx 26rpx 0rpx;
    padding-bottom: 60rpx;
  }
}
.mt {
  margin-top: 0rpx;
}
.mrb {
  margin-bottom: 26rpx;
}
.popup-container {
  width: 80vw;
  background: #ffffff;
  border-radius: 16rpx;
  transition: all 0.3s ease;
  transform: scale(0.8);
  opacity: 0;
  padding: 20rpx;
  .popup-header {
    padding: 0rpx 15rpx 15rpx;
    border-bottom: 1px solid #eee;
    .title {
      font-size: 36rpx;
      font-weight: 600;
      color: #333;
      text-align: center;
    }
  }
}
.content-wrapper-popup {
  overflow: auto;
  .form-item {
    padding: 15rpx 0;
    .item-label {
      font-size: 28rpx;
      font-weight: 600;
      color: #333;
      margin-bottom: 12rpx;
    }
  }
}
.popup-show {
  transform: scale(1);
  opacity: 1;
}
.action-btns {
  display: flex;
  padding: 24rpx;
  gap: 20rpx;
  border-top: 1px solid #eee;

  .btn {
    flex: 1;
    height: 80rpx;
    line-height: 80rpx;
    border-radius: 8rpx;
    font-size: 28rpx;

    &.prev-step {
      background: #f8f8f8;
      color: #666;
    }

    &.submit-btn {
      background: #007aff;
      color: white;
    }
  }
}

/deep/.uni-popup {
  z-index: 667;
}
</style>
