// 上传人员列表
<template>
  <div>
    <el-dialog
      :title="dialogTitle"
      width="1200px"
      :visible.sync="dialogVisible"
      :destroy-on-close="false"
      :close-on-click-modal="false"
      @close="dialogClose"
    >
      <div v-if="isEdit" class="dialog-top">整改内容：{{ form.remark }}</div>
      <el-form
        ref="form"
        :rules="rules"
        :model="form"
        label-position="left"
        label-width="120px"
      >
        <div class="flex">
          <el-form-item label="预警级别" prop="warningGrade" style="flex: 0.5">
            <el-select
              v-model="form.warningGrade"
              filterable
              clearable
              placeholder="请选择预警级别"
            >
              <el-option
                v-for="item in warning_list"
                :key="item.code"
                :label="item.desc"
                :value="item.code"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            style="margin-left: 40px; flex: 0.5"
            label="上传文件"
            prop="correctList"
          >
            <batch-upload ref="batchUploadRef" @getFileList="batchUploadResult">
            </batch-upload>
          </el-form-item>
        </div>
        <div class="flex">
          <el-form-item label="任务名称" style="flex: 0.5" prop="taskName">
            <el-input placeholder="请输入任务名称" v-model="form.taskName" />
          </el-form-item>
          <el-form-item
            style="margin-left: 40px; flex: 0.5"
            label="布控单位"
            prop="controlAdminId"
          >
            <el-select
              v-model="form.controlAdminId"
              filterable
              clearable
              placeholder="请选择布控单位"
            >
              <el-option
                v-for="item in oneselfBelowList"
                :key="item.adminId"
                :label="item.username"
                :value="item.adminId"
              ></el-option>
            </el-select>
          </el-form-item>
        </div>
        <div class="flex">
          <el-form-item label="布控时间段" style="flex: 0.5" prop="time">
            <el-date-picker
              v-model="form.time"
              value-format="yyyy-MM-dd"
              type="daterange"
              range-separator="至"
              start-placeholder="选择布控开始时间"
              end-placeholder="选择布控结束时间"
              style="width: 100%"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item
            style="margin-left: 40px; flex: 0.5"
            label="负责人"
            prop="manageName"
          >
            <el-input
              placeholder="请输入负责人姓名"
              v-model.trim="form.manageName"
            />
          </el-form-item>
        </div>
        <div class="flex">
          <el-form-item
            label="负责人手机号"
            style="margin-right: 40px; flex: 0.5"
            prop="phone"
          >
            <el-input
              placeholder="请输入负责人手机号，多个手机号用“，”隔开,最多10个"
              v-model.trim="form.phone"
            />
          </el-form-item>
        </div>
      </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";
