<template>
  <div style="height: calc(100vh - 200px)">
    <obj-table-plus
      ref="oTable"
      style="height: 100%"
      :tableCols="tableCols"
      :tableProp="tableProp"
      @query="queryList"
      v-model="dataList"
      :tableEvent="tableEvent"
      :enableAutoQuery="false"
    >
      <template slot="tableTop">
        <el-form :inline="true" :model="formInline" class="demo-form-inline">
          <el-form-item v-if="storeList.length > 1" label="商铺">
            <el-select
              v-model="formInline.shopIdList"
              placeholder="请选择商铺"
              multiple
              collapse-tags
              style="width: 200px"
            >
              <el-option
                v-for="item in storeList"
                :key="item.shopId"
                :label="item.shopName"
                :value="item.shopId"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="商品ID">
            <el-input
              placeholder="请输入商品ID"
              v-model="formInline.productId"
            ></el-input>
          </el-form-item>
          <el-form-item label="商品名称">
            <el-input
              placeholder="请输入商品名称"
              v-model="formInline.productName"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="$refs.oTable.reload()"
              >查询</el-button
            >
            <el-button type="primary" @click="reset">重置</el-button>
          </el-form-item>
        </el-form>
        <div class="mb-2">
          <el-button @click="add" type="primary" size="small">+添加</el-button>
        </div>
      </template>
    </obj-table-plus>
    <!-- 商品选择弹框 -->
    <product-selector
      :storeList="storeList"
      @success="$refs.oTable.reload()"
      ref="productSelector"
    ></product-selector>

    <!-- 积分商品配置弹框 -->
    <points-product-config
      @success="$refs.oTable.reload()"
      ref="pointsProductConfig"
    ></points-product-config>
    <!-- 查看详情 -->
    <!-- <viewDetails ref="viewDetails"></viewDetails> -->
  </div>
</template>

