<template>
  <div class="luckDraw">
    <div class="luckDraw_title">
      <span class="text">中奖名单</span>
    </div>
    <div class="luckDraw_select">
      <el-date-picker
        v-model="form.rflDate"
        type="date"
        placeholder="请选择中奖日期"
      >
      </el-date-picker>
      <el-button type="primary" @click="selectClick" :loading="selectLoading">
        <i class="el-icon-search"></i> 查询
      </el-button>
      <el-button type="primary" @click="menuExport" :loading="downloadLoading">
        <i class="el-icon-document"></i> 导出(Excel)
      </el-button>
    </div>
    <div class="luckDraw_table">
      <el-table
        ref="tab"
        :data="tableData"
        style="width: 100%"
        border
        :height="height"
        :stripe="true"
        :highlight-current-row="false"
        :row-style="tableRowStyle"
        :header-cell-style="tableHeaderColor"
        :loading="tableLoading"
        element-tableLoading-text="玩命加载中"
        element-tableLoading-spinner="el-icon-tableLoading"
        size="mini"
      >
        <el-table-column type="index" label="序号" fixed="left" width="50">
        </el-table-column>
        <el-table-column
          sortable
          v-for="(item, i) in tablehead"
          :key="i"
          :prop="item.prop"
          :label="item.label"
          :min-width="item.width || width"
        >
        </el-table-column>
      </el-table>
      <div class="fy">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="pageSizes"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          :hide-on-single-page="true"
        >
        </el-pagination>
      </div>
    </div>
  </div>
</template>

