<template>
  <div class="child-container">
    <div class="table-list" v-show="!info">
      <div class="search-box">
        <gridsTitle title="查询条件" />
        <el-form
          :model="queryParams"
          ref="queryForm"
          size="small"
          :inline="true"
          label-width="95px"
          class="search-from"
        >
          <el-form-item label="人员姓名：" prop="name">
            <el-input v-model="queryParams.name" clearable></el-input>
          </el-form-item>
          <el-form-item label="性别：" prop="sex">
            <el-select v-model="queryParams.sex" clearable>
              <el-option
                :label="sex.label"
                :value="sex.value"
                v-for="sex in dictList.sex"
                :key="sex.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="部门：" prop="division">
            <el-input v-model="queryParams.division" clearable></el-input>
          </el-form-item>
          <el-form-item label="执法证号：" prop="lawNumber">
            <el-input v-model="queryParams.lawNumber" clearable></el-input>
          </el-form-item>
          <el-form-item label="状态：" prop="status">
            <el-select v-model="queryParams.status" clearable>
              <el-option label="停用中" :value="1"></el-option>
              <el-option label="启用中" :value="2"></el-option>
            </el-select>
          </el-form-item>
          <div class="search-btn">
            <el-button icon="el-icon-my-reset" size="mini" @click="resetQuery"
              >重置</el-button
            >
            <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="handleQuery"
              >搜索</el-button
            >
          </div>
        </el-form>
      </div>
      <div class="table-box">
        <gridsTitle title="检查员列表" />
        <div class="table-data">
          <el-row :gutter="10" class="mb8 table-top-btn">
            <!-- <el-col :span="1.5">
              <el-button
                v-hasPermi="['inspector:global:score']"
                plain
                icon="el-icon-star-off"
                size="mini"
                @click="conditionSet()"
                >评分条件设置</el-button
              >
            </el-col> -->
            <el-col :span="1.5">
              <el-button
                v-hasPermi="['inspector:global:export']"
                plain
                icon="el-icon-edit-outline"
                size="mini"
                :disabled="multiple"
                @click="openModel(0)"
                >导出</el-button
              >
            </el-col>
            <el-col :span="1.5">
              <el-button
                v-hasPermi="['inspector:global:Import']"
                plain
                icon="el-icon-my-import"
                size="mini"
                @click="handleImport()"
                >导入</el-button
              >
            </el-col>
            <el-col :span="1.5">
              <el-button
                v-hasPermi="['inspector:global:download']"
                type="text"
                icon="el-icon-download"
                size="mini"
                @click="openModel(1)"
                >导入模版下载</el-button
              >
            </el-col>
          </el-row>
          <el-table
            v-loading="loading"
            :data="tableList"
            height="83%"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column type="index" label="序号" width="55">
            </el-table-column>
            <el-table-column label="人员姓名" align="center" prop="name" />
            <el-table-column label="性别" align="center" prop="sex">
              <template slot-scope="scope">
                {{
                  scope.row.sex == 1 ? "男" : scope.row.sex == 2 ? "女" : "未知"
                }}
              </template>
            </el-table-column>
            <el-table-column label="职务" align="center" prop="duty">
              <template slot-scope="scope">
                {{ filterDict(scope.row.duty, "duty") }}
              </template>
            </el-table-column>
            <el-table-column label="来源" align="center" prop="source">
              <template slot-scope="scope">
                {{ filterDict(scope.row.source, "source") }}
              </template>
            </el-table-column>
            <el-table-column label="执法证号" align="center" prop="lawNumber">
              <!-- <template slot-scope="scope">
                {{ filterDict(scope.row.lawNumber, "lawNumber") }}
              </template> -->
            </el-table-column>
            <el-table-column label="执法证有效期" align="center" prop="lawTime">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.lawTime, "{y}-{m}-{d}") }}</span>
              </template>
            </el-table-column>
            <el-table-column
              label="部门"
              align="center"
              prop="division"
              :show-overflow-tooltip="true"
            >
              <template slot-scope="scope">
                {{ filterDict(scope.row.division, "division") }}
              </template>
            </el-table-column>
            <el-table-column
              label="检查员层级"
              align="center"
              prop="inspectorLevel"
            >
              <template slot-scope="scope">
                {{ filterDict(scope.row.inspectorLevel, "inspectorLevel") }}
              </template>
            </el-table-column>
            <el-table-column
              label="检查员类别"
              align="center"
              prop="inspectorType"
              :show-overflow-tooltip="true"
            >
              <template slot-scope="scope">
                {{ scope.row.inspectorType }}
              </template>
            </el-table-column>
            <el-table-column
              label="检查员级别"
              align="center"
              prop="inspectorGrade"
            >
              <template slot-scope="scope">
                {{ filterDict(scope.row.inspectorGrade, "inspectorGrade") }}
              </template>
            </el-table-column>
            <el-table-column label="状态" align="center" prop="status">
              <template slot-scope="scope">
                {{
                  scope.row.status == 1
                    ? "停用中"
                    : scope.row.status == 2
                    ? "启用中"
                    : "未知"
                }}
              </template>
            </el-table-column>
            <el-table-column
              label="操作"
              align="center"
              class-name="small-padding fixed-width"
            >
              <template slot-scope="scope">
                <el-button
                  v-hasPermi="['inspector:global:info']"
                  size="mini"
                  plain
                  type="primary"
                  @click="getInfo(scope.row)"
                  >详情</el-button
                >
                <el-button
                  v-hasPermi="['inspector:global:state']"
                  size="mini"
                  plain
                  :type="scope.row.status == 1 ? 'success' : 'danger'"
                  @click="updata(scope.row)"
                  >{{
                    scope.row.status == 1
                      ? "启用"
                      : scope.row.status == 2
                      ? "停用"
                      : "未知"
                  }}</el-button
                >
              </template>
            </el-table-column>
          </el-table>
          <pagination
            v-show="total > 0"
            :total="total"
            :page.sync="queryParams.current"
            :limit.sync="queryParams.size"
            @pagination="getList"
          />
        </div>
      </div>
    </div>

    <div class="table-info" v-if="info">
      <userMsgPage
        :showBack="true"
        @getSonData="getSonData"
        :inspectorId="inspectorId"
      ></userMsgPage>
    </div>

    <el-dialog
      :visible.sync="showSet"
      width="35%"
      append-to-body
      destroy-on-close
      custom-class="my-dialog-container"
    >
      <div slot="title" class="my-dialog-title">评分条件设置</div>

      <div class="my-dialog-content">
        <div class="content-head">
          <i class="el-icon-warning-outline"></i>
          提示：选择相应条件后，系统会根据计算方式自动计算出评分
        </div>
        <!-- <div class="contentSelect"> -->
        <div v-for="(item, index) in formData.list" :key="index">
          <div class="contentAdd">
            <span>因子1:</span>

            <div class="itemContent">
              <el-select
                v-model="formData.value"
                size="small"
                placeholder="请选择"
              >
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </div>

            <div class="itemContent">
              <el-input
                placeholder="请输入内容"
                v-model="formData.value1"
                size="small"
              >
                <template slot="prepend">权重</template>
              </el-input>
            </div>
            <div
              :class="[index > 0 ? 'deleteIcon' : 'contentIcon']"
              @click="addCondition(index)"
            >
              <i
                :class="[
                  index > 0
                    ? 'el-icon-remove-outline'
                    : 'el-icon-circle-plus-outline',
                ]"
              ></i>
            </div>
          </div>
        </div>
      </div>
      <div class="manner">
        <span>计算方式:</span>
        <div class="inputM">
          <el-select v-model="formData.value" size="small" placeholder="请选择">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </div>
      </div>

      <div slot="footer" class="my-dialog-footer">
        <el-button icon="el-icon-refresh-left">重置</el-button>
        <el-button type="primary" icon="el-icon-s-promotion">提交</el-button>
      </div>
    </el-dialog>

    <!-- 下载模版 -->
    <el-dialog
      :visible.sync="uploadTel"
      width="400px"
      append-to-body
      custom-class="my-dialog-container"
    >
      <div slot="title" class="my-dialog-title">{{ ModelTitle }}</div>
      <div class="upload-list">
        <div
          v-for="item in telList"
          :key="item.value"
          @click="uploadTemplate(item.value, item.lable)"
        >
          <el-link type="primary">
            {{ item.lable }}<span v-if="ModelTitle != '导出数据'">模版</span>
            <span v-else>数据</span>
          </el-link>
        </div>
      </div>
    </el-dialog>

    <!-- 用户导入对话框 -->
    <el-dialog
      :visible.sync="upload.open"
      width="400px"
      append-to-body
      custom-class="my-dialog-container"
      destroy-on-close
    >
      <div slot="title" class="my-dialog-title">{{ upload.title }}</div>
      <div class="upload-row">
        <div class="row-lable">数据模块：</div>
        <div class="row-value">
          <el-select v-model="uploadData.value" placeholder="请选择">
            <el-option
              v-for="item in telList"
              :key="item.value"
              :label="item.lable"
              :value="item.value"
            ></el-option>
          </el-select>
        </div>
      </div>

      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx,.xls,"
        :headers="upload.headers"
        :action="upload.url"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :on-error="handleFileError"
        :auto-upload="false"
        :data="uploadData"
        :file-list="fileList"
        :on-change="fileChange"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <!-- <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" />
            是否更新已经存在的用户数据
          </div> -->
          <span style="color: red"
            >仅允许导入xls、xlsx格式文件，请按照数据格式要求导入数据。</span
          >
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" type="primary" @click="submitFileForm"
          >确 定</el-button
        >
        <el-button size="small" @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { Loading } from "element-ui";
