<template>
  <div class="app-container">
    <span v-if="checkRole([5, 99])">
      <el-button
        type="primary"
        icon="el-icon-plus"
        @click="create"
        class="margin-left"
        >添加黑名单</el-button
      >
      <el-button
        type="primary"
        icon="el-icon-download"
        @click="batchDownloadMachineList"
        class="margin-left"
        >下载模板</el-button
      >
      <BatchUpload
        fileType="excel"
        @getFileList="getFileList"
        :needFileNameList="['name', 'idNumber', 'cardIdEx']"
      ></BatchUpload>
    </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-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.provinceId"
      @change="chooseProvinceSearch"
      placeholder="请选择省份"
      class="margin-left input"
      :disabled="checkRole([2, 3, 4, 5, 99])"
    >
      <el-option
        v-for="item in province_list_search"
        :key="item.areaCodeId"
        :label="item.name"
        :value="item.areaCodeId"
      >
      </el-option>
    </el-select>
    <el-select
      filterable
      clearable
      v-model="page.data.cityId"
      @change="chooseCitySearch"
      placeholder="请选择城市"
      class="margin-left input"
      :disabled="checkRole([4, 5, 99])"
    >
      <el-option
        v-for="item in city_list_search"
        :key="item.areaCodeId"
        :label="item.name"
        :value="item.areaCodeId"
      >
      </el-option>
    </el-select>
    <el-select
      filterable
      clearable
      v-model="page.data.areaId"
      placeholder="请选择区域"
      class="margin-left input"
      :disabled="checkRole([5, 99])"
    >
      <el-option
        v-for="item in area_list_search"
        :key="item.areaCodeId"
        :label="item.name"
        :value="item.areaCodeId"
      >
      </el-option>
    </el-select>
    <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.avatar"
            :preview-src-list="[scope.row.avatar]">
            <div slot="error" class="image-slot">
              暂无照片
            </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.phone | 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" v-if="checkRole([1, 2])">
        <template slot-scope="scope">
          {{ scope.row.provinceName | matchNull }}
        </template>
      </el-table-column>
      <el-table-column label="市" align="center" v-if="checkRole([1, 2, 3])">
        <template slot-scope="scope">
          {{ scope.row.cityName | matchNull }}
        </template>
      </el-table-column>
      <el-table-column label="区" align="center" v-if="checkRole([1, 2, 3, 4])">
        <template slot-scope="scope">
          {{ scope.row.areaName | matchNull }}
        </template>
      </el-table-column>
      <el-table-column
        label="街道"
        align="center"
        v-if="checkRole([1, 2, 3, 4])"
      >
        <template slot-scope="scope">
          {{ scope.row.streetName | matchNull }}
        </template>
      </el-table-column>
      <el-table-column
        label="详细地址"
        align="center"
        v-if="checkRole([1, 2, 3, 4])"
      >
        <template slot-scope="scope">
          {{ scope.row.address | matchNull }}
        </template>
      </el-table-column>
      <el-table-column
        label="所属组织名称"
        align="center"
        v-if="checkRole([1, 2, 3, 4])"
      >
        <template slot-scope="scope">
          {{ scope.row.policeStationName | matchNull }}
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center">
        <template slot-scope="scope">
          {{ scope.row.createTime | 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
        align="center"
        prop=""
        label="操作区"
        width="100"
        v-if="checkRole([1, 2, 5, 99])"
      >
        <template slot-scope="scope">
          <el-button
            type="warning"
            plain
            size="small"
            @click="removeUser(scope.row.id)"
            >移除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!--分页栏-->
    <pagination
      :total="total"
      :page.sync="page.pageNum"
      :limit.sync="page.pageSize"
      @pagination="fetchData"
    />
    <el-dialog title="添加黑名单" :visible.sync="dialogVisible" width="800px">
      <el-form
        :model="form"
        :rules="rules"
        ref="form"
        label-width="120px"
        label-position="left"
      >
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name" placeholder="请输入姓名"></el-input>
        </el-form-item>
        <el-form-item label="身份证号" prop="idNumber">
          <el-input
            v-model="form.idNumber"
            placeholder="请输入身份证号"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false"> 取消 </el-button>
        <el-button type="primary" @click="add"> 确定 </el-button>
      </div>
    </el-dialog>
    <!-- 批量注册人员-抽屉 -->
    <el-drawer
      :title="hasCompleted ? '导入已完成' : '正在处理中..'"
      :visible.sync="drawerVisible"
      :wrapperClosable="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-progress>
        <el-table
          class="table"
          ref="batch_upload_result"
          v-loading="false"
          :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 | 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.err | matchNull }}
            </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 {
  getPageListBlack,
  removeBlack,
  iuserBlackListInsert,
} from "@/api/ordinary_user";
import { checkRole } from "@/utils/checkRole";
import Pagination from "@/components/Pagination";
import {
  getArea,
  getCity,
  getProvince,
  getUserListSearch,
} from "@/api/user_manage";
import BatchUpload from "@/components/BatchUpload";
import { batchDownload } from "@/utils/batchDownload";

