<template>
  <div class="app-container">
    <!--搜索区-->
    <div class="float-item">
      <el-select
        v-model="page.data.passApplyType"
        filterable
        clearable
        placeholder="通行证类型"
        class="margin-left input"
      >
        <el-option
          v-for="item in type_list"
          :key="item.id"
          :label="item.name"
          :value="item.id"
        />
      </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-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-input
        v-model="page.data.ttttt"
        placeholder="请输入证件编号"
        clearable
        class="margin-left input"
      ></el-input>
      <el-select
        filterable
        clearable
        v-model="page.data.uuuuu"
        placeholder="请选择审核状态"
        class="margin-left input"
      >
        <el-option
          v-for="item in audit_list"
          :key="item.code"
          :label="item.desc"
          :value="item.code"
        >
        </el-option>
      </el-select>-->
      <el-button
        type="primary"
        icon="el-icon-search"
        class="margin-left"
        @click="fetchData"
      >搜索</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>
    <div class="doc-content">
      <div v-for="(item, index) in list" :key="index" class="doc-content-item">
        <div style="flex: 1">
          <!--临时通行证-->
          <shortIerm v-if="item.passApplyType == 2" :item-data="item" />
          <!--长期通行证-->
          <longIerm v-if="item.passApplyType == 1" :item-data="item" />
          <!--        <buildPage v-if="item.passApplyType == 3" :areaList="areaList" />-->
        </div>
        <div
          class="card-right"
          @mouseenter="handleEnter($event, index)"
          @mouseleave="handleLeave($event, index)"
        >
          <div>分值：{{ item.documentScore }}分</div>
          <div>手机号：{{ item.phone }}</div>
          <div v-if="item.stopDocumentTime" class="yellow">
            停证至：{{ item.stopDocumentTime }}
          </div>
          <div class="icon-content">
            <img
              :src="
                item.documentStatus == 1
                  ? papers1
                  : item.documentStatus == 2
                    ? papers2
                    : item.documentStatus == 3
                      ? papers3
                      : papers4
              "
              alt=""
            >
            <img
              :src="
                item.useStatus == 1
                  ? Use1
                  : item.useStatus == 2
                    ? Use3
                    : item.useStatus == 3
                      ? Use2
                      : Use4
              "
              alt=""
            >
            <img :src="item.iseffective == 1 ? validity1 : validity2" alt="">
          </div>
          <div v-if="isShowList[index] == 1" class="card-btn">
            <div>
              <el-button
                v-if="item.documentStatus == 2"
                type="primary"
                size="mini"
                @click="handleFun(item.passId, '重置打印')"
              >重置打印</el-button>
            </div>
            <div>
              <el-button
                type="primary"
                size="mini"
                @click="passPunishRecord(item.passId)"
              >处罚记录</el-button>
            </div>
            <div>
              <el-button
                v-if="item.useStatus == 3 && item.documentStatus != 3"
                type="primary"
                size="mini"
                @click="handleFun(item.passId, '解封')"
              >解封</el-button>
            </div>
            <div>
              <el-button
                type="danger"
                size="mini"
                @click="handleFun(item.passId, '删除')"
              >删除</el-button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!--分页栏-->
    <pagination
      :total="total"
      :page.sync="page.pageNum"
      :limit.sync="page.pageSize"
      @pagination="fetchData"
    />
    <!--对话框-->
    <el-dialog title="处罚记录" :visible.sync="dialogVisible" width="900px">
      <el-table
        ref="table_form"
        v-loading="listLoading"
        class="table"
        :data="recordList"
        element-loading-text="Loading"
        border
        fit
        highlight-current-row
      >
        <el-table-column
          type="index"
          align="center"
          width="80px"
          label="序号"
        />
        <!-- <el-table-column label="证件编号" align="center">
          <template slot-scope="scope">
            {{ scope.row.passSn }}
          </template>
        </el-table-column>
         <el-table-column label="处罚人员照片" align="center">
          <template slot-scope="scope">
            <el-image
              v-if="scope.row.punishAvatar"
              class="table-img"
              :src="scope.row.punishAvatar"
              :preview-src-list="[scope.row.punishAvatar]"
            >
            </el-image>
            <span v-else>暂无</span>
          </template>
        </el-table-column>
        <el-table-column label="处罚人员姓名" align="center">
          <template slot-scope="scope">
            {{ scope.row.punishName }}
          </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.punishScore }}
          </template>
        </el-table-column>
        <el-table-column label="处罚类型" align="center">
          <template slot-scope="scope">
            <el-tag
              v-if="scope.row.punishType === 1"
              type="success"
            >不处罚</el-tag>
            <el-tag
              v-if="scope.row.punishType === 2"
              type="warning"
            >停证</el-tag>
            <el-tag
              v-if="scope.row.punishType === 3"
              type="danger"
            >吊销</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="处罚内容" align="center">
          <template slot-scope="scope">
            {{ scope.row.punishDetail }}
          </template>
        </el-table-column>
        <el-table-column label="停证天数" align="center">
          <template slot-scope="scope">
            {{ scope.row.stopDocumentDays }}
          </template>
        </el-table-column>
        <el-table-column label="处罚时间" align="center">
          <template slot-scope="scope">
            {{ scope.row.createTime }}
          </template>
        </el-table-column>
      </el-table>
      <!--分页栏-->
      <!-- <pagination
        :total="total1"
        :page.sync="page1.pageNum"
        :limit.sync="page1.pageSize"
        @pagination="passPunishRecord"
      /> -->
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogVisible = false">
          确定
        </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 shortIerm from './pass/shortIerm.vue'
