// 上传人员列表
<template>
  <div>
    <el-dialog
      title="批量导入"
      width="600px"
      :visible.sync="dialogVisible"
      :destroy-on-close="false"
      :close-on-click-modal="false"
      @close="dialogClose"
    >
      <el-form
        ref="form"
        :rules="rules"
        :model="form"
        label-position="left"
        label-width="80px"
      >
        <el-form-item label="所属账号" prop="accountId" required>
          <el-select
            v-model="form.accountId"
            placeholder="请选择所属账号"
            filterable
            style="width: 100%"
          >
            <el-option
              v-for="item in option"
              :key="item.id"
              :label="item.username"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="上传文件" prop="correctList">
          <batch-upload ref="batchUploadRef" @getFileList="batchUploadResult" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false"> 取消 </el-button>
        <el-button type="primary" @click="submit"> 确定 </el-button>
      </div>
    </el-dialog>
    <div v-if="type === 'button'" style="position: absolute; top: 99999999px">
      <batch-upload ref="batchUploadRef" @getFileList="batchUploadResult" />
    </div>
    <!-- 批量注册人员-抽屉 -->
    <el-drawer
      :title="hasCompleted ? '导入已完成' : '正在处理中..'"
      :visible.sync="drawerVisible"
      :wrapper-closable="false"
      size="50%"
      direction="rtl"
    >
      <div style="padding: 50px">
        <div>
          已处理条数；{{ hasDealNumber }}; 待处理条数：{{ waitDealNumber }};
          总共条数：{{ allNumber }}
        </div>
        <el-progress
          :percentage="makePercent"
          :format="formatProgress"
          style="margin-top: 10px"
        />
        <el-table
          ref="batch_upload_result"
          v-loading="false"
          :data="batchUploadResultList"
          class="table"
          element-loading-text="Loading"
          border
          fit
          highlight-current-row
          height="500"
        >
          <el-table-column label="错误序号" align="center" width="100px">
            <template slot-scope="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column label="错误描述" align="center">
            <template slot-scope="scope">
              {{ scope.row.err }}
            </template>
          </el-table-column>
        </el-table>
        <div style="text-align: center; margin: 20px 0">
          <el-button type="primary" @click="drawerVisible = false">
            我已知晓
          </el-button>
          <el-button type="warning" @click="downloadBatchUploadErrorList">
            下载错误列表文件
          </el-button>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import { doEditSubuser } from "@/api/subuser";
