<template>
  <div class="app-container">
    <span v-if="checkRole([5, 99])">
      <el-button type="primary" icon="el-icon-plus" @click="create"
        >添加人员</el-button
      >
      <el-button
        type="primary"
        icon="el-icon-download"
        @click="batchDownloadMachineList"
        class="margin-left"
        >下载模板</el-button
      >
      <a href="javascript:;" class="file"
        >批量导入<input
          type="file"
          name="file"
          ref="file"
          @change="upload($event)"
      /></a>
      <el-button
        type="primary"
        class="margin-left"
        @click="download"
        v-if="isOut === 1"
        >导出记录</el-button
      >
      <el-button type="danger" class="margin-left" @click="allDel"
        >一键删除</el-button
      >
    </span>
    <!--操作区-->
    <el-input
      v-model="page.data.name"
      placeholder="请输入姓名"
      class="margin-left input"
    ></el-input>
    <el-input
      v-model="page.data.phone"
      placeholder="请输入手机号"
      class="margin-left input"
    ></el-input>
    <el-input
      v-model="page.data.idNumber"
      placeholder="请输入身份证号"
      class="margin-left input"
    ></el-input>
    <el-input
      v-model="page.data.examSession"
      placeholder="请输入场次"
      class="margin-left input"
    ></el-input>
    <el-input
      v-model="page.data.examCode"
      placeholder="请输入准考证号"
      class="margin-left input"
    ></el-input>
    <el-input
      v-model="page.data.examType"
      placeholder="请输入报考类别"
      class="margin-left input"
    ></el-input>
    <el-select
      v-if="checkRole([1, 2, 3, 4])"
      v-model="page.data.username"
      clearable
      filterable
      placeholder="请选择所属账号"
      class="margin-left input"
    >
      <el-option
        v-for="item in user_list"
        :key="item.id"
        :label="item.username"
        :value="item.username"
      >
      </el-option>
    </el-select>
    <!-- <el-select
      filterable
      clearable
      v-model="page.data.status"
      placeholder="请选择是否认证"
      class="margin-left input"
    >
      <el-option
        v-for="item in status_list"
        :key="item.id"
        :label="item.name"
        :value="item.id"
      >
      </el-option>
    </el-select> -->
    <el-select
      v-model="page.data.status"
      clearable
      filterable
      placeholder="是否入场"
      class="margin-left input"
    >
      <el-option
        v-for="item in enter_list"
        :key="item.id"
        :label="item.name"
        :value="item.id"
      >
      </el-option>
    </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>
    <el-date-picker
      v-model="page.data.endTime"
      type="datetime"
      placeholder="选择考试结束时间"
      value-format="yyyy-MM-dd HH:mm:ss"
      class="margin-left"
    >
    </el-date-picker>
    <el-button
      type="primary"
      icon="el-icon-search"
      @click="fetchData"
      class="margin-left"
      >搜索</el-button
    >
    <!--主表格-->
    <el-table
      class="table"
      ref="table_form"
      v-loading="listLoading"
      :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">
          <el-image
            style="width: 70px; height: 70px"
            :src="scope.row.photo"
            :preview-src-list="[scope.row.photo]"
          >
            <div slot="error" class="image-slot">
              {{ scope.row.photo ? "加载失败" : "暂无照片" }}
            </div>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column label="姓名" align="center">
        <template slot-scope="scope">
          {{ scope.row.name | matchNull }}
        </template>
      </el-table-column>
      <el-table-column label="身份证号" align="center">
        <template slot-scope="scope">
          {{ scope.row.idNumber | matchNull }}
        </template>
      </el-table-column>
      <el-table-column label="手机号" align="center">
        <template slot-scope="scope">
          {{ scope.row.phone | matchNull }}
        </template>
      </el-table-column>
      <el-table-column
        label="所属账号"
        align="center"
        v-if="checkRole([1, 2, 3, 4])"
      >
        <template slot-scope="scope">
          {{ scope.row.username | matchNull }}
        </template>
      </el-table-column>
      <el-table-column label="场次" align="center">
        <template slot-scope="scope">
          {{ scope.row.examSession | matchNull }}
        </template>
      </el-table-column>
      <el-table-column label="准考证号" align="center">
        <template slot-scope="scope">
          {{ scope.row.examCode | matchNull }}
        </template>
      </el-table-column>
      <el-table-column label="报考类别" align="center">
        <template slot-scope="scope">
          {{ scope.row.examType | matchNull }}
        </template>
      </el-table-column>
      <el-table-column label="开始时间" align="center">
        <template slot-scope="scope">
          {{ scope.row.startTime | matchNull }}
        </template>
      </el-table-column>
      <el-table-column label="结束时间" align="center">
        <template slot-scope="scope">
          {{ scope.row.endTime | matchNull }}
        </template>
      </el-table-column>
      <el-table-column label="是否入场" align="center">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status == 0" type="info">未入场</el-tag>
          <el-tag v-if="scope.row.status == 1">已入场</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="入场时间" align="center">
        <template slot-scope="scope">
          {{ scope.row.inTime | matchNull }}
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center">
        <template slot-scope="scope">
          {{ scope.row.remark }}
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        prop=""
        label="操作区"
        width="100"
        v-if="checkRole([1, 2, 5, 99])"
      >
        <template slot-scope="scope">
          <el-button
            type="danger"
            size="small"
            v-if="checkRole([1, 2, 5, 99])"
            @click="deleteUser(scope.row.examUserWhitelistId)"
            >删除</el-button
          >
          <!-- <el-button type="primary" size="small" @click="create(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="dialogTit"
      :visible.sync="dialogVisible"
      width="800px"
      :close-on-click-modal="false"
    >
      <el-form
        :model="form"
        :rules="rules"
        ref="form"
        label-width="90px"
        label-position="left"
      >
        <div class="flex">
          <el-form-item
            label="姓名"
            prop="name"
            class="form-item-style item-margin-bottom"
          >
            <el-input v-model="form.name" placeholder="请输入姓名"></el-input>
          </el-form-item>
          <el-form-item
            label="身份证号"
            prop="idNumber"
            class="form-item-style"
          >
            <el-input
              v-model="form.idNumber"
              placeholder="请输入身份证号"
            ></el-input>
          </el-form-item>
        </div>
        <div class="flex">
          <el-form-item label="手机号" class="form-item-style" prop="phone">
            <el-input
              placeholder="请输入手机号"
              maxlength="11"
              show-word-limit
              v-model.trim="form.phone"
            />
          </el-form-item>
          <el-form-item
            label="场次"
            prop="examSession"
            class="form-item-style special"
          >
            <el-input
              v-model="form.examSession"
              placeholder="请输入场次"
            ></el-input>
          </el-form-item>
        </div>
        <div class="flex">
          <el-form-item
            label="准考证号"
            prop="examCode"
            class="form-item-style"
          >
            <el-input
              v-model="form.examCode"
              placeholder="请输入准考证号"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="报考类别"
            prop="examType"
            class="form-item-style special"
          >
            <el-input
              v-model="form.examType"
              placeholder="请输入报考类别"
            ></el-input>
          </el-form-item>
        </div>
        <el-form-item label="备注" prop="remark" class="form-item-style">
          <el-input v-model="form.remark" placeholder="请输入备注"></el-input>
        </el-form-item>
        <div class="flex">
          <el-form-item
            label="开始时间"
            prop="startTime"
            class="form-item-style"
          >
            <el-date-picker
              style="width: 100%"
              v-model="form.startTime"
              type="datetime"
              placeholder="选择开始时间"
              value-format="yyyy-MM-dd HH:mm:ss"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item
            label="结束时间"
            prop="endTime"
            class="form-item-style special"
          >
            <el-date-picker
              style="width: 100%"
              v-model="form.endTime"
              type="datetime"
              placeholder="选择结束时间"
              value-format="yyyy-MM-dd HH:mm:ss"
            >
            </el-date-picker>
          </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-dialog
      title="提示"
      center
      :visible.sync="resultVisible"
      destroy-on-close
    >
      <el-table
        class="table"
        ref="table_form_result"
        v-loading="false"
        :data="result_list"
        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 | matchNull }}
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="resultVisible = false">
          我已知晓
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  examUserWhitelist,
  examUserWhitelistDel,
  examUserWhitelistInsert,
  uploadExcel,
  excelOut,
  examUserWhitelistDeleteAll,
} from "@/api/exam";
import { checkRole } from "@/utils/checkRole";
import Pagination from "@/components/Pagination";
import { getUserListSearch } from "@/api/user_manage";

