<template>
  <div class="app-container">
    <!--操作区-->
    <el-button
      type="primary"
      icon="el-icon-plus"
      class="margin-bottom"
      @click="create('add')"
    >添加账号</el-button>
    <el-button
      type="primary"
      icon="el-icon-download"
      class="margin-left"
      @click="download"
    >下载模板</el-button>
    <a
      v-loading="loading"
      href="javascript:;"
      class="file"
    >批量导入<input
      ref="file"
      type="file"
      name="file"
      @change="upload($event)"
    ></a>
    <!--搜索区-->
    <div class="float">
      <el-select
        v-model="page.data.unitType"
        filterable
        clearable
        placeholder="请选择单位类型"
        popper-class="unitType-select"
        class="margin-left input m-b-10"
      >
        <el-option
          v-for="item in unitTypeList"
          :key="item.code"
          :label="item.desc"
          :value="item.code"
        >
          <div class="desc">{{ item.desc }}</div>
          <div class="detail">{{ item.detail }}</div>
        </el-option>
      </el-select>
      <el-input
        v-model="page.data.unitAllName"
        placeholder="请输入单位全称"
        clearable
        class="margin-left input"
      />
      <el-input
        v-model="page.data.unitConciseName"
        placeholder="请输入单位简称"
        clearable
        class="margin-left input"
      />
      <el-input
        v-model="page.data.manageName"
        placeholder="请输入管理员姓名"
        clearable
        class="margin-left input"
      />
      <el-input
        v-model="page.data.managePhone"
        placeholder="请输入管理员手机号"
        clearable
        class="margin-left input"
      />
      <el-button
        type="primary"
        icon="el-icon-search"
        class="margin-left"
        @click="fetchData"
      >搜索</el-button>
    </div>
    <!--主表格-->
    <el-table
      ref="table_form"
      v-loading="enumLoading || 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 label="单位类型" align="center">
        <template slot-scope="scope">
          <div
            v-if="scope.row.unitType"
            style="background-color: #ecf5ff;
            border: 1px solid #d9ecff;
    padding: 0 10px;
    line-height: 24px;
    font-size: 12px;
    color: #409EFF;border-radius: 4px;"
          >{{ (unitTypeList||[])[scope.row.unitType - 1].desc }}【{{ (unitTypeList||[])[scope.row.unitType - 1].detail }}】</div>
        </template>
      </el-table-column>
      <el-table-column label="账号名称" align="center">
        <template slot-scope="scope">
          {{ scope.row.username }}
        </template>
      </el-table-column>
      <el-table-column label="单位全称" align="center">
        <template slot-scope="scope">
          {{ scope.row.unitAllName }}
        </template>
      </el-table-column>
      <el-table-column label="单位简称" align="center">
        <template slot-scope="scope">
          {{ scope.row.unitConciseName }}
        </template>
      </el-table-column>
      <el-table-column label="管理员姓名" align="center">
        <template slot-scope="scope">
          {{ scope.row.manageName }}
        </template>
      </el-table-column>
      <el-table-column label="管理员手机号 " align="center">
        <template slot-scope="scope">
          {{ scope.row.managePhone | desensitization(3, 7) }}
        </template>
      </el-table-column>
      <el-table-column label="企业代码" align="center">
        <template slot-scope="scope">
          {{ scope.row.unitCode }}
        </template>
      </el-table-column>
      <!-- <el-table-column label="单位规模" align="center">
        <template slot-scope="scope">
          <el-tag type="success" v-if="scope.row.unitScale === 1"
            >0-99人</el-tag
          >
          <el-tag type="primary" v-if="scope.row.unitScale === 2"
            >100-499人</el-tag
          >
          <el-tag type="danger" v-if="scope.row.unitScale === 3"
            >500以上</el-tag
          >
        </template>
      </el-table-column> -->
      <el-table-column label="营业执照照片" align="center">
        <template slot-scope="scope">
          <el-image
            v-if="scope.row.unitBusinessImg"
            class="table-img"
            :src="scope.row.unitBusinessImg"
            :preview-src-list="[scope.row.unitBusinessImg]"
          />
        </template>
      </el-table-column>
      <el-table-column label="相关材料" align="center">
        <template v-if="scope.row.attachmentList.length>0" slot-scope="scope">
          <el-image
            v-for="(item, index) in scope.row.attachmentList"
            :key="index"
            class="table-img"
            :src="item"
            :preview-src-list="[item]"
          />
        </template>
      </el-table-column>
      <el-table-column label="收费标准" align="center">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.isCharge" type="primary">收费</el-tag>
          <el-tag v-if="!scope.row.isCharge" 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 align="center" prop="" label="操作区" width="200">
        <template slot-scope="scope">
          <el-button
            type="danger"
            size="small"
            @click="deleteFun(scope.row.adminId)"
          >删除</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="1000px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="120px"
        label-position="left"
      >
        <div class="wrap-content">
          <div class="wrap-content__item">
            <el-form-item
              label="单位类型"
              class="form-item-style"
              prop="unitType"
            >
              <el-select
                v-model="form.unitType"
                filterable
                clearable
                placeholder="请选择单位类型"
                popper-class="unitType-select"
                style="width: 100%"
                autocomplete="off"
              >
                <el-option
                  v-for="item in unitTypeList"
                  :key="item.code"
                  :label="item.desc"
                  :value="item.code"
                >
                  <div class="desc">{{ item.desc }}</div>
                  <div class="detail">{{ item.detail }}</div>
                </el-option>
              </el-select>
            </el-form-item>
          </div>
          <div class="wrap-content__item">
            <el-form-item
              label="收费标准"
              prop="isCharge"
              class="form-item-style"
            >
              <el-radio-group v-model="form.isCharge">
                <el-radio :label="true">收费</el-radio>
                <el-radio :label="false">免费</el-radio>
              </el-radio-group>
            </el-form-item>
          </div>
          <div class="wrap-content__item">
            <el-form-item
              label="账号名称"
              class="form-item-style"
              prop="username"
            >
              <el-input
                v-model.trim="form.username"
                :disabled="dialogType === 'update'"
                placeholder="请输入账号名称"
              />
            </el-form-item>
          </div>
          <div class="wrap-content__item">
            <el-form-item
              label="账号密码"
              class="form-item-style"
              :prop="dialogType === 'update' ? '' : 'password'"
            >
              <el-input
                v-model.trim="form.password"
                placeholder="请输入账号密码"
                show-password
              />
            </el-form-item>
          </div>
          <div class="wrap-content__item">
            <el-form-item
              label="管理员姓名"
              class="form-item-style"
              prop="manageName"
            >
              <el-input
                v-model.trim="form.manageName"
                maxlength="20"
                show-word-limit
                placeholder="请输入管理员姓名"
              />
            </el-form-item>
          </div>
          <div class="wrap-content__item">
            <el-form-item
              label="管理员手机号"
              class="form-item-style"
              prop="managePhone"
            >
              <el-input
                v-model.trim="form.managePhone"
                maxlength="11"
                show-word-limit
                placeholder="请输入管理员手机号"
              />
            </el-form-item>
          </div>
          <div class="wrap-content__item">
            <el-form-item
              label="单位全称"
              class="form-item-style"
              prop="unitAllName"
            >
              <el-input
                v-model.trim="form.unitAllName"
                maxlength="100"
                show-word-limit
                placeholder="请输入单位全称"
              />
            </el-form-item>
          </div>
          <div class="wrap-content__item">
            <el-form-item
              label="单位简称"
              class="form-item-style"
              prop="unitConciseName"
            >
              <el-input
                v-model.trim="form.unitConciseName"
                maxlength="50"
                show-word-limit
                placeholder="请输入单位简称"
              />
            </el-form-item>
          </div>
          <div class="wrap-content__item">
            <el-form-item
              label="企业代码"
              class="form-item-style special"
              prop="unitCode"
            >
              <el-input
                v-model.trim="form.unitCode"
                placeholder="请输入请输入企业代码"
              />
            </el-form-item>
          </div>
        </div>
        <!-- <div class="flex">
          <el-form-item
            label="单位规模"
            class="form-item-style"
            prop="unitScale"
          >
            <el-select
              filterable
              clearable
              v-model="form.unitScale"
              placeholder="请选择单位规模"
              style="width: 100%"
            >
              <el-option
                v-for="item in unitScale_list"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </div> -->
        <div class="wrap-content__item">
          <el-form-item
            label="营业执照照片"
            prop="unitBusinessImg"
            class="form-item-style special"
          >
            <UploadImg
              :image="form.unitBusinessImg"
              type="unitBusinessImg"
              @getImg="getImg"
            />
          </el-form-item>
          <!-- <el-form-item
            label="单位准入函件"
            prop="unitAllowInFile"
            class="form-item-style"
          >
            <UploadImg
              :image="form.unitAllowInFile"
              @getImg="getImg"
              type="unitAllowInFile"
            />
          </el-form-item> -->
        </div>
        <TagCard :title="`附件：相关材料（${form.attachmentList.length} / 8）`" style="margin-top: 20px">
          <p>
            <span class="red">*</span>
            1、从事民航生产运输、服务保障及其他工作的证明材料；2、统一社会信用代码、企业营业执照等；3、本单位通行证管理责任部门
            (岗位)设置及工作职责等；4、本单位通行证管理责任人信息；5、本单位通行证管理制度；6、其他相关材料。
          </p>
          <UploadImg
            img-type="more"
            :img-num="8"
            :image-list="form.attachmentList"
            type="attachmentList"
            @getImg="getImg"
            @delImg="delImg"
          />
        </TagCard>
      </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 {
  adminDelete,
  adminEdit,
  getPageList,
  excelInput,
  getUnitList
} from '@/api/user_manage'
import { readExcel } from '@/utils/getExcelList'
import TagCard from '@/components/TagCard'

