<template>
  <div class="level-setting">
    <!-- 摊铺选择 -->
    <div class="shop-selector" v-if="storeList.length > 1">
      <el-form :inline="true" :model="formInline" class="demo-form-inline">
        <el-form-item label="摊铺名称">
          <el-select
            v-model="formInline.shopIds"
            placeholder="请选择摊铺位名称..."
            style="width: 300px"
            multiple
            collapse-tags
            @change="handleShopChange"
          >
            <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>
          <el-button type="primary" @click="getList">查询</el-button>
          <el-button @click="handleBatchLevelSetting"
            >批量会员等级编辑</el-button
          >
        </el-form-item>
      </el-form>
    </div>

    <!-- 数据表格 -->
    <div class="table-container">
      <el-table :data="tableData" border style="width: 100%">
        <el-table-column
          prop="shopName"
          label="摊铺名称"
          width="140"
          align="center"
        >
        </el-table-column>
        <el-table-column label="是否启用会员" width="140" align="center">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.enable"
              @change="handleMemberToggle(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="levelInfo" label="会员等级" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.levelInfo">
              {{ scope.row.levelInfo }}
            </span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="140" align="center">
          <template slot-scope="scope">
            <el-button
              type="primary"
              size="mini"
              @click="handleLevelSetting(scope.row)"
            >
              设置等级明细
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script>
import { mapState } from "vuex";

export default {
  name: "LevelSetting",
  data() {
    return {
      formInline: {
        shopIds: []
      },
      tableData: []
    };
  },
  computed: {
    ...mapState("userData", ["storeList", "shopId", "marketId"])
  },
  created() {
    this.initData();
  },
  activated() {
    // 每次进入页面都刷新数据，确保数据是最新的
    this.getList();
  },
  methods: {
    initData() {
      // 如果storeList有数据，默认选择所有摊铺
      if (this.storeList && this.storeList.length > 0) {
        this.formInline.shopIds = this.storeList.map(store => store.shopId);
      }
      // 如果storeList没有数据但shopId有数据，则设置为shopId（支持只有一家店铺的情况）
      else if (this.shopId) {
        this.formInline.shopIds = [this.shopId];
      }
      // 否则设置为空数组
      else {
        this.formInline.shopIds = [];
      }
      this.getList();
    },

    getList() {
      // 根据选择的摊铺ID查询数据
      if (this.formInline.shopIds.length === 0) {
        this.tableData = [];
        return;
      }

      // 调用membershipEnableList接口
      this.$api.mer_admin
        .membershipEnableList({
          shopIdList: this.formInline.shopIds.join(",")
        })
        .then(res => {
          console.log("会员等级列表数据:", res);
          if (res.data && res.data.code == 200) {
            this.tableData = res.data.data || [];
          } else {
            this.$message.error(res.data?.message || "获取会员等级列表失败");
            this.tableData = [];
          }
        })
        .catch(err => {
          console.error("获取会员等级列表失败:", err);
          this.$message.error("获取会员等级列表失败");
          this.tableData = [];
        });
    },

    handleShopChange() {
      this.getList();
    },

    handleMemberToggle(row) {
      // 检查是否有ID字段，没有则提示先设置会员等级明细
      if (!row.id) {
        // 恢复开关状态
        row.enable = !row.enable;
        this.$message.warning("请先设置会员等级明细");
        return;
      }

      // 调用API更新状态
      this.$api.mer_admin
        .membershipEnableChange({
          id: row.id,
          enable: row.enable
        })
        .then(res => {
          console.log("修改会员状态响应:", res);
          if (res.data && res.data.code == 200) {
            this.$message.success(
              `${row.shopName} 会员功能已${row.enable ? "启用" : "禁用"}`
            );
            // 修改成功后刷新列表
            this.getList();
          } else {
            // 修改失败，恢复开关状态
            row.enable = !row.enable;
            this.$message.error(res.data?.message || "修改会员状态失败");
          }
        })
        .catch(err => {
          console.error("修改会员状态失败:", err);
          // 修改失败，恢复开关状态
          row.enable = !row.enable;
          this.$message.error("修改会员状态失败");
        });
    },

    // 关闭已打开的等级明细页面
    closeLevelDetailTab() {
      const mainTabs = this.$store.state.common.mainTabs;
      const filteredTabs = mainTabs.filter(
        tab => tab.name !== "marketing-level-detail"
      );
      this.$store.commit("common/updateMainTabs", filteredTabs);
    },

    handleLevelSetting(row) {
      // 先关闭已打开的等级明细页面
      this.closeLevelDetailTab();

      // 直接跳转到等级明细页面
      setTimeout(() => {
        this.$router.push({
          name: "marketing-level-detail",
          query: {
            shopId: row.shopId,
            shopName: row.shopName,
            id: row.id || null,
            timestamp: Date.now()
          }
        });
      }, 200);
    },

    handleBatchLevelSetting() {
      // 先关闭已打开的等级明细页面
      this.closeLevelDetailTab();

      setTimeout(() => {
        // 跳转到批量会员等级编辑页面，添加时间戳确保页面刷新
        this.$router.push({
          name: "marketing-level-detail",
          query: {
            mode: "batch", // 标识为批量编辑模式
            timestamp: Date.now() // 添加时间戳确保每次跳转都是新的
          }
        });
      }, 200);
    }
  }
};
</script>

<style lang="scss" scoped>
.level-setting {
  .shop-selector {
    margin-bottom: 20px;
    padding: 15px;
    background: #f5f5f5;
    border-radius: 4px;
  }

  .table-container {
    .el-table {
      .el-switch {
        margin: 0;
      }
    }
  }
}
</style>