import longIerm from './pass/longIerm.vue'
import buildPage from './pass/build.vue'
import {
  passGetPageList,
  passDelete,
  passUnseal,
  passResetPrinting,
  passPunishRecord,
  passPunishTypeList,
  passInsert
} from '@/api/pass'
import { readExcel } from '@/utils/getExcelList1'
export default {
  components: { Pagination, shortIerm, longIerm, buildPage },
  filters: {},
  data() {
    return {
      // 主表格&主表格加载状态
      list: [],
      listLoading: true,
      loading: false,
      // 分页参数
      page: {
        data: {
          passApplyType: null,
          name: null,
          phone: null,
          startTime: null,
          endTime: null
        },
        pageNum: 1,
        pageSize: 10
      },
      total: 0,
      // page1: {
      //   data: {},
      //   pageNum: 1,
      //   pageSize: 10,
      // },
      // total1: 0,
      dialogVisible: false,
      type_list: [
        { id: 1, name: '人员长期通行证' },
        { id: 2, name: '人员短期通行证' }
      ],
      isShowList: [],
      areaList: [
        { choose: false, name: 'A1' },
        { choose: false, name: 'A2' },
        { choose: false, name: 'A3' },
        { choose: false, name: 'B1' },
        { choose: false, name: 'B2' },
        { choose: false, name: 'B3' },
        { choose: false, name: 'C1' },
        { choose: false, name: 'C2' },
        { choose: false, name: 'D1' },
        { choose: false, name: 'D2' },
        { choose: false, name: 'E1' },
        { choose: false, name: 'E2' },
        { choose: false, name: 'F1' },
        { choose: false, name: 'F2' },
        { choose: false, name: 'F3' }
      ],
      recordList: [], // 违规记录
      getOutLineList: [], // 违规列表
      papers1: require('../../assets/status_log/papers1.png'),
      papers2: require('../../assets/status_log/papers2.png'),
      papers3: require('../../assets/status_log/papers3.png'),
      papers4: require('../../assets/status_log/papers4.png'),
      Use1: require('../../assets/status_log/Use1.png'),
      Use2: require('../../assets/status_log/Use2.png'),
      Use3: require('../../assets/status_log/Use3.png'),
      Use4: require('../../assets/status_log/Use4.png'),
      validity1: require('../../assets/status_log/validity1.png'),
      validity2: require('../../assets/status_log/validity2.png'),
      //
      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()
    this.passPunishTypeList()
    this.areaList_copy = JSON.parse(JSON.stringify(this.areaList))
  },
  methods: {
    // 获取列表数据
    fetchData() {
      this.listLoading = true
      passGetPageList(this.page).then((res) => {
        res.data.records.forEach((item, index) => {
          const expireDate = new Date(item.endTime).getTime()
          const nowDate = new Date().getTime()
          if (nowDate * 30 * 24 * 60 * 60 * 1000 >= expireDate) {
            item.isRecertification = true
          } else {
            item.isRecertification = false
          }
          if (expireDate > nowDate) {
            item.iseffective = 1
          } else {
            item.iseffective = 2
          }
          item.areaList = JSON.parse(JSON.stringify(this.areaList_copy))
          // if (index == 0) {
          item.areaNameList.forEach((i1) => {
            item.areaList.forEach((i2) => {
              if (i1 == i2.name) {
                i2.choose = true
              }
            })
          })
          // }
        })
        this.list = res.data.records
        this.total = res.data.total
        this.listLoading = false
      })
    },
    // 鼠标移入
    handleEnter(e, index) {
      this.$set(this.isShowList, index, 1)
    },
    // 鼠标移出
    handleLeave(e, index) {
      this.$set(this.isShowList, index, 0)
    },
    // 违规列表
    passPunishTypeList() {
      passPunishTypeList().then((res) => {
        this.getOutLineList = res.data
      })
    },
    // 获取用户的违规记录
    passPunishRecord(id) {
      passPunishRecord(id).then((res) => {
        res.data.forEach((item) => {
          const index = this.getOutLineList.findIndex((i) => {
            return i.code == item.type
          })
          if (index > -1) {
            item.typeName = this.getOutLineList[index].desc
          }
        })
        this.recordList = res.data
        this.dialogVisible = true
      })
    },
    // 操作
    handleFun(id, type) {
      this.$confirm('确定要' + type + '吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(async() => {
        let res
        switch (type) {
          case '删除':
            res = await passDelete(id)
            break
          case '解封':
            res = await passUnseal(id)
            break
          case '重置打印':
            res = await passResetPrinting(id)
            break
          default:
            break
        }
        if (res.code == 200) {
          this.fetchData()
          this.$message({
            type: 'success',
            message: '操作成功!'
          })
        }
      })
    },
    download() {
      const baseURLStr = window.g.ApiUrl
      window.location.href = baseURLStr + '/excel/pass.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)
      this.$refs.file.value = ''
    },
    // 递归调用校验数据并请求
    async doUploadAddUserInfo(i, data) {
      if (i > data.length - 1) {
        this.hasCompleted = true
        this.fetchData()
        this.$message.success('导入已完成！')
        return
      }
      const form = {}
      form.passApplyType = data[i]['通行证类型']
      // form.extraAttribute = data[i]['附加资格']
      form.startTime = data[i]['开始时间']
      form.endTime = data[i]['结束时间']
      form.areaList = data[i]['通行区域']
      // form.drivingModel = data[i]['准驾车型']
      // form.drivingType = data[i]['准驾类别']
      form.idNumber = data[i]['身份证号']
      form.areaList = form.areaList?.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 passInsert(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)
    },

    // 返回列表序号
    indexMethod1(index) {
      return (this.page1.pageNum - 1) * this.page1.pageSize + index + 1
    }
  }
}
</script>
<style scoped lang="scss">
.float-item {
  //margin-bottom: 10px;
}
.doc-content {
  display: flex;
  flex-wrap: wrap;
  &-item {
    //width: calc((100% - 40px) / 3);
    width: 400px;
    height: 390px;
    background-color: #f5f6f8;
    display: flex;
    justify-content: left;
    border-radius: 0px 8px 8px 0px;
    margin: 10px;
    //&:nth-child(4n) {
    //  margin-right: 0;
    //}
    //&:nth-child(4n - 3) {
    //  margin-left: 0;
    //}
    .card-right {
      width: 140px;
      font-size: 14px;
      padding: 12px 7px;
      line-height: 21px;
      box-sizing: border-box;
      position: relative;
      border-left: 1px dashed #939A7791;
      .icon-content {
        height: 260px;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        &:first-child{
          margin-top: 18px;
        }
      }
      img {
        width: 71.42px;
        height: 66px;
        margin: 10px 0;
      }
      .card-btn {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: rgba(0, 0, 0, 0.7);
        border-radius: 0px 8px 8px 0px;
        padding-top: 88px;
        div {
          width: 100%;
          text-align: center;
          margin-bottom: 28px;
        }
      }
    }
  }
}
.yellow {
  color: #ffb74a;
}
</style>
