<template>
  <div class="pa-2">
    <el-row>
      <el-col :span="24">
        <div class="d-flex justify-space-between">
          <div>
            <el-button type="primary" size="mini" class="importBtn" @click="comparisonMethods">比对表格</el-button>
            <el-select v-model="filterFields" size="mini" collapse-tags multiple placeholder="请选择对比条件">
              <el-option v-for="item in filterFieldsList" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </div>
          <div>
            <el-switch v-model="batchOperation" active-text="批量操作">
            </el-switch>
          </div>
        </div>
      </el-col>
    </el-row>
    <el-divider></el-divider>
    <el-row :gutter="20">
      <el-col :span="12">
        <el-divider>需要上传人员表</el-divider>
        <el-col :span="24" class="mb-5">
          <input class="input-file" type="file" @change="exportData"
            accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" />
          <el-button type="primary" @click="btnClick" size="mini">导入EXCEL</el-button>
          <el-button size="mini" class="importBtn" @click="exportBtn">下载模板</el-button>
          <el-button size="mini" @click="deleteSelect">批量移除</el-button>
          <el-button size="mini" @click="clearAll">清空</el-button>
        </el-col>
        <el-table :data="userlist" border stripe class="table" ref="multipleTable" header-cell-class-name="table-header"
          @selection-change="handleSelectionChange" height="400">
          <el-table-column type="selection" width="55">
          </el-table-column>
          <el-table-column prop="name" label="名称"></el-table-column>
          <el-table-column prop="number" label="学号"></el-table-column>
          <el-table-column prop="cardId" label="卡号"></el-table-column>
          <el-table-column prop="phone" label="手机号"></el-table-column>
          <el-table-column prop="siteName" label="绑定房间"></el-table-column>
          <el-table-column label="性别" align="center">
            <template #default="scope">
              {{ scope.row.sex == 1 ? "男" : "女" }}
            </template>
          </el-table-column>
          <el-table-column label="门卡状态" align="center">
            <template #default="scope">
              <span v-if="scope.row.cardState == 1">正常</span>
              <span v-if="scope.row.cardState == 2">挂失</span>
              <span v-if="scope.row.cardState == 3">挂失冻结</span>
              <span v-if="scope.row.cardState == 4">冻结</span>
              <span v-if="scope.row.cardState == 5">预开户</span>
              <span v-if="scope.row.cardState == 6">过期</span>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
      <el-col :span="12">
        <el-divider>现有人员表</el-divider>
        <el-col :span="24" class="mb-5">
          <input class="input-file input-fileOne" type="file" @change="exportDataOne"
            accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" />
          <el-button type="primary" @click="btnClickOne" size="mini">导入EXCEL</el-button>
          <el-button size="mini" @click="clearAllOne">清空</el-button>
        </el-col>
        <el-table :data="userlistOne" border stripe class="table" ref="multipleTable"
          header-cell-class-name="table-header" @selection-change="handleSelectionChangeOne" height="400">
          <el-table-column type="selection" width="55">
          </el-table-column>
          <el-table-column prop="name" label="名称"></el-table-column>
          <el-table-column prop="number" label="学号"></el-table-column>
          <el-table-column prop="cardId" label="卡号"></el-table-column>
          <el-table-column prop="phone" label="手机号"></el-table-column>
          <el-table-column prop="siteName" label="绑定房间"></el-table-column>
          <el-table-column label="性别" align="center">
            <template #default="scope">
              {{ scope.row.sex == 1 ? "男" : "女" }}
            </template>
          </el-table-column>
          <el-table-column label="门卡状态" align="center">
            <template #default="scope">
              <span v-if="scope.row.cardState == 1">正常</span>
              <span v-if="scope.row.cardState == 2">挂失</span>
              <span v-if="scope.row.cardState == 3">挂失冻结</span>
              <span v-if="scope.row.cardState == 4">冻结</span>
              <span v-if="scope.row.cardState == 5">预开户</span>
              <span v-if="scope.row.cardState == 6">过期</span>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>
    <el-row :gutter="20" class="mt-4">
      <el-divider>对比结果</el-divider>
      <el-col :span="24">
        <el-col :span="24" class="mb-5">
          <el-button type="primary" @click="batchUploadfun" size="mini">确认上传</el-button>
          <el-date-picker v-model="dateTime" size="mini" type="datetimerange" range-separator="至"
            start-placeholder="开始日期" end-placeholder="结束日期">
          </el-date-picker>
          <el-button size="mini" @click="clearAllTwo">清空</el-button>
        </el-col>
        <el-table :data="userlistTwo" border class="table" ref="multipleTable" header-cell-class-name="table-header"
          :row-class-name="tableRowClassName" @selection-change="handleSelectionChangeTwo" height="400">
          <el-table-column type="selection" width="55" :selectable="checkboxInit">
          </el-table-column>
          <el-table-column prop="name" label="名称"></el-table-column>
          <el-table-column prop="number" label="学号"></el-table-column>
          <el-table-column prop="cardId" label="卡号"></el-table-column>
          <el-table-column prop="phone" label="手机号"></el-table-column>
          <el-table-column prop="siteName" label="绑定房间"></el-table-column>
          <el-table-column label="性别" align="center">
            <template #default="scope">
              {{ scope.row.sex == 1 ? "男" : "女" }}
            </template>
          </el-table-column>
          <el-table-column label="门卡状态" align="center">
            <template #default="scope">
              <span v-if="scope.row.cardState == 1">正常</span>
              <span v-if="scope.row.cardState == 2">挂失</span>
              <span v-if="scope.row.cardState == 3">挂失冻结</span>
              <span v-if="scope.row.cardState == 4">冻结</span>
              <span v-if="scope.row.cardState == 5">预开户</span>
              <span v-if="scope.row.cardState == 6">过期</span>
            </template>
          </el-table-column>
          <el-table-column prop="nfc" label="卡片"></el-table-column>
        </el-table>
      </el-col>
    </el-row>
  </div>