export default {
  components: { Pagination, UploadImg, TagCard },
  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 {
      enumLoading: false, // 是否加载中
      // 主表格&主表格加载状态
      list: [],
      listLoading: true,
      loading: false,
      // 分页参数
      page: {
        data: {
          unitType: null,
          unitAllName: null,
          unitConciseName: null,
          manageName: null,
          managePhone: null
        },
        pageNum: 1,
        pageSize: 10
      },
      total: 0,
      // 是否显示对话框
      dialogVisible: false,
      // 对话框标题
      dialogTitle: {
        add: '添加账号',
        update: '编辑账号'
      },
      dialogType: 'add',
      form_copy: null,
      // 添加角色参数
      form: {
        unitType: null,
        username: null,
        password: null,
        manageName: null,
        managePhone: null,
        unitAllName: null,
        unitConciseName: null,
        unitCode: null,
        isCharge: true,
        unitBusinessImg: null,
        unitAllowInFile: null,
        unitScale: null,
        attachmentList: []
      },
      // 验证规则
      rules: {
        // unitAllowInFile: [
        //   { required: true, message: '请选择单位准入函件', trigger: 'change' }
        // ],
        unitType: [{ required: true, message: '请选择单位类型', trigger: 'change' }],
        // unitScale: [{ required: true, message: '请选择单位规模', trigger: 'change' }],
        isCharge: [{ required: true, message: '请选择收费标准', trigger: 'change' }],
        managePhone: [{ required: true, message: '请输入管理员手机号', trigger: 'change' }],
        username: [{ required: true, message: '请输入账号名称', trigger: 'change' }],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            pattern:
              /^(((?=.*\d)(?=.*[a-z])(?=.*[A-Z]))|((?=.*\d)(?=.*[a-z])(?=.*[~!@#$%^&*]))|((?=.*\d)(?=.*[A-Z])(?=.*[~!@#$%^&*]))|((?=.*[a-z])(?=.*[A-Z])(?=.*[~!@#$%^&*]))|((?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[~!@#$%^&*]))).{10,32}$/,
            message:
              '必须大小写字母、数字、特殊字符,4种组合中至少满足3种，且密码长度在10-32位之间'
          }
        ],
        manageName: [{ required: true, message: '请输入管理员姓名', trigger: 'change' }],
        unitAllName: [{ required: true, message: '请输入单位全称', trigger: 'change' }],
        unitConciseName: [
          { required: true, message: '请输入单位简称', trigger: 'change' }
        ]
      },
      unitTypeList: [
        // { id: 1, name: '本级单位' },
        // { id: 2, name: '驻场单位' }
      ],
      account_list: [],
      unitScale_list: [
        { id: 1, name: '0-99人' },
        { id: 2, name: '100-499人' },
        { id: 3, name: '500以上' }
      ],
      hasDealNumber: 0,
      waitDealNumber: 0,
      allNumber: 0,
      hasCompleted: false,
      drawerVisible: false,
      batchUploadResultList: []
    }
  },
  computed: {
    // 批量注册人员-返回向下取整，减少渲染次数
    makePercent() {
      return Math.floor((this.hasDealNumber / this.allNumber) * 100)
    }
  },
  watch: {},
  created() {
    this.selectInit()
    this.fetchData()
    this.form_copy = JSON.parse(JSON.stringify(this.form))
  },
  methods: {
    async selectInit() {
      this.enumLoading = true
      const unitAxios = await getUnitList()
      await Promise.all([
        unitAxios
      ]).then(res => {
        const unitAxiosRes = res[0]
        this.unitTypeList = unitAxiosRes.data
      }).finally(() => {
        this.enumLoading = false
      })
    },
    fetchData() {
      this.listLoading = true
      getPageList(this.page).then((res) => {
        this.list = res.data.records
        this.total = res.data.total
        this.listLoading = false
      })
    },
    // 打开添加角色对话框
    create(type, row) {
      if (type === 'add') {
        this.form = JSON.parse(JSON.stringify(this.form_copy))
      } else {
        this.form = Object.assign(this.form, row)
        this.form.password = ''
      }
      this.dialogType = type
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs['form'].clearValidate()
      })
    },
    // 确定添加/编辑
    addOrUpdate() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          adminEdit(this.form).then((res) => {
            this.dialogVisible = false
            this.fetchData()
            this.$message({
              type: 'success',
              message: '操作成功!'
            })
          })
        }
      })
    },
    // 删除角色
    deleteFun(id) {
      this.$confirm('确定要删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(() => {
        adminDelete(id).then((res) => {
          this.fetchData()
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        })
      })
    },
    // 图片赋值
    getImg(val, index, type) {
      if (type == 'attachmentList') {
        this.form.attachmentList.push(val)
      } else {
        this.form[type] = val
      }
    },
    delImg(index, type) {
      this.form[type].splice(index, 1)
    },
    // 返回列表序号
    indexMethod(index) {
      return (this.page.pageNum - 1) * this.page.pageSize + index + 1
    },
    // 下载模板
    download() {
      window.location.href =
        process.env.VUE_APP_BASE_API + '/excel/adminexcel.xlsx'
    },
    // 批量导入
    async upload(e) {
      this.loading = 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.loading = 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.username = data[i]['用户名（单位）']
      form.password = data[i]['密码']
      form.deptName = data[i]['部门名称']
      form.parentDeptNameList = data[i]['上级部门']
      form.postName = data[i]['岗位名称']
      form.passAreaNameList = data[i]['通行区域列表']
      if (data[i]['上级部门']) {
        form.parentDeptNameList = data[i]['上级部门'].toString().split('-')
      }
      if (data[i]['通行区域列表']) {
        form.passAreaNameList = data[i]['通行区域列表'].toString().split(',')
      }
      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.username) {
        isPass.incorrect.err = '用户名（单位）为必填项'
        isPass.isOk = false
        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)
    }
  }
}
</script>
<style scoped lang="scss">
.red {
  color: #e14545;
}
.table-img{
  width: 60px;
  height: 60px;
  margin-right: 5px;
  margin-bottom: 5px;
}
</style>
<style  lang="scss">
.unitType-select {
  width: 320px;
  .el-select-dropdown__item {
    height: auto;
    line-height: 1;
    .desc, .detail {
      line-height: 30px;
      white-space: normal;
      width: 100%;
    }
    .desc {
      font-size: 14px;
      padding-top: 5px;
      color: #333333;
    }
    .detail {
      padding-bottom: 5px;
      line-height: 20px;
      font-size: 12px;
      text-align: left;
      color: #909399;
    }
  }
}
</style>
