<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true">
      <el-form-item label="部门：">
        <el-cascader
          v-model="queryParams.checkedDeptId"
          :options="deptTreeList"
        >
        </el-cascader>
      </el-form-item>
      <el-form-item label="岗位：">
        <el-input
          v-model="queryParams.checkedPostName"
          placeholder="请输入"
          clearable
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <!-- <el-row :gutter="10" class="mb8" type="flex" justify="end">
      <el-col :span="1.5">
        <el-button
          type="primary"
          @click="establishDialog = true"
          v-hasPermi="['system:post:add']"
          >导入</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          @click="handleCheck('add', '新增')"
          v-hasPermi="['system:post:add']"
          >新增</el-button
        >
      </el-col>
    </el-row> -->
    <el-table
      border
      v-loading="loading"
      :data="postList"
      height="calc(100% - 140px)"
    >
      <el-table-column label="序号" type="index" align="center" width="80" />
      <!-- <el-table-column label="岗检编号" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.postCode || "--" }}</span>
        </template>
      </el-table-column> -->
      <!-- <el-table-column label="工作组" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.checkWorkgroupName || "--" }}</span>
        </template>
      </el-table-column> -->
      <!-- <el-table-column label="检查小组" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.checkGroupName || "--" }}</span>
        </template>
      </el-table-column> -->
      <el-table-column label="部门" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.checkedDeptName || "--" }}</span>
        </template>
      </el-table-column>
      <el-table-column label="岗位" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.checkedPostName || "--" }}</span>
        </template>
      </el-table-column>
      <el-table-column label="检查项" align="center">
        <!--
        <template slot-scope="{ row }">
          <span>{{ row.name || "--" }}</span>
        </template>
        -->
        <template slot-scope="{ row }">
          <!--
          检查项目：1-业务职责；2-党建及党风廉政建设职责；3-安全环保职责；4-合规保密职；5-任职资格与能力素质要求
          -->
          <span>{{ unique(row.children) || "--" }}</span>
        </template>
      </el-table-column>
      <el-table-column label="检查类别" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.checkedType == 1 ? "全要素" : "自定义" || "--" }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="{ row }">
          <span :style="{ color: statusColor[row.status] }">{{
            status[row.status]
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="未通过原因" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.reason || "--" }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="140">
        <template slot-scope="scope">
          <el-button
            type="text"
            @click="handleCheck('edit', '修改', scope.row)"
            v-hasPermi="['postCheck:postChecked:edit']"
            >自定义检查</el-button
          >
          <el-button type="text" @click="handelPrevie(scope.row)"
            >预览</el-button
          >
          <!-- <el-button
            v-if="scope.row.status !== 3"
            type="text"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:post:edit']"
            >删除</el-button
          > -->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改对话框 -->
    <el-dialog
      title="自定义检查"
      :visible.sync="open"
      width="1500px"
      @colse="cancel"
      :close-on-click-modal="false"
    >
      <el-form
        ref="form"
        :model="form"
        label-width="100px"
        style="padding: 0 50px; max-height: 950px; overflow: auto"
        :disabled="type === 'check'"
      >
        <!-- <el-form-item label="工作组：">
          <el-select
            v-model="form.checkGroupId"
            placeholder="请选择"
            style="width: 100%"
            @change="handleGroupId"
          >
            <el-option
              v-for="item in groupList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item> -->
        <!-- <el-form-item label="检查小组：">
          <el-select
            v-model="form.checkWorkgroupId"
            placeholder="请选择"
            style="width: 100%"
          >
            <el-option
              v-for="item in teamList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item label="部门：">
          <el-cascader
            v-model="form.checkedDeptId"
            :options="deptTreeList"
            @change="handleChange"
            style="width: 100%; margin-bottom: 10px"
          >
          </el-cascader>
        </el-form-item>
        <el-form-item label="岗位：">
          <el-select
            v-model="form.checkedPostId"
            placeholder="请选择"
            style="width: 100%"
            @change="handleCheckPost"
          >
            <el-option
              v-for="item in checkedPostList"
              :key="item.postId"
              :label="item.postName"
              :value="item.postId"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="岗检项目：">
          <el-select
            v-model="form.type"
            placeholder="请选择"
            multiple
            style="width: 100%"
          >
            <el-option
              v-for="item in typeList"
              :key="item.type"
              :label="item.typeView"
              :value="item.type"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item  label="检查内容：">
        </el-form-item> -->
        <div
          v-for="(edit, index) in form.children"
          :key="index"
          class="form-list"
        >
          <div class="form-item" v-if="form.type.includes(edit.type)">
            <el-form-item label-width="200" :label="edit.label + '：'">
              <el-select
                v-model="edit.postCheckedContent"
                placeholder="请选择"
                multiple
                style="width: 100%"
              >
                <el-option
                  v-for="(item, index) in edit.options"
                  :key="index"
                  :label="item.postCheckedContent"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </div>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer" v-if="type !== 'check'">
        <el-button type="primary" @click="submitForm">保存</el-button>
        <el-button @click="cancel">取消</el-button>
      </div>
    </el-dialog>
    <el-dialog
      title="导入岗检表"
      :visible="establishDialog"
      width="500px"
      append-to-body
      @close="cancelEstablish"
    >
      <el-form label-width="100px">
        <el-form-item label="上传岗检表：">
          <el-upload
            ref="upload"
            accept=""
            multiple
            :action="uploadFileUrl"
            :on-progress="handleFileUploadProgress"
            :on-success="handleFileSuccess"
            :on-remove="handleDeleteFile"
            :headers="headers"
            :file-list="fileList"
            drag
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">
              将文件拖到此处，或<em>点击上传</em>
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="addTemplate">确定</el-button>
        <el-button @click="cancelEstablish">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog
      title="预览附件"
      :visible.sync="previewAnnex"
      :fullscreen="true"
      :close-on-click-modal="false"
      :destroy-on-close="true"
    >
      <preview-file
        :preview-url="previewUrl"
        :preview-type="previewType"
        @handleDownload="handleDownload"
      />

      <div slot="footer" class="batch-dialog-footer">
        <el-button type="primary" @click="previewAnnex = false">
          关闭
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listChecked,
  delChecked,
  addChecked,
  updateChecked,
  getTypeList,
  getListByType,
  batchImport,
  preview,
} from "@/api/postInspectionPlanning/tableManagement.js";
import {
  listGroupList,
  getDeptTree,
  getOptionselect,
  getTeamListByGroupId,
  getTeamUserByTeamId,
} from "@/api/postInspectionPlanning/teamManagement.js";
import { getBase64 } from "@/api/postInspectionPlanning/projectManagement.js";
import { getToken } from "@/utils/auth";
import  { getBaseUrl } from '@/utils/baseUrl.js'
export default {
  name: "Post",
  dicts: ["sys_normal_disable"],
  data() {
    return {
      uploadFileList: [],
      // 文件预览
      previewAnnex: false,
      previewUrl: "",
      previewType: "",
      filename: "",
      fileList: [],
      uploadFileUrl: getBaseUrl() + "/common/upload",
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      groupList: [],
      teamList: [],
      userList: [],
      deptTreeList: [],
      checkedPostList: [],
      typeList: [],
      type: "",
      rowId: "",
      establishDialog: false,
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 岗位表格数据
      postList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      status: {
        1: "待审核",
        2: "审核中",
        3: "通过",
        4: "驳回",
      },
      statusColor: {
        1: "#cdd152",
        2: "#61dd83",
        3: "#61dd83",
        4: "red",
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        checkedPostName: undefined,
        checkedDeptId: [],
      },
      // 表单参数

      // 表单参数
      form: {
        checkedPostId: "",
        checkedDeptId: "",
        type: [],
        children: [],
      },
      // 表单校验
      rules: {
        // postName: [
        //   { required: true, message: "岗位名称不能为空", trigger: "blur" },
        // ],
        // postCode: [
        //   { required: true, message: "岗位编码不能为空", trigger: "blur" },
        // ],
        // postSort: [
        //   { required: true, message: "岗位顺序不能为空", trigger: "blur" },
        // ],
      },
    };
  },
  created() {
    this.getList();
    this.getGroupList();
    this.getDeptTree();
    this.getTypeList();
  },
  methods: {
    // 去重检查项目：1-业务职责；2-党建及党风廉政建设职责；3-安全环保职责；4-合规保密职；5-任职资格与能力素质要求
    unique(children) {
      const type = [...new Set(children.map((item) => item.type))];
      const tempView = this.typeList
        .filter((item) => type.includes(item.type))
        .map((item) => item.typeView)
        .join(",");
      return tempView;
    },
    getTypeList() {
      getTypeList().then((data) => {
        this.typeList = data.data;
      });
    },
    handleCheckPost() {
      const deptId =
        this.form.checkedDeptId[this.form.checkedDeptId.length - 1];
      this.form.children = [];
      this.form.type = [];
      this.typeList.forEach((item) => {
        getListByType({
          deptId,
          postId: this.form.checkedPostId,
          type: item.type,
        }).then((res) => {
          this.form.children.push({
            options: res.data,
            type: item.type,
            label: item.typeView,
            postCheckedContent: [],
          });
        });
      });
    },
    /** 查询岗位列表 */
    getList() {
      this.loading = true;
      const checkedDeptId =
        this.queryParams.checkedDeptId[
          this.queryParams.checkedDeptId.length - 1
        ];
      listChecked({ ...this.queryParams, checkedDeptId }).then((response) => {
        this.postList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getDeptTree() {
      getDeptTree().then((data) => {
        this.deptTreeList = data.data;
      });
    },
    getParentList(keyNmame, code, tree) {
      let arr = []; //要返回的数组
      for (let i = 0; i < tree.length; i++) {
        let item = tree[i];
        arr = [];
        arr.push(item[keyNmame]); //保存当前节点id
        if (code == item[keyNmame]) {
          //判断当前id是否是默认id
          return arr; //是则退出循环、返回数据
        } else {
          //否则进入下面判断，判断当前节点是否有子节点数据
          if (item.children && item.children.length > 0) {
            //合并子节点返回的数据
            arr = arr.concat(this.getParentList(keyNmame, code, item.children));
            if (arr.includes(code)) {
              //如果当前数据中已包含默认节点，则退出循环、返回数据
              return arr;
            }
          }
        }
      }
    },
    getGroupList() {
      listGroupList().then((data) => {
        this.groupList = data.data;
      });
    },
    async handleGroupId(id) {
      this.form.checkTeamId = "";
      if (id) {
        const { data } = await getTeamListByGroupId(id);
        this.teamList = data;
      }
    },
    getOptionselect(id) {
      getOptionselect(id).then((data) => {
        this.checkedPostList = data.data;
      });
    },
    handleChange(arr) {
      this.form.checkedPostId = "";
      this.checkedPostList = [];
      const id = arr[arr.length - 1];
      this.getOptionselect(id);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = this.$options.data().form;
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams = this.$options.data().queryParams;
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.establishDialog = true;
    },
    /** 查看 */
    handleCheck(type, title, row) {
      this.form.children = [];
      this.type = type;
      this.title = title;
      if (!row) {
        this.open = true;
        return;
      }
      this.form.type = [...new Set(row.children.map((item) => item.type))];
      this.typeList.forEach((item) => {
        getListByType({
          deptId: row.checkedDeptId,
          postId: row.checkedPostId,
          type: item.type,
        }).then((res) => {
          this.form.children.push({
            options: res.data,
            type: item.type,
            label: item.typeView,
            postCheckedContent: row.children
              .filter((d) => d.type === item.type)
              .map((d) => d.childrenTypeId),
          });
        });
      });
      // this.handleGroupId(row.checkGroupId);
      this.form.checkedDeptId = this.getParentList(
        "value",
        row.checkedDeptId,
        this.deptTreeList
      );
      this.handleChange(this.form.checkedDeptId);
      this.form.checkedPostId = row.checkedPostId;
      this.open = true;
      this.rowId = row.id;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const postId = row.postId || this.ids;
      getPost(postId).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改";
      });
    },
    /** 提交按钮 */
    submitForm: function () {
      const typeList = this.form.children.filter((item) =>
        this.form.type.includes(item.type)
      );
      const children = [];
      typeList.forEach((item) => {
        const list = item.options.filter((res) =>
          item.postCheckedContent.includes(res.id)
        );
        children.push(...list);
      });
      children.forEach((item) => {
        item.childrenTypeId = item.id;
      });
      const params = {
        checkedPostId: this.form.checkedPostId,
        checkedDeptId:
          this.form.checkedDeptId[this.form.checkedDeptId.length - 1],
        children,
      };
      addChecked(params).then((response) => {
          this.$modal.msgSuccess("新增成功");
          this.cancel();
          this.getList();
        });
      // if (this.type === "edit") {
      //   updateChecked({ ...params, id: this.rowId }).then((response) => {
      //     this.$modal.msgSuccess("修改成功");
      //     this.cancel();
      //     this.getList();
      //   });
      // } else {
      //   addChecked(params).then((response) => {
      //     this.$modal.msgSuccess("新增成功");
      //     this.cancel();
      //     this.getList();
      //   });
      // }
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const postIds = row.id;
      this.$modal
        .confirm("是否确认删除？")
        .then(function () {
          return delChecked(postIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/post/export",
        {
          ...this.queryParams,
        },
        `post_${new Date().getTime()}.xlsx`
      );
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      // this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.uploadFileList.push({
        name: response.originalFilename,
        url: response.fileName,
      });
    },
    handleDeleteFile(file) {
      const findex = this.uploadFileList.map((f) => f.name).indexOf(file.name);
      if (findex > -1) {
        this.uploadFileList.splice(findex, 1);
      }
    },
    cancelEstablish() {
      this.uploadFileList = [];
      this.fileList = [];
      this.establishDialog = false;
    },
    addTemplate() {
      const fileList = this.uploadFileList.map((item) => item.url);
      batchImport(fileList).then((response) => {
        this.$modal.msgSuccess("导入成功");
        this.cancelEstablish();
        this.getList();
      });
    },
    async handelPrevie(path) {
      const { msg } = await preview(path.id);
      getBase64({ path: msg }).then((res) => {
        let wj = encodeURIComponent(res.msg);
        wj = decodeURIComponent(wj);
        const myBlob = this.dataURLtoBlob(wj);
        this.previewUrl = myBlob;
        this.previewType = this.iconByType(
          msg.split(".")[msg.split(".").length - 1]
        );
        this.filename = this.getFileName(msg);
        this.previewAnnex = true;
      });
    },

    handleDownload(path) {
      getBase64({ path }).then((res) => {
        let wj = encodeURIComponent(res.msg);
        wj = decodeURIComponent(wj);
        const myBlob = this.dataURLtoBlob(wj);
        this.previewUrl = myBlob;
        this.previewType = this.iconByType(
          path.split(".")[path.split(".").length - 1]
        );
        this.filename = this.getFileName(path);
        this.handleDownload();
      });
    },
    // 获取文件后缀名
    iconByType(filename) {
      return filename.substring(filename.lastIndexOf(".") + 1, filename.length);
    },
    // 获取文件名称
    getFileName(name) {
      // 如果是url那么取最后的名字 如果不是直接返回
      if (name.lastIndexOf("/") > -1) {
        return name.slice(name.lastIndexOf("/") + 1);
      } else {
        return name;
      }
    },
    dataURLtoBlob(dataurl) {
      const arr = dataurl.split(",");
      const mime = arr[0].match(/:(.*?);/)[1];
      const bstr = atob(arr[1]);
      let n = bstr.length;
      const u8arr = new Uint8Array(n);
      // eslint-disable-next-line no-plusplus
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new Blob([u8arr], { type: mime });
    },
    handleDownload() {
      // 生成地址
      var myUrl = URL.createObjectURL(this.previewUrl);

      // 下载文件
      this.downloadFile(myUrl, this.filename);
    },
    downloadFile(url, name) {
      const a = document.createElement("a");
      a.setAttribute("href", url);
      a.setAttribute("download", name);
      a.setAttribute("target", "_blank");
      const clickEvent = document.createEvent("MouseEvents");
      clickEvent.initEvent("click", true, true);
      a.dispatchEvent(clickEvent);
    },
  },
};
</script>
<style lang="scss" scoped>
.resetStyle {
  width: 100%;
  ::v-deep .el-upload {
    width: 100%;
    .el-upload-dragger {
      width: 100%;
    }
  }
}
</style>