export default {
  components: { Pagination, BatchUpload },
  filters: {
    matchNull(str) {
      if (!str) {
        return "暂无";
      } else {
        return str;
      }
    },
  },
  data() {
    return {
      // 主表格&主表格加载状态
      list: null,
      listLoading: true,
      // 分页参数
      page: {
        data: {
          username: null,
          name: "",
          phone: "",
          idNumber: "",
          provinceId: null,
          cityId: null,
          areaId: null,
        },
        pageNum: 1,
        pageSize: 10,
      },
      total: 0,
      // 账号列表_搜索
      user_list: [],
      //省市县列表_搜索
      province_list_search: [],
      city_list_search: [],
      area_list_search: [],
      // 是否认证_搜索
      status_list: [
        { id: 1, name: "已认证" },
        { id: 2, name: "未认证" },
      ],
      form: {
        idNumber: null,
        name: "",
      },
      // 验证规则
      rules: {
        idNumber: [
          { required: true, message: "请输入身份证号", trigger: "blur" },
        ],
      },
      dialogVisible: false,
      form_copy: {},
      //批量人员注册-处理提示值
      hasDealNumber: 0,
      waitDealNumber: 0,
      allNumber: 0,
      hasCompleted: false,
      //批量注册人员-抽屉控制值
      drawerVisible: false,
      batchUploadResultList: [],
    };
  },
  created() {
    this.fetchData();
    this.getUserListSearch();
    this.getAddressListSearch(1);
    if (checkRole([2, 3])) {
      this.getAddressListSearch(2, this.$store.getters.provinceId);
      this.page.data.provinceId = this.$store.getters.provinceId;
    } else if (checkRole([4])) {
      this.getAddressListSearch(2, this.$store.getters.provinceId);
      this.page.data.provinceId = this.$store.getters.provinceId;
      this.getAddressListSearch(3, this.$store.getters.cityId);
      this.page.data.cityId = this.$store.getters.cityId;
    } else if (checkRole([5, 99])) {
      this.getAddressListSearch(2, this.$store.getters.provinceId);
      this.page.data.provinceId = this.$store.getters.provinceId;
      this.getAddressListSearch(3, this.$store.getters.cityId);
      this.page.data.cityId = this.$store.getters.cityId;
      this.page.data.areaId = this.$store.getters.areaId;
    }
  },
  methods: {
    // 查询权限
    checkRole,
    // 获取列表数据
    fetchData() {
      this.listLoading = true;
      getPageListBlack(this.page).then((res) => {
        this.list = res.data.list;
        this.total = res.data.total;
        this.listLoading = false;
      });
    },
    // 打开添加对话框
    create() {
      this.form = JSON.parse(JSON.stringify(this.form_copy));
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs["form"].clearValidate();
      });
    },
    // 确定添加
    add() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          iuserBlackListInsert(this.form).then((res) => {
            this.dialogVisible = false;
            this.fetchData();
            this.$message({
              type: "success",
              message: "添加成功!",
            });
          });
        }
      });
    },
    // 批量注册人员-操作
    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);
    },
    //批量注册人员-并提交至添加黑名单接口
    async doSubmitUrl(correctList, index) {
      if (index <= correctList.correct.length - 1) {
        // 换url
        let item = correctList.correct[index];

        //组装数据上传至添加黑名单接口
        let data = JSON.parse(JSON.stringify(this.form_copy));
        data.name = item["姓名"];
        data.idNumber = item["身份证号"];
        await iuserBlackListInsert(data)
          .then((res) => {
            console.log(res);
          })
          .catch((err) => {
            console.log(err);
            this.batchUploadResultList.push({
              name: data.name,
              idNumber: data.idNumber,
              err: err,
            });
          });
        this.hasDealNumber += 1;
        this.waitDealNumber -= 1;
        this.makeScrollDown();
        //继续调用
        this.doSubmitUrl(correctList, ++index);
      } else {
        this.hasCompleted = true;
        this.fetchData();
      }
    },
    // 批量注册人员-保持滚动条在最底部
    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() {
      let 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";
      }
      let blob = new Blob([string], { type: "text/plain;charset=utf-8" });
      let excel_url = window.URL.createObjectURL(blob);
      let link = document.createElement("a");
      link.href = excel_url;
      link.download = "批量注册结果错误名单.xls";
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    },
    //下载模板
    batchDownloadMachineList() {
      window.location.href =
        process.env.VUE_APP_BASE_API + "/excel/userBlackListExcel.xlsx";
    },
    // 获取账号列表数据_搜索
    getUserListSearch() {
      getUserListSearch().then((res) => {
        this.user_list = res.data;
      });
    },
    // 获得省市县列表_搜索
    getAddressListSearch(type, code) {
      switch (type) {
        case 1:
          getProvince().then((res) => {
            this.province_list_search = res.data;
          });
          break;
        case 2:
          getCity(code).then((res) => {
            this.city_list_search = res.data;
          });
          break;
        case 3:
          getArea(code).then((res) => {
            this.area_list_search = res.data;
          });
          break;
        default:
          break;
      }
    },
    // 选择省份_搜索
    chooseProvinceSearch(e) {
      this.city_list_search = [];
      this.page.data.cityId = "";
      this.page.data.cityName = "";
      this.area_list_search = [];
      this.page.data.areaId = "";
      this.page.data.areaName = "";
      this.getAddressListSearch(2, e);
      this.getTagList(e);
    },
    // 选择市_搜索
    chooseCitySearch(e) {
      this.area_list = [];
      this.page.data.areaId = "";
      this.page.data.areaName = "";
      this.getAddressListSearch(3, e);
    },
    // 返回列表序号
    indexMethod(index) {
      return (this.page.pageNum - 1) * this.page.pageSize + index + 1;
    },
    // 移除黑名单
    removeUser(id) {
      this.$confirm("确定要将此用户移除黑名单吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        center: true,
      }).then(() => {
        removeBlack(id).then((res) => {
          this.fetchData();
          this.$message({
            type: "success",
            message: "移除成功!",
          });
        });
      });
    },
  },
  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>

