<template>
  <div class="app-container">
    <!--操作区-->
    <div style="display: flex;flex-wrap: wrap">
      <div :style="`width: calc(${role == 3 ? '280px' : '150px'})`">
        <el-button
          type="primary"
          icon="el-icon-plus"
          class="margin-left"
          @click="create('add')"
        >添加单位人员</el-button>
        <el-button
          v-if="role == 3"
          type="primary"
          icon="el-icon-download"
          class="margin-left"
          @click="download"
        >下载模板</el-button>
        <div
          v-if="role == 3"
          style="margin: 10px 0"
        >
          <a
            href="javascript:;"
            class="file"
            style="margin: 0"
          >批量导入<input
            ref="file"
            type="file"
            name="file"
            @change="batchImport($event)"
          ></a>
        </div>
      </div>
      <!--搜索区-->
      <div class="float" :style="`width: calc(100% - ${role == 3 ? '300px' : '150px'})`">
        <el-select
          v-if="role == 2"
          v-model="page.data.adminId"
          filterable
          clearable
          placeholder="请选择单位"
          class="margin-left input m-b-10"
        >
          <el-option
            v-for="item in unit_list"
            :key="item.adminId"
            :label="item.username"
            :value="item.adminId"
          />
        </el-select>
        <el-input
          v-model="page.data.name"
          placeholder="请输入姓名"
          clearable
          class="margin-left input"
        />
        <el-input
          v-model="page.data.phone"
          placeholder="请输入手机号"
          clearable
          class="margin-left input"
        /><el-input
          v-model="page.data.idNumber"
          placeholder="请输入身份证号"
          clearable
          class="margin-left input"
        />
        <el-select
          v-model="page.data.status"
          filterable
          clearable
          placeholder="请选择实名状态"
          class="margin-left input m-b-10"
        >
          <el-option
            v-for="item in type_list"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
        <el-date-picker
          v-model="page.data.startTime"
          type="datetime"
          placeholder="选择起始时间"
          value-format="yyyy-MM-dd HH:mm:ss"
          class="margin-left"
        />
        <el-date-picker
          v-model="page.data.endTime"
          type="datetime"
          placeholder="选择结束时间"
          value-format="yyyy-MM-dd HH:mm:ss"
          class="margin-left"
        />
        <el-button
          type="primary"
          icon="el-icon-search"
          class="margin-left"
          @click="fetchData"
        >搜索</el-button>
      </div>
    </div>
    <!--主表格-->
    <el-table
      ref="table_form"
      v-loading="listLoading"
      class="table"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
    >
      <el-table-column label="序号" align="center" width="80px">
        <template slot-scope="scope">
          {{ indexMethod(scope.$index) }}
        </template>
      </el-table-column>
      <el-table-column v-if="role != 3" label="所属单位" align="center">
        <template slot-scope="scope">
          {{ scope.row.username }}
        </template>
      </el-table-column>
      <el-table-column label="头像（证件照）" align="center">
        <template slot-scope="scope">
          <el-image
            v-if="scope.row.avatar"
            class="table-img"
            :src="scope.row.avatar"
            :preview-src-list="[scope.row.avatar]"
          />
          <span v-else>暂无</span>
        </template>
      </el-table-column>
      <el-table-column label="实名照片" align="center">
        <template slot-scope="scope">
          <el-image
            v-if="scope.row.photo"
            class="table-img"
            :src="scope.row.photo"
            :preview-src-list="[scope.row.photo]"
          />
          <span v-else>暂无</span>
        </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 | desensitization(6, 14) }}
        </template>
      </el-table-column>
      <el-table-column label="手机号 " align="center">
        <template slot-scope="scope">
          {{ scope.row.phone | desensitization(3, 7) }}
        </template>
      </el-table-column>
      <el-table-column label="实名状态 " align="center">
        <template slot-scope="scope">
          {{ scope.row.content }}
          <el-tag v-if="!scope.row.status" type="info">未实名</el-tag>
          <el-tag v-if="scope.row.status" type="success">已实名</el-tag>
        </template>
      </el-table-column>
      <!-- <el-table-column label="单位全称" align="center">
        <template slot-scope="scope">
          {{ scope.row.createTime }}
        </template>
      </el-table-column> -->
      <el-table-column label="所在部门" align="center">
        <template slot-scope="scope">
          {{ scope.row.deptName }}
        </template>
      </el-table-column>
      <el-table-column v-if="adminType != 2" label="岗位名称" align="center">
        <template slot-scope="scope">
          {{ scope.row.postName }}
        </template>
      </el-table-column>
      <el-table-column label="合同截止日期" align="center">
        <template slot-scope="scope">
          {{ scope.row.contractEndDate }}
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center">
        <template slot-scope="scope">
          {{ scope.row.createTime }}
        </template>
      </el-table-column>
      <el-table-column align="center" prop="" label="操作区" width="200">
        <template slot-scope="scope">
          <el-button
            type="danger"
            size="small"
            @click="deleteFun(scope.row.userId)"
          >删除</el-button>
          <el-button
            type="primary"
            size="small"
            @click="create('update', scope.row)"
          >编辑</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--分页栏-->
    <pagination
      :total="total"
      :page.sync="page.pageNum"
      :limit.sync="page.pageSize"
      @pagination="fetchData"
    />
    <!--对话框-->
    <el-dialog
      :title="dialogTitle[dialogType]"
      :visible.sync="dialogVisible"
      width="900px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="120px"
        label-position="left"
      >
        <div v-if="role != 3" class="flex">
          <el-form-item label="所属单位" prop="adminId" class="form-item-style">
            <el-select
              v-model="form.adminId"
              :disabled="dialogType == 'update'"
              filterable
              clearable
              placeholder="请选择单位"
              style="width: 100%"
              @change="getPostRecursionList"
            >
              <el-option
                v-for="item in unit_list"
                :key="item.adminId"
                :label="item.username"
                :value="item.adminId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="单位简称" prop="adminId" class="form-item-style">
            <el-select
              v-model="form.adminId"
              :disabled="dialogType == 'update'"
              filterable
              clearable
              placeholder="单位简称"
              style="width: 100%"
              @change="getPostRecursionList"
            >
              <el-option
                v-for="item in unit_list"
                :key="item.adminId"
                :label="item.unitConciseName"
                :value="item.adminId"
              />
            </el-select>
          </el-form-item>
        </div>

        <el-form-item label="绑定部门" prop="link">
          <el-cascader
            v-model="form.link"
            style="width: 100%"
            :options="department_list"
            :props="defaultParams"
            clearable
            @change="postList"
          />
        </el-form-item>
        <el-form-item v-if="adminType == 1" label="绑定岗位" prop="deptPostId">
          <el-select
            v-model="form.deptPostId"
            filterable
            clearable
            placeholder="请选择岗位"
            style="width: 100%"
          >
            <el-option
              v-for="item in post_list"
              :key="item.deptPostId"
              :label="item.postName"
              :value="item.deptPostId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="合同截止日期" prop="contractEndDate">
          <el-date-picker
            v-model="form.contractEndDate"
            style="width: 100%"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="合同截止日期"
          />
        </el-form-item>
        <div class="flex">
          <el-form-item label="姓名" class="form-item-style" prop="name">
            <el-input
              v-model.trim="form.name"
              :disabled="dialogType == 'update'"
              placeholder="请输入人员姓名"
            />
          </el-form-item>
          <el-form-item label="身份证" class="form-item-style" prop="idNumber">
            <el-input
              v-model.trim="form.idNumber"
              :disabled="dialogType == 'update'"
              placeholder="请输入人员身份证"
            />
          </el-form-item>
        </div>
        <div class="flex">
          <el-form-item label="手机号" class="form-item-style" prop="phone">
            <el-input
              v-model.trim="form.phone"
              :disabled="dialogType == 'update'"
              maxlength="11"
              show-word-limit
              placeholder="请输入手机号"
            />
          </el-form-item>
          <el-form-item
            label="证件照"
            prop="avatar"
            class="form-item-style special"
          >
            <UploadImg :image="form.avatar" type="avatar" @getImg="getImg" />
          </el-form-item>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false"> 取消 </el-button>
        <el-button type="primary" @click="addOrUpdate"> 确定 </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
          style="margin-top: 10px"
          :percentage="makePercent"
          :format="formatProgress"
        />
        <el-table
          ref="batch_upload_result"
          v-loading="false"
          class="table"
          :data="batchUploadResultList"
          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.err }}
            </template>
          </el-table-column>
        </el-table>
        <div v-show="hasCompleted" style="text-align: center; margin: 20px 0">
          <el-button type="primary" @click="drawerVisible = false">
            我已知晓
          </el-button>
          <el-button
            v-show="batchUploadResultList.length > 0"
            type="warning"
            @click="downloadBatchUploadErrorList"
          >
            下载错误列表文件
          </el-button>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import Pagination from '@/components/Pagination'