export default {
  components: { Pagination },
  filters: {
    matchNull(str) {
      if (!str) {
        return "暂无";
      } else {
        return str;
      }
    },
  },
  data() {
    return {
      isOut: this.$store.getters.isOut, // 是否可以导出
      // 主表格&主表格加载状态
      list: null,
      listLoading: true,
      // 分页参数
      page: {
        data: {
          name: "",
          phone: "",
          idNumber: "",
          examSession: "",
          examCode: "",
          examType: "",
          startTime: "",
          endTime: "",
          status: null,
          username: null,
          status: null,
        },
        pageNum: 1,
        pageSize: 10,
      },
      total: 0,
      form: {
        idNumber: null,
        name: "",
        phone: "",
        examSession: null,
        examCode: null,
        examType: null,
        remark: null,
        startTime: null,
        endTime: null,
      },
      // 验证规则
      rules: {
        idNumber: [
          { required: true, message: "请输入身份证号", trigger: "blur" },
        ],
        startTime: [{ required: true, message: "请选择", trigger: "blur" }],
        endTime: [{ required: true, message: "请选择", trigger: "blur" }],
      },
      dialogVisible: false,
      form_copy: {},
      dialogTit: "添加人员",
      enter_list: [
        { id: 1, name: "已入场" },
        { id: 0, name: "未入场" },
      ], //是否入场
      // 账号列表_搜索
      user_list: [],
      // 是否认证_搜索
      status_list: [
        { id: 1, name: "已认证" },
        { id: 2, name: "未认证" },
      ],
      // 批量导入结果返回
      resultVisible: false,
      result_list: [],
    };
  },
  created() {
    this.fetchData();
    this.getUserListSearch();
  },
  methods: {
    // 查询权限
    checkRole,
    // 获取列表数据
    fetchData() {
      this.listLoading = true;
      examUserWhitelist(this.page).then((res) => {
        this.list = res.data.list;
        this.total = res.data.total;
        this.listLoading = false;
      });
    },
    // 打开添加对话框
    create(row) {
      if (row) {
        this.form = JSON.parse(JSON.stringify(row));
      } else {
        this.form = JSON.parse(JSON.stringify(this.form_copy));
      }
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs["form"].clearValidate();
      });
    },
    // 确定添加
    addOrupdate() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          examUserWhitelistInsert(this.form).then((res) => {
            this.dialogVisible = false;
            this.fetchData();
            this.$message({
              type: "success",
              message: "添加成功!",
            });
          });
        }
      });
    },
    // 删除
    deleteUser(id) {
      this.$confirm("确定要删除此人员吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        center: true,
      }).then(() => {
        examUserWhitelistDel(id).then((res) => {
          this.fetchData();
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        });
      });
    },
    // 批量导入
    upload(e) {
      var files = e.currentTarget.files;
      if (!files.length) {
        return;
      }
      const loading = this.$loading({
        lock: true,
        text: "拼命导入中...",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      var formData = new FormData(); // 必需声明一个FormData对象
      formData.append("file", files[0]);
      uploadExcel(formData)
        .then((res) => {
          loading.close();
          this.fetchData();
          if (res.data.length > 0) {
            this.resultVisible = true;
            this.result_list = res.data;
          } else {
            this.$message({
              type: "success",
              message: "导入成功!",
            });
          }
        })
        .catch((err) => {
          loading.close();
          this.fetchData();
        });
    },
    // 导出记录
    download() {
      this.$prompt("请输入导出密码", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        closeOnClickModal: false,
      })
        .then(async ({ value }) => {
          if (value == "Nqj##361") {
            this.$message({
              type: "success",
              message: "密码正确,正在下载...",
            });
            this.listLoading = true;
            await excelOut(this.page).then((res) => {
              var eleLink = document.createElement("a");
              eleLink.style.display = "none";
              // 字符内容转变成blob地址
              var blob = new Blob([res]);
              eleLink.href = URL.createObjectURL(blob);
              eleLink.setAttribute("download", "考试列表.xlsx");
              // 自动触发点击
              document.body.appendChild(eleLink);
              eleLink.click();
              // 然后移除
              document.body.removeChild(eleLink);
              this.listLoading = false;
            });
          } else {
            this.$message({
              type: "error",
              message: "您输入的密码不正确",
            });
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "取消导出",
          });
        });
    },
    // 一键删除
    allDel() {
      this.$prompt("请输入删除密码", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        closeOnClickModal: false,
      })
        .then(async ({ value }) => {
          if (value == "Nqj##361") {
            this.$message({
              type: "success",
              message: "密码正确,正在删除...",
            });
            this.listLoading = true;
            await examUserWhitelistDeleteAll().then((res) => {
              this.listLoading = false;
              this.fetchData();
            });
          } else {
            this.$message({
              type: "error",
              message: "您输入的密码不正确",
            });
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "取消删除",
          });
        });
    },
    //下载模板
    batchDownloadMachineList() {
      window.location.href =
        process.env.VUE_APP_BASE_API + "/excel/examUserWhitelistExcel.xlsx";
    },
    // 获取账号列表数据_搜索
    getUserListSearch() {
      getUserListSearch().then((res) => {
        this.user_list = res.data;
      });
    },
    // 返回列表序号
    indexMethod(index) {
      return (this.page.pageNum - 1) * this.page.pageSize + index + 1;
    },
  },
  computed: {
    //批量注册人员-返回向下取整，减少渲染次数
    makePercent() {
      return Math.floor((this.hasDealNumber / this.allNumber) * 100);
    },
  },
};
</script>

<style scoped>
.table {
  margin-top: 15px;
}
.flex {
  display: flex;
  justify-content: flex-start;
  align-items: center;
}
.margin-left {
  margin: 10px 0 0 10px;
}
.margin-left-s {
  margin-left: 15px;
}
.input {
  width: 200px;
}
/*批量导入按钮*/
.file {
  margin: 10px 0 0 10px;
  position: relative;
  background: #d0eeff;
  border: 1px solid #99d3f5;
  border-radius: 4px;
  padding: 10px 20px;
  box-sizing: border-box;
  overflow: hidden;
  color: #1e88c7;
  text-decoration: none;
  text-indent: 0;
}
.file input {
  position: absolute;
  font-size: 14px;
  width: 106px;
  height: 40px;
  left: 0;
  top: 0;
  opacity: 0;
  cursor: pointer;
}
.file:hover {
  background: #aadffd;
  border-color: #78c3f3;
  color: #004974;
  text-decoration: none;
}
</style>

<style lang="scss">
//修改element原生样式
.special {
  .el-form-item__label {
    padding-left: 10px;
  }
}
.el-dialog__body {
  padding: 0 20px 10px;
}
</style>