import BatchUpload from "@/components/BatchUpload";
import { checkRole } from "@/utils/checkRole";
export default {
  components: { BatchUpload },
  props: {
    option: {
      type: Array,
      default: () => [],
    },
    type: {
      type: String,
      default: "dialog",
    },
  },
  data() {
    return {
      buyList: [],
      form: {
        accountId: null,
        correctList: {
          correct: [],
          incorrect: [],
        },
      },
      rules: {
        accountId: [
          {
            required: true,
            type: "number",
            whitespace: true,
            message: "不能为空!",
            trigger: ["change", "blur"],
          },
        ],
        correctList: [
          {
            required: true,
            type: "object",
            message: "文件不能为空!",
            trigger: ["change", "blur"],
            validator: (rule, value, callback) => {
              if (
                Object.keys(value).length > 0 &&
                ((value.correct && value.correct.length > 0) ||
                  (value.incorrect && value.incorrect.length > 0))
              ) {
                return callback();
              }
              return callback("数据不能为空!");
            },
          },
        ],
      },
      dialogVisible: false,
      // 批量注册-处理提示值
      hasDealNumber: 0,
      waitDealNumber: 0,
      allNumber: 0,
      hasCompleted: false,
      // 批量注册-抽屉控制值
      drawerVisible: false,
      batchUploadResultList: [],
      freeDaysList: [
        { id: "Monday", name: "周一" },
        { id: "Tuesday", name: "周二" },
        { id: "Wednesday", name: "周三" },
        { id: "Thursday", name: "周四" },
        { id: "Friday", name: "周五" },
        { id: "Saturday", name: "周六" },
        { id: "Sunday", name: "周日" },
      ],
    };
  },
  computed: {
    // 批量注册-返回向下取整，减少渲染次数
    makePercent() {
      return Math.floor((this.hasDealNumber / this.allNumber) * 100);
    },
  },
  created() {
    // console.log(this.option,7);
  },
  methods: {
    checkRole,
    open() {
      if (checkRole([0])) {
        this.dialogVisible = true;
        this.$nextTick(() => {
          this.$refs.form.resetFields();
        });
      } else {
        this.batchUploadResult();
      }
    },
    dialogClose() {
      this.$refs.batchUploadRef.clearFile();
    },
    batchUploadResult(correctList) {
      // this.getFileList(correctList);
      // this.form.correctList = correctList;
      if (this.type === "button") {
        this.getFileList(correctList);
      } else {
        this.form.correctList = correctList;
      }
    },
    // 批量注册人员-操作
    getFileList(correctList) {
      this.hasCompleted = false;
      this.drawerVisible = true;
      this.hasDealNumber = correctList.incorrect.length;
      this.waitDealNumber = correctList.correct.length;
      this.allNumber =
        correctList.incorrect.length + correctList.correct.length;
      this.batchUploadResultList = correctList.incorrect.map((item) => {
        return { name: item.file.name, err: item.reason };
      });
      this.makeScrollDown();
      this.doSubmitUrl(correctList, 0);
    },
    // 批量注册人员-并提交至添加到接口
    async doSubmitUrl(correctList, index) {
      let that = this;
      if (index <= correctList.correct.length - 1) {
        const item = correctList.correct[index];
        // 组装数据上传
        const data = JSON.parse(JSON.stringify(this.form));
        data.username = item["账号名称"];
        data.password = item["账号密码"];
        data.userType = item["账号类型(“管理员”或“巡更员”)"];
        data.idName = item["用户姓名"];
        data.idNumber = item["用户身份证号"];
        data.freeDays = item["用户休息日（示例：周六、周日）"];
        if (
          data.username &&
          data.password &&
          data.userType &&
          data.idName &&
          data.idNumber
        ) {
          let err = "";
          if (
            !/^(((?=.*\d)(?=.*[a-z])(?=.*[A-Z]))|((?=.*\d)(?=.*[a-z])(?=.*[~!@#$%^&*]))|((?=.*\d)(?=.*[A-Z])(?=.*[~!@#$%^&*]))|((?=.*[a-z])(?=.*[A-Z])(?=.*[~!@#$%^&*]))|((?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[~!@#$%^&*]))).{10,32}$/.test(
              data.password
            )
          ) {
            err =
              "密码必须大小写字母、数字、特殊字符,4种组合中至少满足3种，且密码长度在10-32位之间";
          }
          if (!!data.freeDays) {
            let allDays = that.freeDaysList.map((item) => item.name);
            let weekend = data.freeDays.split("、").map((item) => item);
            const res = weekend.every((day) => allDays.includes(day));
            if (!res) {
              err = "用户休息日格式有误,2个及以上请以“中文顿号”隔开";
            }
          }

          // 查找匹配项的id
          data.freeDays = data.freeDays?.split("、").map((day) => {
            const item = that.freeDaysList.find((item) => item.name == day);
            return item ? item.id : null;
          });

          if (data.userType == "管理员") {
            data.userType = 1;
          } else if (data.userType == "巡更员") {
            data.userType = 0;
          }
          if (
            !/^[1-9]\d{5}(19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dxX]$/.test(
              data.idNumber
            )
          ) {
            err = "身份证长度或格式有误";
          }

          if (err) {
            this.batchUploadResultList.push({
              index: "第" + index + "行",
              err: err,
            });
          } else {
            try {
              await doEditSubuser(data);
            } catch (err) {
              console.log(err);
              this.batchUploadResultList.push({
                index: "第" + index + "行",
                err: err,
              });
            }
          }
        } else {
          if (!data.username) {
            this.batchUploadResultList.push({
              index: "第" + index + "行",
              err: "账号名称不能为空",
            });
          }
          if (!data.password) {
            this.batchUploadResultList.push({
              index: "第" + index + "行",
              err: "账号密码不能为空",
            });
          }
          if (!data.userType) {
            this.batchUploadResultList.push({
              index: "第" + index + "行",
              err: "账号类型不能为空",
            });
          }
          if (!data.idName) {
            this.batchUploadResultList.push({
              index: "第" + index + "行",
              err: "用户姓名不能为空",
            });
          }
          if (!data.idNumber) {
            this.batchUploadResultList.push({
              index: "第" + index + "行",
              err: "用户身份证号不能为空",
            });
          }
          // if (!data.freeDays) {
          //   this.batchUploadResultList.push({
          //     index: "第" + index + "行",
          //     err: "用户休息日不能为空",
          //   });
          // }
        }

        this.hasDealNumber += 1;
        this.waitDealNumber -= 1;
        this.makeScrollDown();
        // 继续调用
        this.doSubmitUrl(correctList, ++index);
      } else {
        this.hasCompleted = true;
        this.$emit("finish");
      }
    },
    // 批量注册人员-保持滚动条在最底部
    makeScrollDown() {
      this.$nextTick(() => {
        this.$refs.batch_upload_result.$refs.bodyWrapper.scrollTop =
          this.$refs.batch_upload_result.$refs.bodyWrapper.scrollHeight;
      });
    },
    // 批量注册人员-返回进度条尾部显示值
    formatProgress(percent) {
      return percent === 100 ? "已完成" : "";
    },
    // 批量注册人员-导出错误名单
    downloadBatchUploadErrorList() {
      const list = this.batchUploadResultList;
      let string = "序号\t设备sn\t错误原因\n";
      for (let i = 0; i < this.batchUploadResultList.length; i++) {
        string +=
          (i + 1).toString() +
          "\t" +
          list[i].sn +
          "\t" +
          list[i].err +
          "\t" +
          "\n";
      }
      const blob = new Blob([string], { type: "text/plain;charset=utf-8" });
      const excel_url = window.URL.createObjectURL(blob);
      const link = document.createElement("a");
      link.href = excel_url;
      link.download = "批量注册结果错误名单.xls";
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    },
    submit(e) {
      e.preventDefault();
      this.$refs.form.validate((valid) => {
        if (!valid) {
          return false;
        }
        this.dialogVisible = false;
        this.getFileList(this.form.correctList);
      });
    },
  },
};
</script>

<style scoped>
::v-deep .el-select {
  width: 100%;
}
.table {
  margin-top: 15px;
}
</style>
