<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="formInline.shopId" placeholder="请选择店铺">
              <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="form.userId"
            ></el-input>
          </el-form-item>
          <el-form-item label="用户昵称">
            <el-input
              placeholder="请输入用户昵称"
              v-model="form.username"
            ></el-input>
          </el-form-item>
          <el-form-item label="会员等级id">
            <el-input
              placeholder="请输入会员等级id"
              v-model="form.levelId"
            ></el-input>
          </el-form-item>
          <el-form-item label="手机号">
            <el-input
              placeholder="请输入手机号"
              v-model="form.mobile"
            ></el-input>
          </el-form-item>
          <el-form-item label="会员状态">
            <el-select v-model="form.isMemberUser" placeholder="请选择会员状态">
              <el-option
                v-for="item in [
                  { label: '是', value: 1 },
                  { label: '否', value: 0 },
                ]"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="注册时间">
            <el-date-picker
              @change="changeTime"
              value-format="yyyy-MM-dd HH:mm:ss"
              v-model="value1"
              type="datetimerange"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            >
            </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-title">用户数量（人）</div>
              <div class="stat-value">
                <span style="font-size: 20px">{{
                  overviewList.totalCount
                }}</span>
              </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-title">今日新增（人）</div>
              <div class="stat-value">
                <span style="font-size: 20px">{{
                  overviewList.todayCount
                }}</span>
              </div>
            </div>
          </div>
        </div>
        <div class="mb-2">
          <el-button type="success" size="small" @click="userExport"
            >导出</el-button
          >
        </div>
      </template>
    </obj-table-plus>
    <!-- 修改积分或成长值 -->
    <modifyPoints
      @queryList="$refs.oTable.reload()"
      ref="modifyPoints"
    ></modifyPoints>
    <!-- 查看详情 -->
    <viewDetails ref="viewDetails"></viewDetails>
  </div>
</template>

<script>
import * as XLSX from "xlsx";
import { saveAs } from "file-saver";
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: {},
      tableProp: {
        "auto-resize": true,
        border: true,
        height: "auto",
        "row-id": "id",
        "show-overflow": false,
      },
      productFilterType: "SALE",
      selectList: [],
      value1: [],
      overviewList: {},
    };
  },
  created() {
    this.formInline = {
      unitType:
        JSON.parse(sessionStorage.getItem("userInfo")).role == "ROLE_MERCHANT"
          ? 3
          : 2,
      marketId: this.marketId,
      shopId: this.shopId,
    };
    this.$nextTick(() => {
      this.$refs.oTable.reload();
    });
  },
  methods: {
    // getData() {
    //   this.$api.mer_admin
    //     .storeList({ marketId: this.formInline.marketId })
    //     .then((res) => {
    //       this.storeList = res.data.data;
    //         this.formInline.shopId = res.data.data[0].shopId;
    //       this.$nextTick(() => {
    //         this.$refs.oTable.reload();
    //       });
    //     });
    // },
    queryList(pageNo, pageSize) {
      this.$api.marketing
        .marketingUserPage({
          pageNumber: pageNo,
          pageSize: pageSize,
          ...this.formInline,
          ...this.form,
        })
        .then((res) => {
          console.log(res);
          this.$refs.oTable.complete(
            res.data.data.data,
            Number(res.data.data.total)
          );
        })
        .catch((err) => {
          this.$refs.oTable.complete(false);
        });
      this.$api.marketing
        .overview({ ...this.formInline, ...this.form })
        .then((res) => {
          this.overviewList = res.data.data;
        });
    },
    Reset() {
      this.form = {};
      this.$nextTick(() => {
        this.$refs.oTable.reload();
      });
    },
    changeTime(val) {
      if (val) {
        this.form.startRegistrationTime = val[0];
        this.form.endRegistrationTime = val[1];
      } else {
        this.form.startRegistrationTime = "";
        this.form.endRegistrationTime = "";
      }
    },
    async userExport() {
      let now = new Date();
      let year = now.getFullYear();
      let month = now.getMonth() + 1;
      let day = now.getDate();
      let res = await this.$api.marketing.marketingUserPage({
        pageNumber: 1,
        pageSize: 9999999,
        ...this.formInline,
        ...this.form,
      });
      console.log(res);
      let userData = res.data.data.data.map((item) => {
        return {
          用户ID: item.userId,
          用户头像: item.headUrl,
          用户昵称: item.username,
          手机号: item.mobile,
          会员等级id: item.levelId,
          会员等级名称: item.levelName,
          生日: item.birthday,
          注册时间: item.registrationTime,
        };
      });

      const workbook = XLSX.utils.book_new();
      const worksheet = XLSX.utils.json_to_sheet(userData);

      XLSX.utils.book_append_sheet(workbook, worksheet, "用户管理");
      const excelData = XLSX.write(workbook, {
        type: "array",
        bookType: "xlsx",
      });
      const blob = new Blob([excelData], { type: "application/octet-stream" });
      saveAs(blob, `用户管理-${year + "" + month + day}.xlsx`);
    },
  },
  computed: {
    tableCols() {
      return [
        { type: "checkbox", width: "60px", fixed: "left" },
        // { type: "seq", width: "60px", align: "center", title: "序号" },
        {
          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",
        },
        // {
        //   title: "进行中订单数",
        //   align: "center",
        //   field: "name",
        // },
        // {
        //   title: "完成订单数",
        //   align: "center",
        //   field: "name",
        // },
        // {
        //   title: "消费金额（元）",
        //   align: "center",
        //   field: "name",
        // },
        {
          title: "会员等级id",
          align: "center",
          field: "levelId",
        },
        {
          title: "会员等级名称",
          align: "center",
          field: "levelName",
        },
        {
          title: "生日",
          align: "center",
          field: "birthday",
        },
        {
          title: "注册时间",
          align: "center",
          field: "registrationTime",
        },
        // {
        //   title: "限量",
        //   align: "center",
        //   field: "limitedNum",
        // },
        {
          title: "操作",
          fixed: "right",
          type: "jsx",
          align: "center",
          width: "280px",
          render: ({ row }) => {
            let viewDetails = () => {
              this.$api.marketing
                .memberUnitUserDetail({
                  ...this.formInline,
                  userId: row.userId,
                })
                .then((res) => {
                  console.log(res);
                  this.$refs.viewDetails.toggle(res.data.data).add();
                });
            };
            let points = () => {
              this.$api.marketing
                .memberUnitUserDetail({
                  ...this.formInline,
                  userId: row.userId,
                })
                .then((res) => {
                  console.log(res);
                  this.$refs.modifyPoints.toggle(res.data.data).add();
                });
            };
            let growthValue = () => {
              this.$api.marketing
                .memberUnitUserDetail({
                  ...this.formInline,
                  userId: row.userId,
                })
                .then((res) => {
                  console.log(res);
                  this.$refs.modifyPoints.toggle(res.data.data).update();
                });
            };
            return (
              <div>
                <el-button size="mini" type="primary" onClick={viewDetails}>
                  详情
                </el-button>
                <el-button
                  v-show={!row.id}
                  size="mini"
                  type="primary"
                  onClick={points}
                >
                  修改积分
                </el-button>
                <el-button
                  v-show={!row.id}
                  size="mini"
                  type="primary"
                  onClick={growthValue}
                >
                  修改成长值
                </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: 20px 20px;
  display: flex;
  align-items: center;
}
.stat-right {
  margin-left: 12px;
  font-size: 18px;
}
.stat-title {
  margin-bottom: 5px;
}
</style>