<script>
import luckDrawTableHead from "./luckDrawTableHead";
import { renderTime, sjTime } from "@/utils/sharedJsFile";
export default {
  data() {
    return {
      //查询按钮的状态
      selectLoading: false,
      //导出按钮的状态
      downloadLoading: false,
      //导出excel文件的名字
      tableTitle: "中奖名单",
      //表格的高度
      height: null,
      //表格的每一列的宽度,若没有再表头设置则采用
      width: 150,
      //总条目数
      total: null,
      //每页显示条目个数
      pageSize: 100,
      //每一页面的显示的条目个数数组
      pageSizes: [5, 100, 200, 300],
      //当前页数
      currentPage: 1,
      //表格的加载状态
      tableLoading: false,
      //查询条件
      form: {
        rflDate: new Date(),
      },
      //表格渲染的数据
      tableData: [],
      //表格的表头数据
      tablehead: [],
    };
  },
  created() {
    this.tablehead = luckDrawTableHead.luckDrawTableHead;
    //动态监听页面的高度，如果改变则改变
    window.addEventListener("resize", this.getHeight);
    this.getHeight();
    this.initialization();
  },
  methods: {
    menuExport() {
      if (this.tableData.length < 1) {
        this.$message.error("当前无数据可供导出!");
        return false;
      }
      let data = [];
      let i = 0;
      this.tableData.forEach((e) => {
        i++;
        data.push({
          序号: i,
          单位: e.empDept,
          工号: e.empNo,
          姓名: e.empName,
          电话号码: e.cellPhoneNo,
          中奖等级: e.prizeDesc,
          中奖时间: e.rflDate,
        });
      });
      // 表格标题
      var dataTitle = this.tableTitle;
      // 配置文件类型
      const wopts = {
        bookType: "xlsx",
        bookSST: true,
        type: "binary",
        cellStyles: true,
      };
      this.downloadExl(data, wopts, dataTitle);
    },
    downloadExl(json, type, dataTitle) {
      // 设置表格中cell默认的字体，居中，颜色等
      var defaultCellStyle = {
        // font: {
        //     name: "宋体", sz: 11, color: { auto: 1 } ,
        // },
        // border: {
        //     color: { auto: 1 },
        //     top: { style: 'thin' },
        //     bottom: { style: 'thin'},
        //     left: { style: 'thin' },
        //     right: { style: 'thin' }
        // },
        alignment: {
          /// 自动换行
          wrapText: 1,
          // 居中
          horizontal: "center",
          vertical: "center",
          indent: 0,
        },
      };
      var tmpdata = json[0];
      json.unshift({});
      var keyMap = []; // 获取keys
      for (var k in tmpdata) {
        keyMap.push(k);
        json[0][k] = k;
      }
      var tmpdata = []; // 用来保存转换好的json
      json
        .map((v, i) => {
          let data = keyMap.map((k, j) => {
            return Object.assign(
              {},
              {
                v: v[k],
                position:
                  (j > 25 ? this.getCharCol(j) : String.fromCharCode(65 + j)) +
                  (i + 2),
              }
            );
          });
          return data;
        })
        .reduce((prev, next) => prev.concat(next))
        .forEach(
          (v, i) =>
            (tmpdata[v.position] = {
              v: v.v,
              s: defaultCellStyle,
            })
        );
      var outputPos = Object.keys(tmpdata); // 设置区域,比如表格从A1到D10
      tmpdata["A1"] = { v: dataTitle };
      outputPos = ["A1"].concat(outputPos);
      tmpdata["A1"].s = {
        font: { sz: 14, bold: true, vertAlign: true },
        alignment: { vertical: "center", horizontal: "center" },
      }; // <====设置xlsx单元格样式  fill: { bgColor: { rgb: "E8E8E8"}, fgColor: { rgb: "E8E8E8" } }
      tmpdata["!merges"] = [
        {
          s: { c: 0, r: 0 },
          e: { c: 6, r: 0 },
        },
      ]; // <====合并单元格
      tmpdata["!cols"] = [
        { wpx: 50 },
        { wpx: 150 },
        { wpx: 80 },
        { wpx: 80 },
        { wpx: 100 },
        { wpx: 80 },
        { wpx: 100 },
      ]; // <====设置一列宽度

      var tmpWB = {
        SheetNames: ["mySheet"], // 保存的表标题
        Sheets: {
          mySheet: Object.assign(
            {},
            tmpdata, // 内容
            {
              "!ref": outputPos[0] + ":" + outputPos[outputPos.length - 1], // 设置填充区域
            }
          ),
        },
      };
      var tmpDown = new Blob(
        [
          this.s2ab(
            XLSX.write(
              tmpWB,
              // 这里的数据是用来定义导出的格式类型
              {
                bookType: type == undefined ? "xlsx" : type.bookType,
                bookSST: false,
                type: "binary",
              },
              { defaultCellStyle: this.defaultCellStyle }
            )
          ),
        ],
        {
          type: "",
        }
      );
      this.saveAs(
        tmpDown,
        this.tableTitle +
          "." +
          (type.bookType == "biff2" ? "xls" : type.bookType)
      );
    },
    // 获取26个英文字母用来表示excel的列
    getCharCol(n) {
      let temCol = "",
        s = "",
        m = 0;
      while (n > 0) {
        m = (n % 26) + 1;
        s = String.fromCharCode(m + 64) + s;
        n = (n - m) / 26;
      }
      return s;
    },
    s2ab(s) {
      if (typeof ArrayBuffer !== "undefined") {
        var buf = new ArrayBuffer(s.length);
        var view = new Uint8Array(buf);
        for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xff;
        return buf;
      } else {
        var buf = new Array(s.length);
        for (var i = 0; i != s.length; ++i) buf[i] = s.charCodeAt(i) & 0xff;
        return buf;
      }
    },
    // 下载功能
    saveAs(obj, fileName) {
      var tmpa = document.createElement("a");
      tmpa.download = fileName || "未命名";
      // 兼容ie
      if ("msSaveOrOpenBlob" in navigator) {
        window.navigator.msSaveOrOpenBlob(obj, this.tableTitle + ".xlsx");
      } else {
        tmpa.href = URL.createObjectURL(obj);
      }
      tmpa.click();
      setTimeout(function () {
        URL.revokeObjectURL(obj);
      }, 100);
    },

    getHeight() {
      this.height = window.innerHeight - 200;
    },
    initialization() {
      this.axios
        .get(
          "/icore.icp.web/game/v1/rflemplotterys/?rflDate=&pageNum=" +
            this.currentPage +
            "&pageSize=" +
            this.pageSize +
            "&lotteryResult=1"
        )
        .then((res) => {
          this.tableData = res.data.data.list;
          this.total = res.data.data.total;
        });
    },
    //查询事件
    selectClick() {
      this.selectLoading = true;
      let Time = renderTime(sjTime(this.form.rflDate)).slice(0, 10);
      this.axios
        .get(
          "/icore.icp.web/game/v1/rflemplotterys/?rflDate=" +
            Time +
            "&pageNum=" +
            this.currentPage +
            "&pageSize=" +
            this.pageSize +
            "&lotteryResult=1"
        )
        .then((res) => {
          this.tableData = res.data.data.list;
          this.total = res.data.data.total;
        });
      this.selectLoading = false;
    },
    //行间样式
    tableRowStyle() {
      return "background-color:#CCF1FF;color:#000;text-align:center;height:10px";
    },
    //表头样式
    tableHeaderColor() {
      return "background-color:#0C2278;color:#fff;text-align:center;height:20px";
    },
    changeList() {
      this.initialization();
      this.tableLoading = false;
    },
    handleSizeChange(val) {
      this.tableLoading = true;
      this.pageSize = val;
      this.changeList();
    },
    handleCurrentChange(val) {
      this.tableLoading = true;
      this.currentPage = val;
      this.changeList();
    },
    exportData() {
      if (this.tableData.length) {
        let tHeader = [];
        let filterVal = [];
        this.tablehead.filter((item, i) => {
          tHeader.push(item.label);
          filterVal.push(item.prop);
        });
        this.export2Excel(tHeader, filterVal, this.tableData);
      } else {
        this.$alert("没有查询到数据，不能使用导出功能", "提示", {
          confirmButtonText: "确定",
          callback: (action) => {},
        });
      }
    },
    export2Excel(tHeader, filterVal, dataTabel) {
      var that = this;
      this.downloadLoading = true;
      require.ensure([], () => {
        const {
          export_json_to_excel,
        } = require("@/assets/excel/Export2Excel.js"); //这里必须使用绝对路径，使用@/+存放export2Excel的路径
        let list = dataTabel;
        let data = that.formatJson(filterVal, list);
        export_json_to_excel(tHeader, data, that.tableTitle); // 导出的表格名称
      });
      this.downloadLoading = false;
    },
    //3.格式转换
    formatJson(filterVal, jsonData) {
      return jsonData.map((v) => filterVal.map((j) => v[j]));
    },
    a() {
      this.height = null;
    },
  },
  beforeDestroy() {
    document.removeEventListener("resize", this.a);
    this.a();
  },
};
</script>

<style lang="scss">
.luckDraw {
  .luckDraw_title {
    width: 100%;
    height: 100px;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 46px;
    font-weight: 900;
    color: red;
  }
  .luckDraw_select {
    display: flex;
    align-items: center;
    width: 100%;
    height: 60px;
    padding-left: 50px;
    .el-input {
      width: 200px;
      margin-right: 20px;
    }
  }
  .fy {
    display: flex;
    align-items: center;
    height: 40px;
    width: 100%;
  }
}
</style>