</template>

<script>
  import {
    httpPost,
    download,
    httpGet,
    httgetaxio1
  } from "../../api/index.js";
  import RequestSet from "../../api/allFun.js";
  import ICINLocker from "../../utils/equipment.js"
  import XLSX from "xlsx";
  import {
    getcurrentTime1,
    dec2hex,
    group,
  } from "../../utils/index";
  import utils from "../../utils/util.js";
  import moment from 'moment'
  let nowDate = new Date()
  var currentTime = nowDate
  var endcurrentTime = getcurrentTime1(6)
  export default {
    name: "contrast",
    data() {
      return {
        dateTime: [currentTime, endcurrentTime],
        batchOperation: false,
        userlist: [],
        userlistOne: [],
        userlistTwo: [],
        multipleSelection: [],
        multipleSelectionOne: [],
        multipleSelectionTwo: [],
        filterFields: [],
        filterFieldsList: [{
            value: 'name',
            label: '名称'
          },
          {
            value: 'number',
            label: '学号'
          },
          {
            value: 'cardId',
            label: '卡号'
          },
          {
            value: 'phone',
            label: '手机号'
          },
          {
            value: 'sex',
            label: '性别'
          },
          {
            value: 'cardState',
            label: '门卡状态'
          }
        ],
        deviceList: [],
        allCertificates:[]
      }
    },
    created() {
      this.getDevice()
      this.getCertificatesSort()
    },
    methods: {
      checkboxInit(row, index) {
        if (row.color == 'bgred') {
          return 0;
        } else if (row.color == '') {
          return 1;
        }
      },
      tableRowClassName({
        row,
        rowIndex
      }) {
        if (row.color == 'bgred') {
          return 'warning-row';
        } else if (row.color == '') {
          return 'success-row';
        }
        return '';
      },
      getDevice() {
        var data = {
          q: JSON.stringify({
            lockType: 1
          }),
          pageNum: 0,
          pageSize: 0,
        };
        httpPost(data, this.$api.getDeviceItems).then((res) => {
          if (res.code == 200) {
            this.deviceList = res.data.list
          }
        })
      },
      // 批量删除
      deleteSelect() {
        // this.
      },
      // 获取凭证名称
      getCertificatesSort(){
          var dataall = {
            pageNum: 0,
            pageSize: 0,
            orderBy: "create_at desc",
            q: {
              inStatus: "0,1",
              types: "13"
            },
          }
          httpGet(dataall, this.$api.getCertificates).then((resall) => {
            if(resall.code==200){
              var sendOn = utils.zlib_unzip(resall.data)
              this.allCertificates=sendOn
            }
          })
      },
      // 上传对比结果
      async batchUploadfun() {
        var _this=this
        if (this.dateTime[0] == '' || this.dateTime[1] == '') {
          this.$message.error("请选择开始结束时间")
          return false;
        }
        if (this.multipleSelectionTwo.length > 0) {
          this.multipleSelectionTwo.map(li => {
            var fjid = [];
            var str = {
              cardId: li.id,
              siteId: li.roomId,
              startTime: this.dateTime[0],
              endTime: this.dateTime[1]
            };
            fjid.push(str)
            var infostr = JSON.parse(li.info);
            if (li.manufactureId == 201|| li.manufactureId == 221) {
              var data = {
                lockerId: li.deviceNum,
                imei: li.imei,
                lockerUserId: infostr.userPassword,
                keyId: infostr.userPassword,
                role: 0,
                action: 1,
                order: 6226,
                cardName: li.name,
                roomName: li.siteName,
                pzname:'NFC'+li.num
              };
              ICINLocker.addUserToLock(data.lockerId, data.imei, data
                .lockerUserId, data.role, data.action, data.order, data.cardName, data
                .roomName, (
                  callback) => {
                  if (callback.success) {
                    var locakUserdata = {
                      deviceNum: li.deviceNum,
                      imei: li.imei,
                      cardId: li.id,
                      content: JSON.stringify(
                        data
                      ), //operateMode:NFC-10、把人员添加到凭证-1
                      type: 26,
                      serial: callback.data.serialNumber,
                      startTime:parseInt(_this.dateTime[0].getTime() / 1000),
                      endTime:parseInt(_this.dateTime[1].getTime() / 1000),
                    }
                    utils.sendLockUser(locakUserdata, (callbackLOCK) => {

                    })
                    if (li.nfc.length == 8) {
                      li.nfc = utils.cardFormatConversion(li.nfc)
                      li.nfc = li.nfc + '00000000'
                    } else if (li.nfc.length == 16) {
                      password = li.nfc
                    }
                    console.log(li.nfc)
                    httpPost(fjid, this.$api.bindCard).then((res) => {
                      if (res.success) {
                        this.$message.success("添加成功")
                      } else {
                        this.$message.error("添加失败")
                      }
                    });
                    ICINLocker.RfCardRegister(data.lockerId, data.imei, data.lockerUserId, 1, 1, li.nfc.toUpperCase(),
                      50, locakUserdata.startTime, locakUserdata.endTime, 6210, data.cardName, data
                      .roomName, (callbackTwo) => {
                          var str = {
                            imei: data.imei,
                            userTelephone: infostr.userTelephone,
                            cardId: li.id,
                            userPassword: infostr.userPassword,
                            password: li.nfc.toUpperCase(),
                            operateMode: 10,
                            order: 6210,
                            type: 2,
                            passwordStartTime: locakUserdata.passwordStartTime,
                            passwordEndTime: locakUserdata.passwordEndTime,
                            pzname: data.pzname,
                            is: false,
                            cardName: data.cardName,
                            roomName: data.roomName
                          };
                          var dataCertifi = {
                            cardId: li.id,
                            imei: data.imei,
                            deviceNum: data.deviceNum,
                            content: JSON.stringify(str), //operateMode:NFC-10、把人员添加到凭证-1
                            type: 13,
                            startTime: locakUserdata.startTime,
                            endTime: locakUserdata.endTime,
                          };
                          httpPost(dataCertifi, this.$api.addCertificates).then((res) => {
                            var dataCertifiTwo=dataCertifi
                            dataCertifiTwo.type=3
                            dataCertifiTwo.serial=callbackTwo.data.serialNumber
                            httpPost(dataCertifiTwo, this.$api.addCertificates).then((res) => {
                              this.$emit('getAboutRoom')
                            })
                          });

                      })
                  } else {
                    this.$message.error(callback.msg);
                    if (callback.code == 201016) {
                      httpPost(fjid, this.$api.bindCard).then((res) => {
                        if (res.success) {
                          this.$message.success("该用户门锁已存在")
                        } else {
                          this.$message.error("添加失败")
                        }
                      });
                    }
                  }
                })
            } else if (li.manufactureId == 101) {
              var userstr = {
                imei: li.imei,
                deviceNum: li.deviceNum,
                userTelephone: infostr.userTelephone,
                userPassword: infostr.userPassword,
                password: infostr.userPassword,
                operateMode: 26,
                order: 6226,
                passwordStartTime: moment(this.dateTime[0]).format(
                  "YYYYMMDDHHmmss"),
                passwordEndTime: moment(this.dateTime[1]).format("YYYYMMDDHHmmss"),
                is: false,
                cardName: li.name,
                pzname:'NFC'+li.num,
                roomName: li.siteName
              };
              ICINLocker.LDAddUser(userstr.deviceNum, userstr.imei, userstr.userTelephone,
                userstr.userPassword, userstr.password, userstr.passwordStartTime,
                userstr.passwordEndTime, userstr.operateMode, userstr.order, userstr
                .cardName, userstr.roomName, false, (callback) => {
                  if (callback.success) {
                    var locakUserdata = {
                      deviceNum: li.deviceNum,
                      imei: li.imei,
                      cardId: li.id,
                      content: JSON.stringify(
                        userstr
                      ), //operateMode:NFC-10、把人员添加到凭证-1
                      type: 26,
                      serial: callback.data.serialNumber,
                      startTime:parseInt(_this.dateTime[0].getTime() / 1000),
                      endTime:parseInt(_this.dateTime[1].getTime() / 1000),
                    }
                    utils.sendLockUser(locakUserdata, (callbackLOCK) => {

                    })
                    httpPost(fjid, this.$api.bindCard).then((res) => {
                      if (res.success) {
                        ICINLocker.LDRfCardRegister(userstr.deviceNum, userstr.imei, userstr.userTelephone, userstr.userPassword, li.nfc, userstr.passwordStartTime, userstr.passwordEndTime,10, 6210, userstr.cardName, userstr.roomName,false, (callbackTwo) => {
                              var str = {
                                imei: userstr.imei,
                                userTelephone: userstr.userTelephone,
                                cardId: li.id,
                                userPassword: userstr.userPassword,
                                password: li.nfc,
                                operateMode: 10,
                                order: 6210,
                                type: 2,
                                passwordStartTime: userstr.passwordStartTime,
                                passwordEndTime: userstr.passwordEndTime,
                                pzname: userstr.pzname,
                                is: false,
                                cardName: userstr.cardName,
                                roomName: userstr.roomName
                              };
                              var dataCertifi = {
                                cardId: li.id,
                                imei: userstr.imei,
                                deviceNum: userstr.deviceNum,
                                content: JSON.stringify(str), //operateMode:NFC-10、把人员添加到凭证-1
                                type: 13,
                                startTime: locakUserdata.startTime,
                                endTime: locakUserdata.endTime,
                              };
                              httpPost(dataCertifi, this.$api.addCertificates).then((res) => {
                                var dataCertifiTwo=dataCertifi
                                dataCertifiTwo.type=3
                                dataCertifiTwo.serial=callbackTwo.data.serialNumber
                                httpPost(dataCertifiTwo, this.$api.addCertificates).then((res) => {
                                  this.$emit('getAboutRoom')
                                })
                              });
                          })
                        this.$message.success("添加成功")
                      } else {
                        this.$message.error("添加失败")
                      }
                    });
                  } else {
                    this.$message.error(callback.msg);
                  }
                })
            }

          })
        } else {
          this.$message.error("请选择人员")
        }
      },
      //查询人员
      getperson(li, callback) {
        var data = {
          orderBy: "create_time desc",
          q: JSON.stringify({
            cardId: li.cardId,
          }),
        };
        let roomAbout = this.$store.state.roomAbout
        httpPost(data, this.$api.getlistNum).then((res) => {
          callback(res.data.list[0]);
        });
      },
      // 清空表格
      clearAll() {
        this.userlist = []
      },
      clearAllOne() {
        this.userlistOne = []
      },
      clearAllTwo() {
        this.userlistTwo = []
      },
      mapTwoDimension(arr) {
        let dataArr = []
        if (arr.length === 0) {
          console.log(arr, arr.length)
          return dataArr
        }
        arr.map(oneDim => {
          if (dataArr.length == 0) {
            dataArr.push({
              cardId: oneDim.cardId,
              cardState: oneDim.cardState,
              enterpriseId: oneDim.enterpriseId,
              id: oneDim.id,
              info: oneDim.info,
              name: oneDim.name,
              phone: oneDim.phone,
              sex: oneDim.sex,
              siteId: oneDim.siteId,
              siteName: oneDim.siteName,
              type: oneDim.type,
              list: [oneDim]
            })
          } else {
            let res = dataArr.some(item => { // 判断相同，有就添加到当前项
              if (item.cardId == oneDim.cardId && item.id == oneDim.id) {
                item.list.push(oneDim)
                return true
              }
            })
            if (!res) { // 如果没找相同添加一个新对象
              dataArr.push({
                cardId: oneDim.cardId,
                cardState: oneDim.cardState,
                enterpriseId: oneDim.enterpriseId,
                id: oneDim.id,
                info: oneDim.info,
                name: oneDim.name,
                phone: oneDim.phone,
                sex: oneDim.sex,
                siteId: oneDim.siteId,
                siteName: oneDim.siteName,
                type: oneDim.type,
                list: [oneDim]
              })
            }
          }
        })
        return dataArr
      },
      // 筛选现有人员
      contrastDeDuplication(arr) {
        let _this = this
        const p = new Promise((resolve, reject) => {
          let list = []
          arr.map(li => {
            this.getperson(li, function(data) {
              if (data) {
                li.id = data.id;
                li.info = data.info
                list.push(li)
              }
            })
          })
          setTimeout(() => {
            resolve(list)
            // reject("筛选错误");
          }, 1000);
        })
        p.then(list => {
          // let result = _this.mapTwoDimension(list)
          _this.getRoomIdMethods(list)
        }).catch(error => {
          _this.$message.error("请求错误")
        })
      },
      // 获取房间id
      getRoomIdMethods(result) {
        result.map(lt => {
          let id = this.deviceList.filter(item => item.roomName == lt.siteName)[0]
          if (id) {
            lt.manufactureId = id.manufactureId
            lt.deviceNum = id.deviceNum
            lt.imei = id.imei
            lt.roomId = id.roomId
            lt.color = ''
            if (lt.cardId.length == 8) {
              lt.nfc = lt.cardId
            } else if (lt.cardId.length == 0) {
              lt.nfc = ""
            } else {
              var nfc = ''
              var array3 = dec2hex(lt.cardId);
              var arr4 = group(array3, 2)
              arr4.map((li) => {
                nfc += li;
              });
              lt.nfc = nfc
            }
            var num=this.allCertificates.filter(item=> item.cardId==lt.id)
            lt.num=num.length+1
          } else {
            lt.color = 'bgred'
          }
        })
        this.userlistTwo = result
      },
      // 比对表格
      async comparisonMethods() {
        let arr = await this.screenMethods(this.userlist, this.userlistOne, this.filterFields)
        console.log(arr)
        let result = await this.contrastDeDuplication(arr)
      },
      screenMethods(arr1, arr2, KeyName) {
        let KeyNameData = KeyName
        let sum = 0,
          products = []
        if (KeyNameData.length === 0) {
          this.$message.error("请选择筛选条件")
        } else {
          for (let i = 0; i < KeyNameData.length; i++) {
            products = arr1.filter((item) => arr2.some((val) => {
              return item[KeyNameData[i]] == val[KeyNameData[i]]
            }))
          }
          return products;
        }
      },
      // 多选操作
      handleSelectionChange(val) {
        this.multipleSelection = val;
      },
      handleSelectionChangeOne(val) {
        this.multipleSelectionOne = val;
      },
      handleSelectionChangeTwo(val) {
        this.multipleSelectionTwo = val;
      },
      // 导入
      async exportData(event) {
        if (!event.currentTarget.files.length) {
          return;
        }
        const that = this;
        // 拿取文件对象
        var f = event.currentTarget.files[0];
        // 用FileReader来读取
        var reader = new FileReader();
        // 重写FileReader上的readAsBinaryString方法
        FileReader.prototype.readAsBinaryString = function(f) {
          var binary = "";
          var wb; // 读取完成的数据
          var outdata; // 你需要的数据
          var reader = new FileReader();
          reader.onload = function(e) {
            // 读取成Uint8Array，再转换为Unicode编码（Unicode占两个字节）
            var bytes = new Uint8Array(reader.result);
            var length = bytes.byteLength;
            for (var i = 0; i < length; i++) {
              binary += String.fromCharCode(bytes[i]);
            }
            // 接下来就是xlsx了，具体可看api
            wb = XLSX.read(binary, {
              type: "binary",
            });
            outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]);
            // 自定义方法向父组件传递数据
            var userInfo = localStorage.getItem('info')
            let arr = [];
            outdata.map((li, index) => {
              var obj = {};
              obj.name = li["名称"];
              obj.siteId = li["房间ID"];
              obj.siteName = li["绑定房间"];
              obj.number = li["编号/证件号/学工号"];
              obj.cardId = li["卡号"];
              obj.phone = li["电话"];
              obj.sex = li["性别"];
              obj.id = li["id"];
              obj.cardState = '1';
              obj.enterpriseId = JSON.parse(userInfo).enterpriseId;
              obj.type = 0;
              var phone = obj.phone.toString()
              obj.siteId = JSON.stringify(obj.siteId)
              var str = {
                userPassword: phone.substring(phone.length - 6, phone.length - 1),
                userTelephone: phone,
              };
              obj.info = JSON.stringify(str);
              if (obj.sex == "男") {
                obj.sex = 1;
              } else if (obj.sex == "女") {
                obj.sex = 2;
              }
              arr.push(obj);
            });
            var map = {},
              dest = []
            for (var i = 0; i < arr.length; i++) {
              var ai = arr[i]
              if (!map[ai.phone]) {
                dest.push({
                  name: ai.name,
                  siteId: ai.siteId,
                  siteName: ai.siteName,
                  number: ai.number,
                  cardId: ai.cardId,
                  phone: ai.phone,
                  sex: ai.sex,
                  id: ai.id,
                  cardState: ai.cardState,
                  enterpriseId: ai.enterpriseId,
                  type: ai.type,
                  info: ai.info
                })
                map[ai.phone] = ai
              }
            }
            that.$nextTick(() => {
              that.userlist = arr;
            });
          };
          reader.readAsArrayBuffer(f);
        };
        reader.readAsBinaryString(f);
      },

      exportDataOne(event) {
        if (!event.currentTarget.files.length) {
          return;
        }
        const that = this;
        // 拿取文件对象
        var f = event.currentTarget.files[0];
        // 用FileReader来读取
        var reader = new FileReader();
        // 重写FileReader上的readAsBinaryString方法
        FileReader.prototype.readAsBinaryString = function(f) {
          var binary = "";
          var wb; // 读取完成的数据
          var outdata; // 你需要的数据
          var reader = new FileReader();
          reader.onload = function(e) {
            // 读取成Uint8Array，再转换为Unicode编码（Unicode占两个字节）
            var bytes = new Uint8Array(reader.result);
            var length = bytes.byteLength;
            for (var i = 0; i < length; i++) {
              binary += String.fromCharCode(bytes[i]);
            }
            // 接下来就是xlsx了，具体可看api
            wb = XLSX.read(binary, {
              type: "binary",
            });
            outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]);
            // 自定义方法向父组件传递数据
            var userInfo = localStorage.getItem('info')
            let arr = [];
            outdata.map((li, index) => {
              var obj = {};
              obj.name = li["名称"];
              obj.siteId = li["房间ID"];
              obj.siteName = li["绑定房间"];
              obj.number = li["编号/证件号/学工号"];
              obj.cardId = li["卡号"];
              obj.phone = li["电话"];
              obj.sex = li["性别"];
              obj.id = li["id"];
              obj.cardState = '1';
              obj.enterpriseId = JSON.parse(userInfo).enterpriseId;
              obj.type = 0;
              var phone = obj.phone.toString()
              var str = {
                userPassword: phone.substring(phone.length - 6, phone.length - 1),
                userTelephone: phone,
              };
              obj.info = JSON.stringify(str);
              if (obj.sex == "男") {
                obj.sex = 1;
              } else if (obj.sex == "女") {
                obj.sex = 2;
              }
              arr.push(obj);
            });
            that.$nextTick(() => {
              that.userlistOne = arr;
            });
          };
          reader.readAsArrayBuffer(f);
        };
        reader.readAsBinaryString(f);
      },
      btnClick() {
        document.querySelector(".input-file").click();
      },
      btnClickOne() {
        document.querySelector(".input-fileOne").click();
      },
      exportBtn() {
        this.exportExcel()
      },
      exportExcel() {
        let sheet1data = [
          ['名称', '卡号', '状态', '电话', '绑定房间', '性别']
        ]
        var sheet1 = XLSX.utils.json_to_sheet(sheet1data, {
          skipHeader: true,
        })
        // 创建一个新的空的workbook
        var wb = XLSX.utils.book_new()
        XLSX.utils.book_append_sheet(wb, sheet1, '人员导入模板')
        // XLSX.utils.book_append_sheet(wb, sheet2, '行政部')
        // XLSX.utils.book_append_sheet(wb, sheet3, '前端部')
        const workbookBlob = this.workbook2blob(wb)
        this.openDownloadDialog(workbookBlob, '人员导入模板.xlsx')
      },
      // 将blob对象 创建bloburl,然后用a标签实现弹出下载框
      openDownloadDialog(blob, fileName) {
        if (typeof blob === 'object' && blob instanceof Blob) {
          blob = URL.createObjectURL(blob) // 创建blob地址
        }
        var aLink = document.createElement('a')
        aLink.href = blob
        // HTML5新增的属性，指定保存文件名，可以不要后缀，注意，有时候 file:///模式下不会生效
        aLink.download = fileName || ''
        var event
        if (window.MouseEvent) event = new MouseEvent('click')
        //   移动端
        else {
          event = document.createEvent('MouseEvents')
          event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null)
        }
        aLink.dispatchEvent(event)
      },
      // 下载模板
      workbook2blob(workbook) {
        // 生成excel的配置项
        var wopts = {
          // 要生成的文件类型
          bookType: 'xlsx',
          // // 是否生成Shared String Table，官方解释是，如果开启生成速度会下降，但在低版本IOS设备上有更好的兼容性
          bookSST: false,
          type: 'binary'
        }
        var wbout = XLSX.write(workbook, wopts)
        // 将字符串转ArrayBuffer
        function s2ab(s) {
          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
        }
        let buf = s2ab(wbout)
        var blob = new Blob([buf], {
          type: 'application/octet-stream'
        })
        return blob
      },
    }
  }
</script>

<style scoped>
  .input-file {
    display: none;
  }

  .el-table .warning-row {
    background: oldlace;
  }

  .el-table .success-row {
    background: #f0f9eb;
  }
</style>