import {
  getwarningPersonLogAdminList,
  getwarningPersonOneselfBelowList,
  getwarningPersonCreateList,
  getwarningPersonReviewPageList,
  getwarningPersonInsert,
  getwarningPersonRectify,
  getwarningPersonCheckPageList,
} from "@/api/personnelWarning";
export default {
  components: { BatchUpload },
  props: {
    type: {
      type: String,
      default: "dialog",
    },
  },
  data() {
    return {
      buyList: [],
      form: {
        warningGrade: "",
        taskName: "",
        controlAdminId: "",
        controlStartTime: "",
        controlEndTime: "",
        time: "",
        manageName: "",
        phone: "",
        managePhone: [],
        warningPersonCheckListDtoList: [
          {
            documentType: "",
            idNumber: "",
            name: "",
            warningType: "",
          },
        ],
        correctList: {
          correct: [],
          incorrect: [],
        },
      },
      oneselfBelowList: [],
      // 预警级别
      warning_list: [
        { code: 1, desc: "Ⅰ级" },
        { code: 2, desc: "Ⅱ级" },
        { code: 3, desc: "Ⅲ级" },
        { code: 4, desc: "Ⅳ级" },
        { code: 5, desc: "Ⅴ级" },
      ],
      rules: {
        // accountId: [
        //   {
        //     required: true,
        //     type: "number",
        //     whitespace: true,
        //     message: "不能为空!",
        //     trigger: ["change", "blur"],
        //   },
        // ],
        warningGrade: [
          {
            required: true,
            message: "请选择预警级别",
            trigger: "change",
          },
        ],
        taskName: [
          {
            required: true,
            message: "请输入任务名称",
            trigger: "blur",
          },
        ],
        controlAdminId: [
          {
            required: true,
            message: "请选择布控单位",
            trigger: "change",
          },
        ],
        time: [
          {
            required: true,
            message: "请选择布控时间",
            trigger: "change",
          },
        ],
        manageName: [
          {
            required: true,
            message: "请输入负责人姓名",
            trigger: "blur",
          },
        ],
        phone: [
          {
            required: true,
            message: "请输入负责人手机号,中文逗号隔开",
            trigger: "blur",
          },
          {
            validator: (rule, value, callback) => {
              const numbers = value.split("，");
              if (numbers.every((num) => /^[0-9]+$/.test(num.trim()))) {
                callback();
              } else {
                callback(new Error("请输入正确格式的电话号码或用中文逗号分隔"));
              }
            },
            trigger: "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: [],
      //
      arr: [],
      dialogTitle: "",
      isEdit: false,
    };
  },
  computed: {
    // 批量注册-返回向下取整，减少渲染次数
    makePercent() {
      return Math.floor((this.hasDealNumber / this.allNumber) * 100);
    },
  },
  created() {
    // console.log(this.option,7);
  },
  methods: {
    checkRole,
    open(edit) {
      // if (checkRole([0])) {
      this.dialogVisible = true;
      this.getOneselfBelowList();
      this.$nextTick(() => {
        this.$refs.form.resetFields();
        if (edit) {
          console.log(edit);
          this.dialogTitle = "编辑批量导入";
          this.isEdit = true;
          this.form = {
            ...JSON.parse(JSON.stringify(edit)),
            time: [edit.controlStartTime, edit.controlEndTime],
            phone: edit.managePhone.join("，"),
          };
        } else {
          this.dialogTitle = "批量导入";
          this.isEdit = false;
        }
      });
      // } else {
      // this.batchUploadResult();
      // }
    },
    async getOneselfBelowList() {
      const res = await getwarningPersonOneselfBelowList();
      this.oneselfBelowList = res.data;
    },
    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.arr = [];
      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));
        // console.log(data, 1);
        // console.log(item, 2);
        let warningParams = {
          name: item["人员姓名"],
          documentType: item["证件类型"],
          idNumber: item["证件号"],
          warningType: item["布控人员类型"],
        };
        // console.log(data.warningPersonCheckListDtoList.name, 4);
        // data.warningPersonCheckListDtoList[0].name = item["人员姓名"];
        // data.warningPersonCheckListDtoList[0].documentType = item["证件类型"];
        // data.warningPersonCheckListDtoList[0].idNumber = item["证件号"];
        // data.warningPersonCheckListDtoList[0].warningType =
        //   item["布控人员类型"];
        if (
          warningParams.name &&
          warningParams.documentType &&
          warningParams.idNumber &&
          warningParams.warningType
        ) {
          let err = "";
          if (warningParams.documentType == "身份证号") {
            warningParams.documentType = 2;
          } else if (warningParams.documentType == "护照") {
            warningParams.documentType = 1;
          }
          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(
              warningParams.idNumber && warningParams.documentType === 2
            )
          ) {
            err = "身份证长度或格式有误";
          }

          if (err) {
            this.batchUploadResultList.push({
              index: "第" + index + "行",
              err: err,
            });
          } else {
            try {
              this.arr.push(warningParams);
              // console.log(this.arr);
              // const controlStartTime = this.form.time[0];
              // const controlEndTime = this.form.time[1];
              // const managePhone = this.form.phone
              //   .split("，")
              //   .map((item) => item);
              // // const res11 = {
              // //   ...data,
              // //   controlStartTime,
              // //   controlEndTime,
              // //   managePhone,
              // // };
              // // console.log(res11, 333);
              // // return;
              // await getwarningPersonInsert({
              //   ...data,
              //   controlStartTime,
              //   controlEndTime,
              //   managePhone,
              // });
            } catch (err) {
              // console.log(err);
              this.batchUploadResultList.push({
                index: "第" + index + "行",
                err: err,
              });
            }
          }
        } else {
          if (!warningParams.name) {
            this.batchUploadResultList.push({
              index: "第" + index + "行",
              err: "人员姓名不能为空",
            });
          }
          if (!warningParams.documentType) {
            this.batchUploadResultList.push({
              index: "第" + index + "行",
              err: "证件类型不能为空",
            });
          }
          if (!warningParams.idNumber) {
            this.batchUploadResultList.push({
              index: "第" + index + "行",
              err: "证件号不能为空",
            });
          }
          if (!warningParams.warningType) {
            this.batchUploadResultList.push({
              index: "第" + index + "行",
              err: "布控人员类型不能为空",
            });
          }
        }
        this.hasDealNumber += 1;
        this.waitDealNumber -= 1;
        this.makeScrollDown();
        // 继续调用
        this.doSubmitUrl(correctList, ++index);
      } else {
        if (this.batchUploadResultList.length == 0) {
          const controlStartTime = this.form.time[0];
          const controlEndTime = this.form.time[1];
          const managePhone = this.form.phone.split("，").map((item) => item);
          if (this.isEdit) {
            await getwarningPersonRectify({
              ...this.form,
              controlStartTime,
              controlEndTime,
              managePhone,
              warningPersonCheckListDtoList: this.arr,
            });
          } else {
            await getwarningPersonInsert({
              ...this.form,
              controlStartTime,
              controlEndTime,
              managePhone,
              warningPersonCheckListDtoList: this.arr,
            });
          }
        }
        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;
}
.flex {
  width: 100%;
  display: flex;
  justify-content: flex-start;
  align-items: center;
}
.dialog-top {
  padding: 16px;
  background-color: #ff5c651a;
  color: #ff4747;
  font-size: 16px;
  font-weight: 600;
  border-radius: 10px;
  margin-bottom: 10px;
}
</style>