<script>
import ProductSelector from "./popup/product-selector.vue";
import PointsProductConfig from "./popup/points-product-config.vue";
import { mapState } from "vuex";
export default {
  components: {
    ProductSelector,
    PointsProductConfig
  },
  data() {
    return {
      dataList: [],
      formInline: {
        marketId: "",
        shopId: "",
        shopIdList: [],
        unitType: "",
        productId: "",
        productName: "",
        productSpecId: "",
        productSpecName: ""
      },
      tableProp: {
        "auto-resize": true,
        border: true,
        height: "auto",
        "row-id": "id",
        "show-overflow": false
      },
      productFilterType: "SALE",
      selectList: [],
      value1: []
    };
  },
  created() {
    this.formInline = {
      unitType:
        JSON.parse(sessionStorage.getItem("userInfo")).role == "ROLE_MERCHANT"
          ? 3
          : 2,
      marketId: this.marketId,
      shopId: this.shopId,
      shopIdList: [] // 初始为空，等待storeList加载完成后设置
    };
    this.$nextTick(() => {
      this.$refs.oTable.reload();
    });
  },
  watch: {
    // 监听storeList变化，设置默认选择所有店铺
    storeList: {
      handler(newStoreList) {
        if (
          newStoreList &&
          newStoreList.length > 0 &&
          this.formInline.shopIdList.length === 0
        ) {
          // 默认选择所有店铺
          this.formInline.shopIdList = newStoreList.map(store => store.shopId);
        }
      },
      immediate: true // 立即执行一次
    }
  },
  methods: {
    queryList(pageNo, pageSize) {
      // 使用新的积分商品分页接口
      const queryParams = {
        shopIdList: this.formInline.shopIdList || [],
        productId: this.formInline.productId || "",
        productName: this.formInline.productName || "",
        // productSpecId: this.formInline.productSpecId || "",
        // productSpecName: this.formInline.productSpecName || "",
        // 添加分页参数以备后续使用
        pageNumber: pageNo,
        pageSize: pageSize
      };

      this.$api.marketing
        .membershipPointsProductPage(queryParams)
        .then(res => {
          console.log(res);
          this.$refs.oTable.complete(
            res.data.data.data || [],
            Number(res.data.data.total || 0)
          );
        })
        .catch(err => {
          console.error("查询积分商品失败:", err);
          this.$refs.oTable.complete(false);
        });
    },
    add() {
      // 传递选中的商铺列表，如果没有选择则传递当前shopId
      const shopIdList =
        this.formInline.shopIdList && this.formInline.shopIdList.length > 0
          ? this.formInline.shopIdList
          : this.formInline.shopId
          ? [this.formInline.shopId]
          : [];
      this.$refs.productSelector.show(shopIdList);
    },
    handleEnableChange(row) {
      // 使用编辑接口进行启用状态切换
      const updateData = {
        id: row.id,
        exchangeRequiredPoints: row.exchangeRequiredPoints,
        increaseInventory: 0, // 默认为0
        exchangeRequiredAmount: row.exchangeRequiredAmount || 0,
        enable: row.enable // 使用当前的启用状态
      };

      this.$api.marketing
        .updateMembershipPointsProduct(updateData)
        .then(() => {
          this.$message.success("状态切换成功");
          this.$refs.oTable.reload();
        })
        .catch(err => {
          console.error("状态切换失败:", err);
          this.$message.error("状态切换失败");
          // 恢复原状态
          row.enable = !row.enable;
        });
    },
    reset() {
      this.formInline = {
        unitType:
          JSON.parse(sessionStorage.getItem("userInfo")).role == "ROLE_MERCHANT"
            ? 3
            : 2,
        marketId: this.marketId,
        shopId: this.shopId,
        shopIdList: this.storeList.map(store => store.shopId), // 重置时也选择所有店铺
        productId: "",
        productName: "",
        productSpecId: "",
        productSpecName: ""
      };
      this.$refs.oTable.reload();
    }
  },
  computed: {
    tableCols() {
      return [
        { type: "checkbox", width: "60px", fixed: "left" },
        // { type: "seq", width: "60px", align: "center", title: "序号" },
        {
          title: "商品ID",
          align: "center",
          field: "productId"
        },
        {
          title: "商品名称",
          align: "center",
          field: "productName"
        },
        // {
        //   title: "商品规格ID",
        //   align: "center",
        //   field: "productSpecId"
        // },
        {
          title: "规格名称",
          align: "center",
          field: "productSpecName"
        },
        {
          title: "归属店铺",
          align: "center",
          field: "shopName"
        },
        {
          title: "商品原价",
          align: "center",
          field: "marketPrice",
          type: "jsx",
          render: ({ row }) => {
            return <span>¥{row.marketPrice}</span>;
          }
        },
        {
          title: "原有商品状态",
          align: "center",
          field: "productStatus",
          type: "jsx",
          render: ({ row }) => {
            return <span>{row.productStatus === "UP" ? "上架" : "下架"}</span>;
          }
        },
        {
          title: "积分使用模式",
          align: "center",
          field: "exchangePointsType",
          type: "jsx",
          render: ({ row }) => {
            return (
              <span>
                {row.exchangePointsType === 1 ? "积分换购" : "积分优惠购"}
              </span>
            );
          }
        },
        {
          title: "剩余库存",
          align: "center",
          field: "surplusInventory"
        },
        {
          title: "启用状态",
          align: "center",
          field: "enable",
          type: "jsx",
          render: ({ row }) => {
            return (
              <el-switch
                v-model={row.enable}
                onChange={() => this.handleEnableChange(row)}
              ></el-switch>
            );
          }
        },
        {
          title: "操作",
          fixed: "right",
          type: "jsx",
          align: "center",
          width: "200px",
          render: ({ row }) => {
            let edit = () => {
              // 直接使用列表数据，不调用详情接口
              const productData = {
                productId: row.productId,
                productName: row.productName,
                shopName: row.shopName,
                productSpecName: row.productSpecName,
                productSpecId: row.productSpecId,
                attributeValue: row.productSpecName,
                marketPrice: row.marketPrice,
                surplusInventory: row.surplusInventory
              };

              // 直接使用列表中的数据作为编辑数据
              const editData = {
                id: row.id,
                shopId: row.shopId,
                productId: row.productId,
                productSpecId: row.productSpecId,
                attributeValue: row.productSpecName,
                marketPrice: row.marketPrice,
                exchangeRequiredPoints: row.exchangeRequiredPoints,
                exchangeInventory: row.exchangeInventory,
                exchangeRestrictions: row.exchangeRestrictions,
                exchangeRestrictionsType: row.exchangeRestrictionsType
              };

              this.$refs.pointsProductConfig.show(productData, editData);
            };
            let deleteProduct = () => {
              this.$api.marketing
                .deleteMembershipPointsProduct({ id: row.id })
                .then(res => {
                  this.$message.success("删除成功");
                  this.$refs.oTable.reload();
                })
                .catch(err => {
                  console.error("删除积分商品失败:", err);
                  this.$message.error("删除失败");
                });
            };
            return (
              <div>
                <el-button
                  style="margin-right:10px"
                  size="mini"
                  type="primary"
                  onClick={edit}
                >
                  编辑
                </el-button>
                <el-popconfirm
                  confirm-button-text="确定"
                  cancel-button-text="取消"
                  icon="el-icon-info"
                  icon-color="red"
                  onConfirm={deleteProduct}
                  title="确定删除吗？"
                >
                  <el-button size="mini" slot="reference" type="danger">
                    删除
                  </el-button>
                </el-popconfirm>
              </div>
            );
          }
        }
      ];
    },
    tableEvent() {
      return {
        "checkbox-all": ({ records, reserves }) => {
          this.selectList = [...records, ...reserves];
        },
        "checkbox-change": ({ records, reserves }) => {
          this.selectList = [...records, ...reserves];
        }
      };
    },
    ...mapState("userData", [
      "isMerchant",
      "marketList",
      "storeList",
      "marketId",
      "shopId"
    ])
  }
};
</script>

<style lang="scss" scoped></style>
