<template>
  <view class="product-manger-wrapper">
    <headersVue headerTitle="商品管理" @headerJump="headerJump"></headersVue>
    <view class="product-manger-content">
      <view class="product-manger-content--top">
        <searchVue @search="search" class="search-box"></searchVue>
        <view class="btn-product" @click="onHandleAddProduct">
          <image
            src="/static/images/new_ui/tianjiachanpin.png"
            mode="scaleToFill"
          />
          <view class="txt">添加商品</view>
        </view>
      </view>
      <view class="product-manger-content--tab">
        <tabsVue
          :category="dataList"
          :currentActive="currentActive"
          @tabs="tabsHandleClick"
        />
      </view>
    </view>
    <view class="product-manger-content--list">
      <template v-if="list.length > 0">
        <view class="list-card" v-for="(item, index) in list" :key="index">
          <view class="list-card-top">
            <view class="list-card-top--left">
              <image
                v-if="item.image && !isError"
                :src="item.image"
                mode="scaleToFill"
                @error="imgError"
                @load="loadImage"
              />
              <image
                v-else
                src="/static/images/new_ui/wutu.png"
                mode="scaleToFill"
                @error="imgError"
              />
            </view>
            <view class="list-card-top--right">
              <view class="list-card-top--right-title">{{
                item.store_name
              }}</view>
              <view class="list-card-top--right-description">
                <view class="list-card-top--right-description--left">
                  <text class="title">销量</text>
                  <text class="mdikd">{{ item.sales || 0 }}</text>
                </view>
                <view class="list-card-top--right-description--right">
                  <text class="title">库存</text>
                  <text class="mdikd">{{ item.stock || 0 }}</text>
                </view>
              </view>
              <view class="list-card-top--right-description">
                <view class="list-card-top--right-description--left">
                  <text class="title">活动：</text>
                  <text class="mdikd" style="color: red">{{
                    item.seckill == 1 ? "秒杀" : "无"
                  }}</text>
                </view>
              </view>
              <view class="list-card-top--right-price">
                <view class="list-card-top--right-price--left">
                  <text>¥</text>
                  <text class="price">{{ item.price || "0.00" }}</text>
                </view>
              </view>
            </view>
          </view>
          <view class="list-card-bottom-btn">
            <view class="list-card-bottom-btn-list">
              <button
                class="list-card-bottom-btn-list--item set-activity active"
                @click="huodong(item, index)"
              >
                活动
              </button>
              <!-- v-if="tableFrom.type === '5'" -->
              <button
                v-if="type == 5"
                class="list-card-bottom-btn-list--item bohui-activity active"
                @click="handleRestore(item.product_id)"
              >
                恢复商品
              </button>
              <template v-if="type == 1 || type == 2">
                <button
                  class="list-card-bottom-btn-list--item set-activity active"
                  v-if="item.is_show == 0"
                  @click="onHandleShow(item, 'shangjia')"
                >
                  上架
                </button>
                <button
                  v-if="item.is_show == 1"
                  class="list-card-bottom-btn-list--item set-activity active"
                  @click="onHandleShow(item, 'xiajia')"
                >
                  下架
                </button>
              </template>
              <button
                v-if="type != 1 && type != 3 && type != 4"
                class="list-card-bottom-btn-list--item delete-activity active"
                @click="handleDelete(item, index)"
              >
                {{ type == "5" ? "删除" : "加入回收站" }}
              </button>
            </view>
          </view>
        </view>
      </template>
      <template v-else>
        <emptyDataVue style="top: 0" />
      </template>
      <view
        class=""
        v-if="tihsi == 0 && list.length > 0"
        style="margin: 60rpx 0 30rpx 0; color: #999999; font-size: 26rpx"
      >
        —— 已经到最底部了哦 ——
      </view>
    </view>
    <!-- 弹窗主体 -->
    <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">
          <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 headersVue from "../components/headers/headers.vue";
