<template>
  <div>
    <div class="container">
      <div class="handle-box">
        <!--<el-select v-model="selectoptionValue" size="mini" class="handle-input mr10" placeholder="请选择数据中心"
          @change="selectTenantId" style="width: 1.5rem;" v-if="userInfo.type==0">
          <el-option v-for="item in selectoption" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
          </el-select> -->
          <selectoption></selectoption>
          <!-- <el-button type="primary" @click="batchUpload" size="mini"
          >批量上传</el-button> -->
          <el-button type="primary" @click="batchDelete" size="small">批量删除</el-button>
      </div>
      <el-table :data="tableData" border class="table" ref="multipleTable" header-cell-class-name="table-header"
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center">
        </el-table-column>
        <el-table-column prop="id" label="ID" align="center"></el-table-column>
        <el-table-column prop="pzname" label="名称" align="center"></el-table-column>
        <el-table-column prop="cardId" label="卡号" width="150" align="center"></el-table-column>
        <el-table-column prop="userTelephone" label="电话" width="150" align="center"></el-table-column>
        <el-table-column label="凭证类型" align="center">
          <template #default="scope">
            <span v-if="scope.row.type == 0">人脸</span>
            <span v-if="scope.row.type == 1">指纹</span>
            <span v-if="scope.row.type == 2">身份证</span>
            <span v-if="scope.row.type == 3">NFC</span>
            <span v-if="scope.row.type == 4">密码</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" align="center">
          <template #default="scope">
            <!-- <el-button type="text" @click="handleEdit(scope.$index, scope.row)"
              >编辑</el-button
            > -->
            <el-button type="text" class="red" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination background layout="total, prev, pager, next" :current-page="query.pageIndex"
          :page-size="query.pageSize" :total="pageTotal" @current-change="handlePageChange"></el-pagination>
      </div>
      <el-dialog title="批量上传" :visible.sync="uploadkj" width="70%">
        <input class="input-file" type="file" @change="exportData"
          accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" />
        <!-- <button @click="btnClick">导入EXCEL</button> -->
        <el-button type="primary" @click="btnClick" size="mini">导入EXCEL</el-button>
        <el-form ref="form" :model="form" label-width="70px"> </el-form>
        <el-table :data="userlist2" v-if="userlist1statu" border class="table" ref="multipleTable1" height="200"
          header-cell-class-name="table-header" @selection-change="handleSelectionChange1">
          <el-table-column prop="card" label="ID" align="center"></el-table-column>
          <el-table-column prop="name" label="名称" align="center"></el-table-column>
          <el-table-column prop="cardId" label="卡号" width="150" align="center"></el-table-column>
          <el-table-column prop="phone" label="电话" width="150" align="center"></el-table-column>
          <el-table-column label="性别" align="center">
            <template #default="scope">
              {{ scope.row.sex == 1 ? "男" : "女" }}
            </template>
          </el-table-column>
        </el-table>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="cancel">取 消</el-button>
            <el-button type="primary" @click="batchUploadfun">确 定</el-button>
          </span>
        </template>
      </el-dialog>
      <el-dialog title="编辑" :visible.sync="editVisiblelist" class="dialogheight">
        <el-form ref="form1" :model="form1" label-width="70px">
          <el-form-item label="名称">
            <el-input v-model="form1.name"></el-input>
          </el-form-item>
          <el-form-item label="学号">
            <el-input v-model="form1.number"></el-input>
          </el-form-item>
          <el-form-item label="卡号">
            <el-input v-model="form1.card"></el-input>
          </el-form-item>
          <el-form-item label="电话">
            <el-input v-model="form1.phone"></el-input>
          </el-form-item>
          <el-form-item label="类型">
            <el-select v-model="documentType" placeholder="请选择" class="documentType">
              <el-option label="人脸" value="0"></el-option>
              <el-option label="指纹" value="1"></el-option>
              <el-option label="身份证" value="2"></el-option>
              <el-option label="NFC" value="3"></el-option>
              <el-option label="密码" value="4"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="上传照片" v-if="documentType == 0">
            <!-- <el-input v-model="temporaryPassword"></el-input>                     -->
            <div v-if="documentType == 0">
              <el-upload action="#" list-type="picture-card" :auto-upload="false" :modal-append-to-body="false">
                <i slot="default" class="el-icon-plus"></i>
                <div slot="file" slot-scope="{ file }">
                  <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
                  <span class="el-upload-list__item-actions">
                    <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                      <i class="el-icon-zoom-in"></i>
                    </span>
                    <span v-if="!disabled1" class="el-upload-list__item-delete" @click="handleDownload(file)">
                      <i class="el-icon-download"></i>
                    </span>
                    <span v-if="!disabled1" class="el-upload-list__item-delete" @click="handleRemove(file)">
                      <i class="el-icon-delete"></i>
                    </span>
                  </span>
                </div>
              </el-upload>
              <el-dialog :visible.sync="dialogVisible" :modal-append-to-body="false">
                <img width="100%" :src="dialogImageUrl" alt="" />
              </el-dialog>
            </div>
          </el-form-item>
          <el-form-item label="指纹" v-if="documentType == 1">
            <el-radio-group v-model="checkList" @change="selectCheck">
              <el-radio-button label="左手大拇指" :value="0"></el-radio-button>
              <el-radio-button label="左手食指" :value="1"></el-radio-button>
              <el-radio-button label="右手大拇指" :value="2"></el-radio-button>
              <el-radio-button label="右手食指" :value="3"></el-radio-button>
            </el-radio-group>
            <iframe src="static/equipment/mafp_serial/index.html" frameborder="0" style="width: 100%; height: 350px"
              id="iframeBox"></iframe>
          </el-form-item>
          <el-form-item label="身份证" v-if="documentType == 2">
            <el-input v-model="voucher.idcard"></el-input>
          </el-form-item>
          <el-form-item label="NFC卡号" v-if="documentType == 3">
            <el-input v-model="voucher.nfc"></el-input>
          </el-form-item>
          <el-form-item label="密码" v-if="documentType == 4">
            <el-input v-model="voucher.password" show-password></el-input>
          </el-form-item>
          <el-form-item label="性别" disabled>
            <el-radio v-model="form1.sex" :label="1">男</el-radio>
            <el-radio v-model="form1.sex" :label="2">女</el-radio>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="editVisiblelist = false">取 消</el-button>
            <el-button type="primary" @click="modifyEdit">修 改</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script>
  import {
    httpGet,
    httpPost
  } from "../api";
  import XLSX from "xlsx";
  import utils from "../utils/util.js";
  export default {
    inject: ['reload'],
    name: "warningLog",
    data() {
      return {
        selectoption: [],
        selectoptionValue: '',
        BatchUpload: false,
        dialogImageUrl: "",
        dialogVisible: false,
        disabled1: false,
        documentType: "请选择",
        cardstatus: [{
            value: 1,
            label: "正常",
          },
          {
            value: 2,
            label: "挂失",
          },
          {
            value: 3,
            label: "挂失冻结",
          },
          {
            value: 4,
            label: "冻结",
          },
          {
            value: 5,
            label: "预开户",
          },
          {
            value: 6,
            label: "过期",
          },
        ],
        editVisiblelist: false,
        query: {
          operType: "",
          operateName: "",
          operModul: "",
        },
        query1: {
          operType: "",
          operateName: "",
          operModul: "",
        },
        activeName: "first",
        tableData: [],
        tableData1: [],
        multipleSelection: [],
        multipleSelection1: [],
        delList: [],
        editVisible: false,
        pageTotal: 0,
        pageTotal1: 0,
        form: {},
        form1: {
          sex: 1,
          cardState: 1,
          name: "",
          number: "",
          cardId: "",
          id: '',
          card: '',
          content: '',
          phone: "",
          type: ''
        },
        idx: -1,
        id: -1,
        uploadkj: false,
        userlist1: [],
        userlist1statu: true,
        userlist2: [],
        editrow: {},
        voucher: {
          username: "",
          pzname: "",
          nfc: "",
          idcard: "",
          password: "123456",
        },
        fingerprintId: 0,
        checkList: "",
        userInfo: {
          type: ''
        }
      };
    },
    created() {
      this.userInfo = JSON.parse(localStorage.getItem('info'))
      // var tenantId = JSON.parse(localStorage.getItem('tenantId'))
      // if (tenantId == 400) {
      //   this.$store.commit('defaultsettenantid')
      // }
      this.getOperates();
      this.selectoption = JSON.parse(localStorage.getItem('selectoption'))
      this.selectoptionValue = localStorage.getItem('tenantId')
    },
    methods: {
      // 人脸图片上传功能
      handleRemove(file) {
        console.log(file);
      },
      handlePictureCardPreview(file) {
        this.dialogImageUrl = file.url;
        this.dialogVisible1 = true;
      },
      handleDownload(file) {
        console.log(file);
      },
      selectCheck(e) {
        if (e == "左手大拇指") {
          this.fingerprintId = 0;
        } else if (e == "左手食指") {
          this.fingerprintId = 1;
        } else if (e == "右手大拇指") {
          this.fingerprintId = 2;
        } else if (e == "右手食指") {
          this.fingerprintId = 3;
        }
      },
      handleEdit(index, row) {
        this.form1 = {
          sex: 1,
          number: row.number,
          name: row.name,
          phone: row.phone,
          cardId: row.cardId,
          card: row.card,
          id: row.id,
          content: row.content,
          cardState: row.cardState,
          userPassword: row.userPassword,
          userTelephone: row.userTelephone,
          type: row.type,
          sex: row.sex,
        };
        this.documentType = ""
        this.editrow = row;
        this.editVisiblelist = true;
      },
      Bytes2Str(arrBytes) {
        var str = "";
        for (var i = 0; i < arrBytes.length; i++) {
          var tmp;
          var num = parseInt(arrBytes[i]);
          if (num < 0) {
            //此处填坑，当byte因为符合位导致数值为负时候，需要对数据进行处理
            tmp = (255 + num + 1).toString(16);
          } else {
            tmp = num.toString(16);
          }
          if (tmp.length == 1) {
            tmp = "0" + tmp;
          }
          if (i > 0) {
            str += "" + tmp;
          } else {
            str += tmp;
          }
        }
        return str;
      },
      modifyEdit() {
        var documentType = this.documentType;
        if (documentType == 1) {
          var fingerprint = localStorage.getItem("fingerprint") || "";
          var array = fingerprint.split(",");
          var num = this.Bytes2Str(array);
          this.form1.type = 1
          this.form1.content = num
        } else if (documentType == 2) {
          this.form1.content = this.voucher.idcard
          this.form1.type = 2
        } else if (documentType == 3) {
          this.form1.content = this.voucher.nfc
          this.form1.type = 3
        } else if (documentType == 4) {
          this.form1.content = this.voucher.password
          this.form1.type = 4
        }
        if (this.form1.name == '' || this.form1.number == '' || this.form1.phone == '') {
          this.$message.error('请填写信息完整')
        } else {
          var data = {
            id: this.form1.id,
            cardId: this.form1.cardId,
            content: JSON.stringify(this.form1)
          }
          httpPost(data, this.$api.editMark).then(res => {
            if (res.success) {
              this.$message.success("修改成功")
              this.editVisiblelist = false
              this.getOperates()
            }
          })
        }
      },
      //添加
      handleSearch1() {
        this.form1 = {
          sex: 1,
          number: "",
          name: "",
          phone: "",
          cardId: "",
          cardState: 1,
        };
        this.editVisiblelist = true;
      },
      // 删除操作
      handleDelete(index, row) {
        // 二次确认删除
        this.$confirm("确定要删除吗？", "提示", {
            type: "warning",
          })
          .then(() => {
            var data = {
              ids: [row.id],
            };
            httpPost(data, this.$api.deleteMark).then((res) => {
              this.$message.success("删除成功");
              this.getOperates();
            });
          })
          .catch(() => {});
      },
      // 删除操作
      batchDelete(row) {
        var ids = [];
        this.multipleSelection.map((li) => {
          ids.push(li.id);
        });
        // 二次确认删除
        this.$confirm("确定要删除吗？", "提示", {
            type: "warning",
          })
          .then(() => {
            var data = {
              ids: ids,
            };
            httpPost(data, this.$api.deleteMark).then((res) => {
              this.$message.success("删除成功");
              this.getOperates();
            });
          })
          .catch(() => {});
      },
      //取消
      cancel() {
        this.uploadkj = false;
        this.userlist2 = [];
      },
      handleSelectionChange1(val) {
        this.multipleSelection1 = val;
      },
      handleSelectionChange(val) {
        this.multipleSelection = val;
      },
      //批量上传
      batchUpload() {
        this.uploadkj = true;
      },
      //批量上传确认
      batchUploadfun() {
        var data = {
          list: this.userlist1,
        };
        httpPost(data, this.$api.addMark).then((res) => {
          this.getOperates();
          this.uploadkj = false;
        });
      },
      time(time = +new Date()) {
        var date = new Date(time + 8 * 3600 * 1000); // 增加8小时
        return date.toJSON().substr(0, 19).replace("T", " ");
      },
      //   获取信息库
      getOperates() {
        var data = {
          pageNum: 1,
          pageSize: 10,
        };
        httpGet(data, this.$api.getMark).then((res) => {
          var array = [];
          res.data.map((li) => {
            var str = JSON.parse(li.content);
            str.id = li.id;
            str.cardId = li.cardId;
            array.push(str);
          });
          this.tableData = array;
          this.pageTotal = res.data.length;
        });
      },
      // 触发搜索按钮
      handleSearch() {
        var data = {
          pageNum: 1,
          pageSize: 10,
        };
        httpGet(data, this.$api.getMark).then((res) => {
          res.data.list.map((li) => {
            li.createTime = this.time(+new Date(li.createTime));
          });
          this.tableData = res.data.list;
          this.pageTotal = res.data.total;
        });
        //   this.$set(this.query, "pageIndex", 1);
      },
      // 分页导航
      handlePageChange(val) {
        var data = {
          pageNum: val,
          pageSize: 10,
        };
        httpPost(data, this.$api.getDeviceResult).then((res) => {
		let datalist=utils.zlib_unzip(res.data)
          datalist.map((li) => {
            li.createTime = this.time(+new Date(li.createTime));
          });
          this.tableData = datalist;
          this.pageTotal = res.data.total;
        });
      },
      btnClick() {
        document.querySelector(".input-file").click();
      },
      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]]);
            // 自定义方法向父组件传递数据
            let arr = [],
              arr1 = [];
            outdata.map((li, index) => {
              var obj = {},
                str = {};
              str.pzname = li["名称"];
              str.cardId = li["卡号"];
              str.userTelephone = li["电话"];
              str.content = li["凭证内容"];
              str.type = li["凭证类型"];
              if (str.sex == "男") {
                str.sex = 1;
              } else if (str.sex == "女") {
                str.sex = 2;
              }
              var phone = JSON.stringify(str.userTelephone);
              str.userPassword = phone.substr(phone.length - 6, phone.length - 1);
              obj.content = JSON.stringify(str);
              arr.push(obj);
              arr1.push(str);
            });
            //   this.tableData=arr
            that.userlist1statu = false;
            that.$nextTick(() => {
              that.userlist1 = arr;
              that.userlist2 = arr1;
              that.userlist1statu = true;
            });
          };
          reader.readAsArrayBuffer(f);
        };
        reader.readAsBinaryString(f);
      },
    },
  };
</script>

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

  .handle-box {
    margin-bottom: 20px;
  }

  .handle-select {
    width: 120px;
  }

  .handle-input {
    width: 300px;
    display: inline-block;
  }

  .table {
    width: 100%;
    font-size: 14px;
  }

  .red {
    color: #ff0000;
  }

  .mr10 {
    margin-right: 10px;
  }

  .table-td-thumb {
    display: block;
    margin: auto;
    width: 40px;
    height: 40px;
  }
</style>
