<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="120px"
      >
        <el-form-item v-if="roleId == 1" label="所属账号" :required="roleId == 1">
          <el-select
            v-model="form.account"
            style="width: 100%"
            filterable
            clearable
            placeholder="请选择账号"
          >
            <el-option
              v-for="item in accountList"
              :key="item.code"
              :label="item.label"
              :value="item.code"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="任务名称" prop="taskName">
          <el-input
            v-model="form.taskName"
            placeholder="请输入任务名称"
          />
        </el-form-item>

        <el-form-item label="有效期开始时间" prop="startTime">
          <el-date-picker
            v-model="form.startTime"
            type="datetime"
            placeholder="选择时间"
            value-format="yyyy-MM-dd HH:mm:ss"
            format="yyyy-MM-dd HH:mm:ss"
            :picker-options="startPickerOptions"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="有效期结束时间" prop="endTime">
          <el-date-picker
            v-model="form.endTime"
            type="datetime"
            placeholder="选择时间"
            value-format="yyyy-MM-dd HH:mm:ss"
            format="yyyy-MM-dd HH:mm:ss"
            :picker-options="endTimePickerOptions"
            style="width: 100%"
          />
        </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>
    <!-- 批量注册人员-抽屉 -->
    <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.name }}
            </template>
          </el-table-column>
          <el-table-column label="身份证号" align="center">
            <template slot-scope="scope">
              {{ scope.row.IDNumber }}
            </template>
          </el-table-column>
          <el-table-column label="人员类型" align="center">
            <template slot-scope="scope">
              {{ scope.row.typeName }}
            </template>
          </el-table-column>
          <el-table-column label="点位" align="center">
            <template slot-scope="scope">
              {{ scope.row.pointer }}
            </template>
          </el-table-column>
          <el-table-column label="商铺名称" align="center">
            <template slot-scope="scope">
              {{ scope.row.tenantName }}
            </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 BatchUpload from '@/components/BatchUpload';

export default {
  components: { BatchUpload },
  props: {
    accountList: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      buyList: [],
      typeList: [
        {
          label: '员工',
          code: 'a'
        },
        {
          label: '商户',
          code: 'b'
        },
        {
          label: '居民',
          code: 'c'
        },
        {
          label: '其他',
          code: 'd'
        }
      ],
      form: {
        account: null,
        taskName: null,
        startTime: null,
        endTime: null,
        correctList: {
          correct: [],
          incorrect: []
        }
      },
      rules: {
        taskName: [
          { required: true, message: '请输入任务名称', trigger: 'blur' }
        ],
        startTime: [
          { required: true, message: '请选择有效期开始时间', trigger: 'change' }
        ],
        endTime: [
          { required: true, message: '请选择有效期结束时间', trigger: 'change' }
        ],
        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: []
    };
  },
  computed: {
    roleId() {
      return this.$store.getters.role;
    },
    // 批量注册-返回向下取整，减少渲染次数
    makePercent() {
      return Math.floor((this.hasDealNumber / this.allNumber) * 100);
    },
    startPickerOptions() {
      const _this = this;
      return {
        disabledDate(time) {
          if (_this.form.endTime && _this.form.endTime !== '') {
            return time.getTime() > new Date(_this.form.endTime).getTime(); // 禁用true值
          }
          return false;
        }
      };
    },
    endTimePickerOptions() {
      const _this = this;
      return {
        disabledDate(time) {
          if (_this.form.startTime && _this.form.startTime !== '') {
            return time.getTime() < new Date(_this.form.startTime).getTime(); // 禁用true值
          }
          return false;
        }
      };
    }
  },
  watch: {},
  created() {
  },
  methods: {
    open() {
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs.form.resetFields();
      });
    },
    dialogClose() {
      this.$refs.batchUploadRef.clearFile();
    },
    batchUploadResult(correctList) {
      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);
    },
    verifyIdNumber(idNumber) {
      return /(^\d{15}$)|(^\d{17}(\d|X|x)$)/.test(idNumber);
    },
    // 批量注册人员-并提交至添加到接口
    async doSubmitUrl(correctList, index) {
      console.log(correctList, index);
      const that = this;
      if (index <= correctList.correct.length - 1) {
        const item = correctList.correct[index];
        if (item['姓名'] && item['身份证号'] && item['人员类型']) {
          // 组装数据上传
          let data = JSON.parse(JSON.stringify(this.form));
          const typeIndex = that.typeList.findIndex(
            (i) => i.label === item['人员类型'].trim()
          );
          const uploadData = {
            name: item['姓名']?.trim() || '',
            IDNumber: item['身份证号']?.trim() || '',
            typeName: item['人员类型']?.trim() || '',
            point: item['点位']?.trim() || '',
            tenantName: item['商铺名称']?.trim() || ''
          };
          if (typeIndex === -1) {
            this.batchUploadResultList.push({
              ...uploadData,
              err: '人员类型查找失败'
            });
            this.makeScrollDown();
            // 继续调用
            this.doSubmitUrl(correctList, ++index);
            return;
          }
          uploadData.type = that.typeList[typeIndex].code;
          if (!this.verifyIdNumber(uploadData.IDNumber)) {
            this.batchUploadResultList.push({
              ...uploadData,
              err: '身份证不合法'
            });
            this.makeScrollDown();
            // 继续调用
            this.doSubmitUrl(correctList, ++index);
            return;
          }
          data = {
            ...data,
            ...uploadData
          };
          console.log('数据===>', typeIndex, data);
          if (typeIndex > -1) {
            try {
              console.log(data);
              // await configAdd(data);
            } catch (err) {
              console.log(err);
              this.batchUploadResultList.push({
                name: data.name,
                IDNumber: data.IDNumber,
                typeName: data.typeName,
                point: data.point,
                tenantName: data.tenantName,
                err: err
              });
            }
          } else {
            this.batchUploadResultList.push({
              name: item['姓名'] || '',
              IDNumber: item['身份证号'] || '',
              err: '身份证号有误'
            });
          }
        } else {
          this.batchUploadResultList.push({
            name: item['姓名'] || '',
            IDNumber: item['身份证号'] || '',
            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姓名\t错误原因\n';
      for (let i = 0; i < this.batchUploadResultList.length; i++) {
        string +=
          (i + 1).toString() +
          '\t' +
          list[i].name +
          '\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%;
}
</style>
