<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="form" class="demo-form-inline">
          <el-form-item v-if="storeList.length > 1" label="所属店铺">
            <el-select
              v-model="form.shopIdList"
              placeholder="请选择店铺"
              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 label="用户昵称">
            <el-input
              placeholder="请输入用户昵称"
              v-model="form.username"
            ></el-input>
          </el-form-item>
          <el-form-item label="会员等级">
            <el-select
              v-model="form.level"
              placeholder="请选择会员等级"
              clearable
            >
              <el-option
                v-for="item in memberLevelList"
                :key="item.level"
                :label="item.level"
                :value="item.level"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="注册时间">
            <el-date-picker
              v-model="form.registrationDate"
              type="date"
              placeholder="请选择注册日期"
              value-format="yyyy-MM-dd"
            >
            </el-date-picker>
          </el-form-item>
          <!-- <el-form-item label="生日">
            <el-date-picker
              v-model="value1"
              type="datetimerange"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            >
            </el-date-picker>
          </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="stat-list">
          <div class="stat-item">
            <i style="font-size: 22px" class="el-icon-user-solid"></i>
            <div class="stat-right">
              <div class="stat-value">
                <span style="font-size: 20px">{{
                  overviewList.totalCount
                }}</span>
              </div>
              <div class="stat-title">会员总数</div>
            </div>
          </div>
          <div class="stat-item">
            <i style="font-size: 22px" class="el-icon-s-custom"></i>
            <div class="stat-right">
              <div class="stat-value">
                <span style="font-size: 20px">{{
                  overviewList.todayCount
                }}</span>
              </div>
              <div class="stat-title">今日新增</div>
            </div>
          </div>
        </div>
        <!-- 测试按钮 -->
        <!-- <div class="test-buttons" style="margin-bottom: 10px;">
          <el-button type="success" size="small" @click="showTestDetail">
            测试查看会员详情样式
          </el-button>
        </div> -->
      </template>
    </obj-table-plus>
    <!-- 修改积分或成长值 -->
    <modifyPoints
      @queryList="$refs.oTable.reload()"
      ref="modifyPoints"
    ></modifyPoints>
    <!-- 查看详情 -->
    <viewDetails ref="viewDetails"></viewDetails>
  </div>
</template>