var downloadLoadingInstance;
import userMsgPage from "../userMsgPage/index2.vue";
import {
  getList,
  uploadFile,
  dictList,
  updataRow,
  exportFile,
  exportExcel,
} from "@/api/jcy";
import gridsTitle from "../components/gridsTitle";

export default {
  components: {
    gridsTitle,
    userMsgPage,
  },
  data() {
    return {
      fileList: [],
      ModelTitle: "",
      currentTab: 0, //导出、下载
      ids: [],
      multiple: true,
      //字典
      dict: {},
      inspectorId: null,
      //显示评分条件设置
      showSet: false,
      //输入框
      formData: {
        value1: "",
        list: [
          {
            a1: "1",
            a2: "2",
          },
        ],
      },
      options: [],
      //详情
      info: false,
      // 遮罩层
      loading: true,
      // 总条数
      total: 0,
      //接口条件
      queryParams: {
        name: "",
        sex: "",
        lawNumber: "",
        division: "",
        current: 1,
        size: 10,
        status: "",
      },
      //表格数据
      tableList: [],
      // 下载模版
      uploadTel: false,
      telList: [
        { lable: "基础信息", value: 0 },
        { lable: "培训情况", value: 1 },
        { lable: "聘任信息", value: 2 },
        { lable: "奖惩信息", value: 3 },
        { lable: "年度考核情况", value: 4 },
      ],
      // 导入模版参数
      uploadData: {
        value: 0,
      },
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: {
          Authentication: localStorage.getItem("MSSM-LIAONING__TOKEN"),
        },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API2 + "/common/importExcel",
      },
    };
  },
  created() {
    this.getDict(
      "duty,source,inspectorLevel,inspectorType,inspectorGrade,division"
    );
  },

  methods: {
    /**表格全选 */
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.multiple = !selection.length;
    },
    /**过滤字典 */
    filterDict(value, type) {
      if (this.dict[type] == undefined) {
        return value;
      }
      let dictLable = this.dict[type].filter((item) => item.dictValue == value);
      return dictLable.length > 0 ? dictLable[0].dictLabel : value;
    },
    /**获取字典列表 */
    getDict(typeList) {
      let query = {
        list: typeList,
      };
      dictList(query).then((res) => {
        if (res.status == 200) {
          for (let key in res.result) {
            this.dict[key] = res.result[key];
          }
        }
        this.getList();
      });
    },
    /**停用 */
    updata(row) {
      let title = "";
      let params = {};
      if (row.status == 1) {
        params.id = row.id;
        params.status = 2;
        title = "您确定要启用吗?";
      } else {
        params.id = row.id;
        params.status = 1;
        title = "您确定要停用吗?";
      }
      this.$confirm(`${title}`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          updataRow(params).then((res) => {
            this.$modal.msgSuccess("修改成功");
            this.getList();
          });
        })
        .catch(() => {
          this.$modal.msgWarning("已取消操作！");
        });
    },
    /**导出或者下载 */
    openModel(index) {
      this.currentTab = index;
      if (index == 0) {
        this.ModelTitle = "导出数据";
      } else {
        this.ModelTitle = "模版下载";
      }
      this.uploadTel = true;
    },
    /**下载模板、导出 */
    uploadTemplate(value, lable) {
      if (this.currentTab == 1) {
        let suffix = "xlsx";
        let baseUrl =
          location.origin +
          process.env.VUE_APP_PREFIX +
          `/static/file/${lable}.${suffix}`;
        const link = document.createElement("a");
        link.href = baseUrl;
        link.style.display = "none";
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        // let params = {
        //   value,
        // };
        // uploadFile(params).then((res) => {
        //   this.uploadFile(
        //     res.data.data.result.url,
        //     res.data.data.result.originalFilename
        //   );
        // });
      } else {
        let params = {
          value: value,
          ids: this.ids.toString(),
        };
        exportExcel(params).then((res) => {
          if (res.data.code == 200) {
            this.uploadFile(
              res.data.data.result.url,
              res.data.data.result.originalFilename
            );
          }
        });
      }
    },
    // /**导出 */
    // handleExport() {
    //   let ids = this.ids.toString();
    //   exportFile(ids).then((res) => {
    //     if (res.data.status == 200) {
    //       this.uploadFile(
    //         res.data.result.url,
    //         res.data.result.originalFilename
    //       );
    //     }
    //   });
    // },
    fileChange(file, fileList) {
      this.fileList = fileList;
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "检查员信息导入";
      this.upload.open = true;
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      console.log("wenjian", fileList);
      this.upload.isUploading = true;
    },
    //上传失败
    handleFileError(err, file, fileList) {
      this.fileList = [];
      downloadLoadingInstance.close();
      let myError = JSON.parse(err.toString().replace("Error: ", "")); //转字符串
      this.$modal.msgError(myError.message);
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      downloadLoadingInstance.close();
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.fileList = [];
      this.$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
          response.msg +
          "</div>",
        "导入结果",
        { dangerouslyUseHTMLString: true }
      );
      if (this.uploadData.value == 0) {
        this.getList();
      }
    },
    // 提交上传文件
    submitFileForm() {
      console.log(this.fileList, "文件");
      if (this.fileList.length == 0) {
        this.$modal.msgError("请先上传文件！");
        return;
      }
      downloadLoadingInstance = Loading.service({
        text: "正在导入数据，请稍候",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      this.$refs.upload.submit();
    },

    //评分条件设置
    conditionSet() {
      this.showSet = true;
    },
    addCondition(e) {
      if (e == 0) {
        this.formData.list.push({
          a1: "1",
          a2: "2",
        });
      } else {
        this.formData.list.splice(0, 1);
      }
    },
    /**打开详情页 */
    getInfo(rows) {
      this.inspectorId = rows.id;
      this.info = !this.info;
    },
    /**详情返回 */
    getSonData(e) {
      this.info = e.isShow;
      this.resetQuery();
    },
    /**获取表格数据 */
    getList() {
      this.loading = true;
      getList(this.queryParams).then((res) => {
        this.tableList = res.result.records;
        this.total = res.result.total;
        this.loading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.current = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
  },
};
</script>

<style lang="scss" scoped>
.child-container {
  height: 100%;
  & > div {
    height: 100%;
  }
  // 表格部分
  .table-list {
    display: flex;
    flex-direction: column;
    align-items: center;
    .search-box {
      .search-from {
        padding: 15px;
      }
      .search-btn {
        position: relative;
        left: 50%;
        bottom: 0;
        transform: translateZ(-50%);
      }
    }
    .table-box {
      flex: 1;
      margin-top: 10px;
      .table-data {
        height: calc(100% - 40px);
        box-sizing: border-box;
        padding: 15px;
        position: relative;
        .paginBox {
          position: absolute;
          bottom: 15px;
          width: 100%;
          width: 98%;
          margin: 0;
        }
      }
    }
    & > div {
      width: 100%;
      border-radius: 6px;
      background-color: #fff;
    }
  }
  .table-top-btn {
    margin-bottom: 15px;
  }
  // 结束
}
::v-deep .search-from {
  .el-form-item__label {
    font-size: 14px;
    font-weight: 500;
    color: #4d5158;
  }
  .el-select,
  .el-input {
    width: 300px;
  }
}
//弹出框
.my-dialog-title {
  font-size: 16px;
  font-weight: 550;
  color: #333333;
  background: #e9eff7;
  padding: 10px 0 10px 16px;
}
.my-dialog-content {
  padding-left: 40px;

  .content-head {
    font-size: 14px;
    font-weight: 400;
    color: #8e8e8e;
    line-height: 24px;
  }
  .contentAdd {
    display: flex;
    align-items: center;
    margin-top: 10px;
    span {
      font-size: 14px;
      font-weight: 500;
      color: #4d5158;
      margin-right: 4px;
    }
    .itemContent {
      width: 40%;
      margin: 0 4px;
    }
    .contentIcon {
      font-size: 22px;
      color: #22c98d;
      margin-left: 4px;
      cursor: pointer;
    }
    .deleteIcon {
      font-size: 22px;
      color: #f76359;
      margin-left: 4px;
      cursor: pointer;
    }
  }
}
.manner {
  padding-left: 19px;
  display: flex;
  align-items: center;
  margin-top: 10px;
  span {
    font-size: 14px;
    font-weight: 500;
    color: #4d5158;
    margin-right: 4px;
  }
  .inputM {
    width: 78.5%;
    margin-left: 4px;
  }
}
::v-deep .el-select {
  width: 100%;
}
.my-dialog-footer ::v-deep .el-button {
  padding: 8px 10px !important;
}
.my-dialog-footer ::v-deep .el-button--primary {
  background: #ff9822 !important;
  border: 1px solid #ff9822;
}
.upload-row {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
  .row-lable {
    font-size: 14px;
  }
}
.upload-list {
  & > div {
    margin-bottom: 10px;
  }
  & > :last-child {
    margin-bottom: 0;
  }
}
</style>