import searchVue from "./components/search/search.vue";
import tabsVue from "./components/tablist.vue";
import emptyDataVue from "../components/emptyData/emptyData.vue";
import {
  getProductList,
  getGoodsTab,
  changeshowApi,
  destoryApi,
  productDeleteApi,
  productRestoreApi,
  Addseckill, //活动
} from "@/commit/product.js";
//商品列表
export default {
  components: {
    headersVue,
    searchVue,
    tabsVue,
    emptyDataVue,
  },

  data() {
    return {
      currentActive: "0",
      list: [],
      tihsi: "",
      is_panudn: true,
      page: 1,
      limit: 10,
      mer_cate_id: "",
      cate_id: "",
      keyword: "",
      type: 1,
      is_gift_bag: "",
      p_type: "",
      isError: false,
      dataList: [
        {
          type: 1,
          name: "出售中商品",
          count: 0,
        },
        {
          type: 2,
          name: "仓库中商品",
          count: 0,
        },
        {
          type: 3,
          name: "已售罄商品",
          count: 0,
        },
        {
          type: 4,
          name: "警戒库存",
          count: 0,
        },
        {
          type: 5,
          name: "回收站商品",
          count: 0,
        },
        {
          type: 6,
          name: "待审核商品",
          count: 0,
        },
        {
          type: 7,
          name: "审核未通过商品",
          count: 0,
        },
      ],
      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: {},
    };
  },
  async onLoad(options) {
    this.currentActive = options.tabIndex || "0";
    this.type = options.type || 1;

    await this.getGoodsTabData();
    await this.getProductListData();
  },
  async onPullDownRefresh() {
    uni.showLoading({
      title: "加载中",
    });
    this.page = 1;
    this.is_panudn = true;
    this.list = [];
    await this.getProductListData();
  },
  onReachBottom() {
    console.log("onReachBottom");
    if (this.is_panudn == true) {
      this.page++;
      this.getProductListData();
    } else {
      return;
    }
  },
  methods: {
    async initData() {
      await this.getGoodsTabData();
      await this.getProductListData();
    },
    imgError() {
      this.isError = true;
    },
    loadImage(e) {
      // console.log(e,"loadImage")
    },
    headerJump() {
      uni.switchTab({ url: "/shop/productManagementModule/index" });
    },
    onHandleAddProduct() {
      uni.redirectTo({
        url: `./addProduct`,
      });
    },
    async getGoodsTabData() {
      try {
        const res = await getGoodsTab();
        if (res.data.status == 200) {
          this.dataList = res.data.data;
        }
      } catch (error) {
      } finally {
      }
    },
    async getProductListData() {
      const params = {
        page: this.page,
        limit: this.limit,
        mer_cate_id: this.mer_cate_id,
        cate_id: this.cate_id,
        keyword: this.keyword,
        type: this.type,
        is_gift_bag: this.is_gift_bag,
        p_type: this.p_type,
      };

      try {
        uni.showLoading({
          title: "加载中",
        });
        const res = await getProductList(params);
        if (res.data.status == 200) {
          this.tihsi = res.data.data.list.length;
          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;
          }
        }
      } catch (error) {
      } finally {
        uni.hideLoading();
      }
    },
    async tabsHandleClick(obj) {
      this.currentActive = obj.index;
      this.type = obj.item?.type || 1;
      this.page = 1;
      this.list = [];
      this.is_panudn = true;
      uni.pageScrollTo({ scrollTop: 0, duration: 0 });
      await this.getProductListData();
    },
    async search(val) {
      this.keyword = val;
      // console.log(val)
      await this.getProductListData();
    },
    async onHandleShow(item, type) {
      const id = item.product_id;
      const data = {
        status: item.is_show,
      };
      const titleTips = item.is_show == 1 ? "商品下架中" : "商品上架中";
      const titleMsg = item.is_show == 1 ? "商品下架成功" : "商品上架成功";
      uni.showLoading({
        title: titleTips,
      });
      try {
        const res = await changeshowApi(id, data);
        if (res.data.status == 200) {
          uni.showToast({
            title: titleMsg,
            icon: "none",
          });
          await this.getProductListData();
        }
      } catch (error) {
      } finally {
        uni.hideLoading();
        uni.hideToast();
      }
    },
    /**删除 */
    handleDelete(item, index) {
      //  {{item.type === "5" ? "删除" : "加入回收站"}}
      const req = this.type === "5" ? destoryApi : productDeleteApi;
      const titleContent =
        this.type === "5" ? "是否删除产品？" : "是否商品加入回收站中？";
      const titleTips = this.type === "5" ? "商品删除中" : "商品加入回收站中";
      const titleMsg =
        this.type === "5" ? "商品删除成功" : "商品加入回收站成功";
      const product_id = item.product_id;
      const _this = this;
      uni.showModal({
        title: "温馨提示",
        content: titleContent,
        showCancel: true,
        success: ({ confirm, cancel }) => {
          if (confirm) {
            uni.showLoading({
              title: titleTips,
            });
            req(product_id)
              .then((res) => {
                if (res.data.status == 200) {
                  uni.showToast({
                    title: titleMsg,
                    icon: "none",
                  });
                  this.list.splice(index, 1);
                  _this.initData();
                }
              })
              .finally(() => {
                uni.hideLoading();
                uni.hideToast();
              });
          } else if (cancel) {
          }
        },
      });
    },
    //恢复产品
    handleRestore(id) {
      const _this = this;
      const titleTips = "商品恢复中";
      const titleMsg = "商品恢复成功";
      const product_id = id;
      uni.showModal({
        title: "温馨提示",
        content: "是否恢复商品？",
        showCancel: true,
        success: ({ confirm, cancel }) => {
          if (confirm) {
            uni.showLoading({
              title: titleTips,
            });
            productRestoreApi(product_id)
              .then((res) => {
                if (res.data.status == 200) {
                  uni.showToast({
                    title: titleMsg,
                    icon: "none",
                  });
                  _this.initData();
                }
              })
              .finally(() => {
                uni.hideLoading();
                uni.hideToast();
              });
          } else if (cancel) {
          }
        },
      });
    },
    huodong(item) {
      this.dataObj = item;
      const _this = this;
      if (item.seckill == 1 && this.type !=2) {
        uni.showModal({
          title: "温馨提示",
          content: "此商品正在处于秒杀状态,请勿操作",
          showCancel: false,
          success: ({ confirm, cancel }) => {},
        });
        return;
      }
       _this.showPopup()
      // Addseckill({}).then(data=>{
      //   console.log(data)
      // }).catch((res) => {
      //   console.log(res);
      //   if (res.data.message == "没有权限访问") {
      //     uni.showToast({
      //       title: res.data.message || "没有权限访问",
      //       icon: "none",
      //     });
      //   } else {
      //     _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;
}
</style>
<style lang="scss" scoped>
.product-manger-wrapper {
  // margin-top: 96rpx;

  .product-manger-content {
    background: #fff;
    position: fixed;
    top: 80rpx;
    width: 100%;
    z-index: 666;
    &--top {
      display: flex;
      .search-box {
        flex: 1;
      }
      .btn-product {
        user-select: none;
        width: 160rpx;
        flex-shrink: 0;
        display: flex;
        align-items: center;
        gap: 15rpx;
        image {
          width: 32rpx;
          height: 32rpx;
        }
        .txt {
          font-weight: 400;
          font-size: 26rpx;
          color: #666666;
          word-break: break-all;
        }
      }
    }
  }
  .product-manger-content--list {
    display: flex;
    flex-direction: column;
    align-items: center;
    width: calc(100% - 52rpx);
    // border: 2rpx solid #f00;
    margin: 328rpx 26rpx 26rpx;
    overflow: auto;
    .list-card {
      width: 100%;
      min-height: 274rpx;
      background: #ffffff;
      border-radius: 8rpx;
      margin-bottom: 26rpx;
      box-sizing: border-box;
      padding: 22rpx 20rpx 22rpx;
      .list-card-top {
        display: flex;
        gap: 20rpx;
        .list-card-top--left {
          width: 150rpx;
          height: 150rpx;
          flex-shrink: 0;
          border-radius: 7rpx;
          background: #d8d8d8;
          // text-align: center;
          image {
            width: 100%;
            height: 100%;
            border-radius: 7rpx;
          }
        }
        .list-card-top--right {
          flex: 1;

          .list-card-top--right-title {
            font-family: PingFangSC, PingFang SC;
            font-weight: 400;
            font-size: 26rpx;
            color: #333333;
            line-height: 37rpx;
            display: -webkit-box;
            -webkit-box-orient: vertical;
            -webkit-line-clamp: 1;
            overflow: hidden;
          }
          .list-card-top--right-description {
            font-family: PingFangSC, PingFang SC;
            font-weight: 400;
            font-size: 22rpx;
            color: #666666;
            line-height: 30rpx;
            word-break: break-all;
            display: flex;
            gap: 20rpx;
            justify-content: flex-start;
            padding: 13rpx 0 20rpx 0;
          }
          .list-card-top--right-description--left,
          .list-card-top--right-description--right {
            flex: 40%;
            .title {
              padding-right: 16rpx;
              font-size: 26rpx;
            }
            .mdikd {
              font-size: 26rpx;
            }
          }
          .list-card-top--right-price {
            font-family: PingFangSC, PingFang SC;
            .list-card-top--right-price--left {
              word-break: break-all;
              .price {
                font-weight: 600;
                font-size: 36rpx;
                color: #333333;
                line-height: 38rpx;
              }
            }
          }
        }
      }
      .list-card-bottom-btn {
        padding-top: 30rpx;
        .list-card-bottom-btn-list {
          display: flex;
          justify-content: flex-end;
          align-items: center;
          flex-wrap: wrap;
          gap: 20rpx;
          user-select: none;
          .list-card-bottom-btn-list--item {
            flex: 1;
            display: flex;
            justify-content: center;
            align-items: center;
            flex-wrap: wrap;
            width: 146rpx;
            white-space: nowrap;
            height: 60rpx;
            // border: 1rpx solid #e5e5e5;
            font-weight: 400;
            font-size: 24rpx;
            border-radius: 12rpx;
            color: #333333;
            transition: all 0.2s;

            &.edit-price {
              background: #fff;
              color: #007aff;
              // border: 1rpx solid #007aff;
            }

            &.set-activity {
              background: #007aff;
              color: white;
            }
            &.delete-activity {
              background: #f15314;
              color: white;
            }
            &.bohui-activity {
              background: #e9ca1d;
              color: white;
            }

            &:active {
              opacity: 0.8;
              transform: scale(0.98);
            }
          }
        }
      }
    }
  }
}
.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 {
  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>