<script>
import modifyPoints from "./popup/modify-points.vue";
import viewDetails from "./popup/view-details.vue";
import { mapState } from "vuex";
export default {
  components: { viewDetails, modifyPoints },
  data() {
    return {
      dataList: [],
      formInline: {
        marketId: "",
        shopId: "",
        unitType: ""
      },
      form: {
        shopIdList: [], // 多选店铺列表
        username: "",
        mobile: "",
        level: "",
        registrationDate: ""
      },
      tableProp: {
        "auto-resize": true,
        border: true,
        height: "auto",
        "row-id": "id",
        "show-overflow": false
      },
      productFilterType: "SALE",
      selectList: [],
      overviewList: {},
      memberLevelList: [] // 会员等级列表
    };
  },
  created() {
    this.formInline = {
      unitType:
        JSON.parse(sessionStorage.getItem("userInfo")).role == "ROLE_MERCHANT"
          ? 3
          : 2,
      marketId: this.marketId,
      shopId: this.shopId
    };
    // 初始化店铺列表
    if (this.storeList.length > 0) {
      this.form.shopIdList = [this.shopId];
    }
    this.getMemberLevelList();
    this.$nextTick(() => {
      this.$refs.oTable.reload();
    });
  },
  methods: {
    // 获取会员等级列表
    getMemberLevelList() {
      const shopIdList =
        this.form.shopIdList && this.form.shopIdList.length > 0
          ? this.form.shopIdList
          : [this.shopId];

      this.$api.marketing
        .levelList({
          shopIdList: shopIdList
        })
        .then(res => {
          if (res.data.code === "200") {
            // 多个店铺取并集，去重
            const levelSet = new Set();
            const levels = res.data.data || [];
            levels.forEach(item => {
              if (item.level) {
                levelSet.add(item.level);
              }
            });
            this.memberLevelList = Array.from(levelSet).map(level => ({
              level
            }));
            console.log(this.memberLevelList);
          }
        })
        .catch(() => {
          this.memberLevelList = [];
        });
    },
    // 处理店铺选择变化
    handleShopChange() {
      this.getMemberLevelList();
    },
    // 手机号脱敏处理
    maskMobile(mobile) {
      if (!mobile || mobile.length !== 11) {
        return mobile;
      }
      return mobile.replace(/(\d{3})\d{4}(\d{4})/, "$1****$2");
    },
    queryList(pageNo, pageSize) {
      const queryParams = {
        pageNumber: pageNo,
        pageSize: pageSize,
        shopIdList:
          this.form.shopIdList && this.form.shopIdList.length > 0
            ? this.form.shopIdList
            : [this.shopId],
        username: this.form.username || "",
        mobile: this.form.mobile || "",
        level: this.form.level || "",
        registrationDate: this.form.registrationDate || ""
      };

      this.$api.marketing
        .marketingUserPage(queryParams)
        .then(res => {
          console.log(res);
          this.$refs.oTable.complete(
            res.data.data.data,
            Number(res.data.data.total)
          );
        })
        .catch(() => {
          this.$refs.oTable.complete(false);
        });

      // 调用概览接口
      const overviewParams = {
        shopIdList: queryParams.shopIdList,
        username: queryParams.username,
        mobile: queryParams.mobile,
        level: queryParams.level,
        registrationDate: queryParams.registrationDate
      };

      this.$api.marketing.overview(overviewParams).then(res => {
        this.overviewList = res.data.data;
      });
    },
    Reset() {
      this.form = {
        shopIdList: this.storeList.length > 0 ? [this.shopId] : [],
        username: "",
        mobile: "",
        level: "",
        registrationDate: ""
      };
      this.$nextTick(() => {
        this.$refs.oTable.reload();
      });
    },
    // 测试查看会员详情样式
    showTestDetail() {
      // 模拟会员数据
      const testMemberData = {
        userId: "3",
        username: "张三",
        mobile: "13812341234",
        birthday: "1990-05-15",
        headUrl:
          "https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png",
        levelName: "LV2",
        growthValue: 1250,
        memberPoints: 890,
        joinTime: "2023-01-15 10:30:00",
        registrationTime: "2023-01-15 10:30:00",
        id: 1 // 表示是会员
      };

      // 调用详情弹框
      this.$refs.viewDetails.toggle(testMemberData).add();
    }
  },
  computed: {
    tableCols() {
      return [
        { type: "checkbox", width: "60px", fixed: "left" },
        {
          title: "所属店铺",
          align: "center",
          field: "shopName"
        },
        {
          title: "用户ID",
          align: "center",
          field: "userId"
        },
        {
          title: "用户头像",
          align: "center",
          field: "headUrl",
          type: "jsx",
          render: ({ row }) => {
            return (
              <el-image
                style="width: 60px; height: 60px"
                src={row.headUrl}
                preview-src-list={[row.headUrl]}
              ></el-image>
            );
          }
        },
        {
          title: "用户昵称",
          align: "center",
          field: "username"
        },
        {
          title: "手机号",
          align: "center",
          field: "mobile",
          type: "jsx",
          render: ({ row }) => {
            return <span>{this.maskMobile(row.mobile)}</span>;
          }
        },
        {
          title: "会员等级",
          align: "center",
          field: "levelName",
          width: "120px",
          type: "jsx",
          render: ({ row }) => {
            if (!row.levelName) {
              return <span>-</span>;
            }
            // 根据等级名称设置不同颜色
            const getTagType = levelName => {
              if (levelName.includes("LV1") || levelName.includes("1"))
                return "";
              if (levelName.includes("LV2") || levelName.includes("2"))
                return "success";
              if (levelName.includes("LV3") || levelName.includes("3"))
                return "warning";
              if (levelName.includes("LV4") || levelName.includes("4"))
                return "danger";
              return "info";
            };
            return (
              <el-tag type={getTagType(row.levelName)} size="small">
                {row.levelName}
              </el-tag>
            );
          }
        },
        {
          title: "生日",
          align: "center",
          field: "birthday"
        },
        {
          title: "注册时间",
          align: "center",
          field: "registrationTime"
        },
        // {
        //   title: "限量",
        //   align: "center",
        //   field: "limitedNum",
        // },
        {
          title: "操作",
          fixed: "right",
          type: "jsx",
          align: "center",
          width: "100px",
          render: ({ row }) => {
            let viewDetails = () => {
              // 直接使用列表数据，不再调用memberUnitUserDetail接口
              this.$refs.viewDetails.toggle(row).add();
            };
            return (
              <div>
                <el-button size="mini" type="primary" onClick={viewDetails}>
                  详情
                </el-button>
              </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>
.stat-list {
  display: flex;
  align-items: center;
  /* justify-content: space-between; */
  // flex-wrap: wrap;
  margin-bottom: 10px;
  padding: 10px;
  border: 1px solid #ccc;
}
.stat-item {
  width: 30%;
  margin: 8px;
  display: flex;
  align-items: center;
}
.stat-right {
  margin-left: 12px;
  font-size: 18px;
}
.stat-title {
  margin-bottom: 5px;
}
</style>