import UploadImg from '@/components/UploadImg'
import {
  userdelete,
  userInsert,
  userUpdate,
  userGetPageList,
  excelInput
} from '@/api/user'
import { belowList, getPostRecursionList, postList } from '@/api/user_manage'
import { readExcel } from '@/utils/getExcelList'
export default {
  components: { Pagination, UploadImg },
  filters: {},
  filters: {
    // 脱敏
    desensitization(string = '', start, end) {
      if (string) {
        var star = ''
        function makeStar(number) {
          if (number > 0) {
            star += '*'
            return makeStar(--number)
          } else {
            return star
          }
        }
        return (
          string.substring(0, start) +
          makeStar(end - start) +
          string.substring(end)
        )
      }
    }
  },
  data() {
    return {
      role: this.$store.getters.role,
      adminType: this.$store.getters.adminType,
      adminId: this.$store.getters.adminId,
      // 主表格&主表格加载状态
      list: [],
      listLoading: true,
      // 分页参数
      page: {
        data: {
          adminId: null,
          idNumber: null,
          endTime: null,
          startTime: null,
          name: null,
          phone: null,
          status: null
        },
        pageNum: 1,
        pageSize: 10
      },
      total: 0,
      // 是否显示对话框
      dialogVisible: false,
      // 对话框标题
      dialogTitle: {
        add: '添加单位人员',
        update: '编辑单位人员'
      },
      dialogType: 'add',
      form_copy: null,
      // 添加角色参数
      form: {
        adminId: null,
        deptPostId: null,
        contractEndDate: null,
        name: null,
        idNumber: null,
        phone: null,
        avatar: null,
        link: null
      },
      // 验证规则
      rules: {
        link: [{ required: true, message: '请选择', trigger: 'change' }],
        adminId: [{ required: true, message: '请选择', trigger: 'change' }],
        deptPostId: [{ required: true, message: '请选择', trigger: 'change' }],
        contractEndDate: [
          { required: true, message: '请选择', trigger: 'change' }
        ],
        name: [{ required: true, message: '请输入', trigger: 'change' }],
        idNumber: [{ required: true, message: '请输入', trigger: 'change' }],
        phone: [{ required: true, message: '请输入', trigger: 'change' }]
      },
      type_list: [
        { id: 0, name: '未实名' },
        { id: 1, name: '已实名' }
      ],
      unit_list: [],
      department_list: [],
      post_list: [],
      defaultParams: {
        checkStrictly: true,
        label: 'deptName',
        value: 'departmentId',
        children: 'deptRsList',
        multiple: false
      },
      // 批量人员注册-处理提示值
      hasDealNumber: 0,
      waitDealNumber: 0,
      allNumber: 0,
      hasCompleted: false,
      // 批量注册人员-抽屉控制值
      drawerVisible: false,
      batchUploadResultList: []
    }
  },
  computed: {
    // 批量注册人员-返回向下取整，减少渲染次数
    makePercent() {
      return Math.floor((this.hasDealNumber / this.allNumber) * 100)
    }
  },
  watch: {},
  created() {
    this.fetchData()
    if (this.role !== 3) {
      this.belowList()
    }
    if (this.role == 3) {
      this.getPostRecursionList(this.adminId)
    }
    this.form_copy = JSON.parse(JSON.stringify(this.form))
  },
  methods: {
    // 获取列表数据
    fetchData() {
      this.listLoading = true
      userGetPageList(this.page).then((res) => {
        this.list = res.data.records
        this.total = res.data.total
        this.listLoading = false
      })
    },
    // 打开添加角色对话框
    async create(type, row) {
      if (type === 'add') {
        this.form = JSON.parse(JSON.stringify(this.form_copy))
      } else {
        this.form = Object.assign(this.form, row)
        await this.getPostRecursionList(this.form.adminId, 1)
        await this.postList([this.form.deptId], 1)
        this.form.link = this.form.link.map(Number)
      }
      this.dialogType = type
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs['form'].clearValidate()
      })
    },
    // 确定添加/编辑
    addOrUpdate() {
      this.$refs['form'].validate(async(valid) => {
        if (valid) {
          let res
          this.form.deptId = this.form.link[this.form.link.length - 1]
          if (this.dialogType === 'add') {
            res = await userInsert(this.form)
          } else {
            res = await userUpdate(this.form)
          }
          if (res.code == 200) {
            this.dialogVisible = false
            this.fetchData()
            this.$message({
              type: 'success',
              message: '操作成功!'
            })
          }
        }
      })
    },
    // 删除角色
    deleteFun(id) {
      this.$confirm('确定要删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(() => {
        userdelete(id).then((res) => {
          this.fetchData()
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        })
      })
    },
    // 账号
    belowList() {
      this.form.deptPostId = null
      this.form.link = []
      belowList().then((res) => {
        this.unit_list = res.data
      })
    },
    // 部门
    getPostRecursionList(e, type) {
      if (!type) {
        this.form.link = []
        this.form.deptPostId = null
      }
      if (e) {
        getPostRecursionList(e).then((res) => {
          this.department_list = res.data
        })
      }
    },
    // 岗位
    postList(e, type) {
      if (!type) {
        this.form.deptPostId = null
      }
      if (e) {
        const id = e[e.length - 1]
        postList(id).then((res) => {
          this.post_list = res.data
        })
      }
    },
    // 图片赋值
    getImg(val, index, type) {
      this.form[type] = val
    },
    // 下载模板
    download() {
      window.location.href = process.env.VUE_APP_BASE_API + '/excel/user.xlsx'
    },
    // 批量导入
    async batchImport(e) {
      this.listLoading = true
      var files = e.currentTarget.files
      if (!files.length) {
        return
      }
      let data = await readExcel(files[0]) // file指的是获取的excel文件对象，如e.file
      const newData = []
      data.forEach((i) => {
        for (const key in i) {
          if (i[key]) {
            newData.push(i)
            return
          }
        }
      })
      data = newData
      this.listLoading = false
      this.allNumber = data.length
      this.drawerVisible = true
      this.doUploadAddUserInfo(0, data)
    },
    // 递归调用校验数据并请求
    async doUploadAddUserInfo(i, data) {
      if (i > data.length - 1) {
        this.hasCompleted = true
        this.fetchData()
        this.$message.success('导入已完成！')
        return
      }
      const form = {}
      form.name = data[i]['姓名']
      form.phone = data[i]['手机号']
      form.idNumber = data[i]['身份证号']
      form.deptNameList1 = data[i]['部门名称']
      form.postName = data[i]['岗位名称']
      form.contractEndDate = data[i]['合同终止日期']
      await this.isPassFun(form, i).then(async(res) => {
        let timeout = 0
        if (res.isOk) {
          await this.addUserInfo(data, form, i)
        } else {
          this.getFileList1(data, i, res, form)
          timeout = 0
        }
        this.hasDealNumber = i + 1
        this.waitDealNumber = data.length - (i + 1)
        setTimeout(() => {
          this.doUploadAddUserInfo(++i, data)
        }, timeout)
      })
    },
    // 校验模板数据内容
    async isPassFun(form, i) {
      const isPass = {
        isOk: true,
        incorrect: {
          name: `第${i + 1}行`,
          err: ''
        }
      }
      if (!form.name) {
        isPass.incorrect.err = '姓名为必填项'
        isPass.isOk = false
        return isPass
      }
      if (!form.idNumber) {
        isPass.incorrect.err = '身份证为必填项'
        isPass.isOk = false
        return isPass
      }
      if (
        form.idNumber &&
        !/(^\d{15}$)|(^\d{17}(\d|X|x)$)/.test(form.idNumber)
      ) {
        isPass.isOk = false
        isPass.incorrect.err = '身份证长度或格式有误'
        return isPass
      }
      if (form.phone && !/^[0-9]*$/.test(form.phone)) {
        isPass.isOk = false
        isPass.incorrect.err = '手机号只能由数字组成'
        return isPass
      }
      if (!form.deptNameList1) {
        isPass.incorrect.err = '部门名称为必填项'
        isPass.isOk = false
        return isPass
      }
      form.deptNameList = form.deptNameList1.split('-')
      if (!form.postName) {
        isPass.incorrect.err = '岗位名称为必填项'
        isPass.isOk = false
        return isPass
      }
      if (form.contractEndDate) {
        const reg = /^\d{4}-\d{2}-\d{2}$/
        if (!reg.test(form.contractEndDate)) {
          isPass.isOk = false
          isPass.incorrect.err = '合同终止日期格式有误'
          return isPass
        }
      }
      return new Promise((resolve) => {
        resolve(isPass)
      })
    },
    // 批量导入-调用添加员工接口
    async addUserInfo(data, form, i) {
      await excelInput(form)
        .then((res) => {})
        .catch((err) => {
          this.batchUploadResultList.push({ name: `第${i + 1}行`, err: err })
          this.makeScrollDown()
        })
    },
    // 批量导入-推入错误信息
    getFileList1(data, i, isPass) {
      // this.initAddress(this.user_form.contents);
      this.batchUploadResultList.push(isPass.incorrect)
      this.makeScrollDown()
    },
    // 批量注册人员-保持滚动条在最底部
    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)
    },
    // 返回列表序号
    indexMethod(index) {
      return (this.page.pageNum - 1) * this.page.pageSize + index + 1
    }
  }
}
</script>
<style scoped lang="scss">
</style>
