<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
    >
      <!-- <el-form-item label="岗检编号">
        <el-input
          v-model="queryParams.postCode"
          placeholder="请输入"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="工作组：">
        <el-select v-model="queryParams.checkGroupId" placeholder="请选择">
          <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-input
          v-model="queryParams.checkedPostNames"
          placeholder="请输入"
          clearable
        />
      </el-form-item> -->
      <el-form-item label="年度：">
        <el-date-picker
          v-model="valueYear"
          type="year"
          placeholder="选择年"
          value-format="yyyy"
          :clearable="false"
        >
        </el-date-picker>
      </el-form-item>
      <!-- <el-form-item label="职责归属">
        <el-input
          v-model="queryParams.postCode"
          placeholder="请输入"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </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="downloadTemplate"
          v-hasPermi="['postCheck:postCheckedProblem:export']"
          >模板下载</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          @click="uploadDialog = true"
          v-hasPermi="['postCheck:postCheckedProblem:export']"
          >批量导入</el-button
        >
      </el-col>
    </el-row>
    <el-table
      border
      v-loading="loading"
      :data="postList"
      height="calc(100% - 90px)"
    >
      <el-table-column label="序号" align="center" type="index" width="80" />
      <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.checkTeamName || "--" }}</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.checkedPostNames || "--" }}</span>
        </template>
      </el-table-column> -->
      <el-table-column label="岗检状态" align="center">
        <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.checkTime || "--" }}</span>
        </template>
      </el-table-column> -->
      <!-- <el-table-column label="问题属性" align="center">
        <template slot-scope="{ row }">
          <span>{{ problematicData[row.problemAttribute] || "--" }}</span>
        </template>
      </el-table-column>
      <el-table-column label="问题类别" align="center">
        <template slot-scope="{ row }">
          <span>{{ questionData[row.problemCategory] || "--" }}</span>
        </template>
      </el-table-column> -->
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        width="120"
      >
        <template slot-scope="scope">
          <el-button
            type="text"
            v-if="scope.row.children.length === 0"
            @click="handleCheck('录入', scope.row)"
            v-hasPermi="['postCheck:postCheckedProblem:add']"
            >录入</el-button
          >
          <el-button
            type="text"
            v-if="scope.row.children.length > 0"
            @click="handleCheck('修改', scope.row)"
            v-hasPermi="['postCheck:postCheckedProblem:edit']"
            >修改</el-button
          >
          <el-button
            v-if="scope.row.children.length > 0"
            type="text"
            @click="handleCheck('查看', scope.row)"
            >查看</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="title"
      :visible="establishDialog"
      :fullscreen="true"
      @close="cancelEstablish"
    >
      <h1 style="text-align: center">岗位责任制检查问题录入</h1>
      <div style="display: flex; font-size: 16px; margin-bottom: 16px">
        <div>检查部门：{{ row.checkedDeptName }}</div>
      </div>
      <el-form
        ref="form"
        class="gwzr"
        :model="form"
        :rules="rules"
        :disabled="this.title === '查看'"
      >
        <el-table
          ref="tableData"
          border
          v-loading="loading"
          :data="form.postList"
          style="height: calc(100vh - 350px)"
        >
          <el-table-column
            label="序号"
            align="center"
            type="index"
            width="80"
          />
          <!-- <el-table-column label="问题编号" align="center" width="250px">
            <template slot-scope="{ row, $index }">
              <span v-if="row.index">{{ row.index }}</span>
              <span v-else>GJ-MF5-2023-Z-{{ formatIndex($index + 1) }}</span>
            </template>
          </el-table-column> -->
          <el-table-column label="涉及岗位" align="center" width="200px">
            <template slot-scope="{ row, $index }">
              <el-form-item label-width="0">
                <el-select
                  v-model="row.checkedPostId"
                  placeholder="请选择"
                  :disabled="statusType(row.status)"
                  @change="(id) => handelPost(id, $index)"
                >
                  <el-option
                    v-for="item in checkedPostList"
                    :key="item.postId"
                    :label="item.postName"
                    :value="item.postId"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="检查时间" align="center" width="300px">
            <template slot-scope="{ row }">
              <el-form-item label-width="0">
                <el-date-picker
                  v-model="row.checkTime"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  type="date"
                  placeholder="选择日期"
                  :disabled="statusType(row.status)"
                >
                </el-date-picker>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="检查人员" align="center" width="150px">
            <template slot-scope="{ row }">
              <el-form-item label-width="0">
                <el-input
                  v-model="row.checkUserName"
                  :disabled="statusType(row.status)"
                  placeholder="请输入"
                  clearable
                />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="问题级别" align="center" width="100px">
            <template slot-scope="{ row }">
              <el-form-item label-width="0">
                <el-radio-group
                  v-model="row.problemLevel"
                  :disabled="statusType(row.status)"
                >
                  <el-radio
                    v-for="(item, k) in levelData"
                    :key="item"
                    :label="k"
                    >{{ item }}</el-radio
                  >
                </el-radio-group>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="职责类别" align="center" width="240px">
            <template slot-scope="{ row }">
              <el-form-item label-width="0">
                <el-radio-group
                  v-model="row.dutyType"
                  :disabled="statusType(row.status)"
                >
                  <el-radio
                    v-for="(item, k) in dutyData"
                    :key="item"
                    :label="k"
                    >{{ item }}</el-radio
                  >
                </el-radio-group>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="问题属性" align="center" width="100px">
            <template slot-scope="{ row }">
              <el-form-item label-width="0">
                <el-radio-group
                  v-model="row.problemAttribute"
                  :disabled="statusType(row.status)"
                >
                  <el-radio
                    v-for="(item, k) in problematicData"
                    :key="item"
                    :label="k"
                    >{{ item }}</el-radio
                  >
                </el-radio-group>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="问题类别" align="center" width="200px">
            <template slot-scope="{ row }">
              <el-form-item label-width="0">
                <el-radio-group
                  v-model="row.problemCategory"
                  :disabled="statusType(row.status)"
                >
                  <el-radio
                    v-for="(item, k) in questionData"
                    :key="item"
                    :label="k"
                    >{{ item }}
                  </el-radio>
                </el-radio-group>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="问题描述" align="center">
            <template slot-scope="{ row }">
              <el-form-item label-width="0">
                <el-input
                  type="textarea"
                  :autosize="{ minRows: 4, maxRows: 6 }"
                  :disabled="statusType(row.status)"
                  placeholder="请输入"
                  v-model="row.description"
                >
                </el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <!-- <el-table-column
            v-if="this.title !== '查看'"
            label="操作"
            align="center"
            class-name="small-padding fixed-width"
            width="160"
          >
            <template slot-scope="scope">
              <el-button
                type="text"
                v-if="form.postList.length > 1"
                @click="handleDelete(scope.row)"
                v-hasPermi="['system:post:edit']"
                >删除</el-button
              >
              <span v-else>-</span>
            </template>
          </el-table-column> -->
        </el-table>
      </el-form>
      <el-button
        v-if="this.title !== '查看'"
        style="margin-top: 16px"
        type="primary"
        @click="addNewItem"
        >添加问题</el-button
      >
      <div slot="footer" class="dialog-footer" v-if="this.title !== '查看'">
        <el-button type="primary" @click="submitForm">保存</el-button>
        <el-button @click="cancelEstablish">取消</el-button>
      </div>
    </el-dialog>
    <el-dialog
      title="导入"
      :visible.sync="uploadDialog"
      width="520px"
      @close="canceUpload"
    >
      <el-form ref="formUpload" :model="formUpload" label-width="120px">
        <el-form-item label="导入：">
          <el-upload
            ref="upload"
            accept=""
            :action="uploadFileUrl"
            :on-progress="handleFileUploadProgress"
            :on-success="handleFileSuccess"
            :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="submitUpload">确认</el-button>
        <el-button @click="canceUpload">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  addPostPlanJoinProblem,
  listCheckedProblem,
  updatePostPlanJoinProblem,
  getJoinProblemList,
  batchImport
} from "@/api/postImplementation/problemEntry.js";
import {
  listGroupList,
  getOptionselectTwo,
} from "@/api/postInspectionPlanning/teamManagement.js";
import { getToken } from "@/utils/auth";
import download from "@/plugins/download.js"
import { getBaseUrl } from "@/utils/baseUrl.js";

export default {
  name: "Post",
  dicts: ["sys_normal_disable"],
  data() {
    return {
      uploadDialog: false,
      fileList: [],
      formUpload: {},
      uploadList: [],
      uploadFileUrl: getBaseUrl() + "/common/upload",
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      valueYear: "",
      groupList: [],
      checkedPostList: [],
      row: "",
      checkDialog: false,
      templateManagementDialog: false,
      textarea2: "",
      // 文件预览
      previewAnnex: false,
      previewUrl: "",
      previewType: "",
      filename: "",
      active: 0,
      establishDialog: false,
      options: [
        {
          value: "选项1",
          label: "待审核",
        },
        {
          value: "选项2",
          label: "已通过",
        },
        {
          value: "选项3",
          label: "未通过",
        },
      ],
      levelData: {
        1: "一般",
        2: "重要",
      },
      dutyData: {
        1: "业务职责",
        2: "党建及党风廉政建设职责",
        3: "安全环保职责",
        4: "合规与保密职责",
        5: "任职资格与能力素质要求",
        6: "岗位责任制文件完整性与适宜性"
      },
      problematicData: {
        1: "完整性",
        2: "适宜性",
        3: "有效性",
      },
      questionData: {
        1: "职责权限问题",
        2: "工作内容问题",
        3: "工作标准问题",
        4: "考核奖励问题",
        5: "任职资格问题",
        6: "其他",
      },
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      postList: [],
      status: {
        1: "未检",
        2: "已检",
      },
      statusColor: {
        1: "red",
        2: "#67C23A",
      },
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: getBaseUrl() + "/system/user/importData",
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        checkGroupId: undefined,
        checkedPostNames: undefined,
      },
      // 表单参数
      form: {
        postList: [
          {
            checkUserName: "",
            problemLevel: "",
            dutyType: "",
            problemAttribute: "",
            problemCategory: "",
            checkTime: "",
            checkedPostId: "",
          },
        ],
        // rules: {},
      },
      // 表单校验
      rules: {
        postName: [
          { required: true, message: "岗位名称不能为空", trigger: "blur" },
        ],
        postCode: [
          { required: true, message: "岗位编码不能为空", trigger: "blur" },
        ],
        postSort: [
          { required: true, message: "岗位顺序不能为空", trigger: "blur" },
        ],
      },
    };
  },
  computed: {
    formatIndex() {
      return (index) => {
        return index.toString().padStart(6, "0");
      };
    },
    statusType() {
      return (type) => {
        return type && type !== 1;
      };
    },
  },
  created() {
    this.initYear();
    this.getList();
    this.getGroupList();
  },
  methods: {
    handelPost(id, index) {
      const find = this.checkedPostList.find((item) => item.postId === id);
      console.log(find, "find")
      this.form.postList[index].checkTime = find.checkTime;
      this.form.postList[index].checkUserName = find.checkUserName;
    },
    initYear() {
      let _now = new Date();
      let currentYear = _now.getFullYear();
      this.valueYear = `${currentYear}`;
    },
    getGroupList() {
      listGroupList().then((data) => {
        this.groupList = data.data;
      });
    },
    getOptionselect(id, planId) {
      this.checkedPostList = [];
      getOptionselectTwo(id, planId).then((data) => {
        this.checkedPostList = data.data;
      });
    },
    addNewItem() {
      this.form.postList.push({
        checkUserName: "",
        problemLevel: "",
        dutyType: "",
        problemAttribute: "",
        problemCategory: "",
        checkTime: "",
        checkedPostId: "",
      });
      this.$nextTick(() => {
        this.$refs.tableData.bodyWrapper.scrollTop =
          this.$refs.tableData.bodyWrapper.scrollHeight;
      });
    },
    handleDelete(row) {
      this.$confirm("是否删除？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.form.postList = this.form.postList.filter(
            (item) => item.id !== row.id
          );
        })
        .catch(() => false);
    },
    /** 查询岗位列表 */
    getList() {
      this.loading = true;
      const dateRange = [`${this.valueYear}-01-01`, `${this.valueYear}-12-31`];
      getJoinProblemList(this.addDateRange(this.queryParams, dateRange)).then(
        (response) => {
          this.postList = response.rows;
          this.total = response.total;
          this.loading = false;
        }
      );
    },
    // 表单重置
    cancelEstablish() {
      this.form = this.$options.data().form;
      this.establishDialog = false;
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams = this.$options.data().queryParams;
      this.initYear();
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.postId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.establishDialog = true;
    },
    /** 查看 */
    handleCheck(title, row) {
      this.title = title;
      this.row = row;
      this.getOptionselect(row.checkedDeptId, row.planId);
      if (this.title !== "录入") {
        this.form.postList = row.children.map((item) => {
          return {
            ...item,
            dutyType: item.dutyType + "",
            problemAttribute: item.problemAttribute + "",
            problemCategory: item.problemCategory + "",
            problemLevel: item.problemLevel + "",
          };
        });
        this.establishDialog = true;
      } else {
        this.establishDialog = true;
      }
    },
    /** 提交按钮 */
    submitForm: function () {
      const postList = this.form.postList.map((item) => {
        return {
          ...item,
          planInfoId: this.row.planInfoId,
          dutyType: item.dutyType * 1,
          problemAttribute: item.problemAttribute * 1,
          problemCategory: item.problemCategory * 1,
          problemLevel: item.problemLevel * 1,
        };
      });

      if (this.title === "录入") {
        addPostPlanJoinProblem(postList).then((response) => {
          this.$modal.msgSuccess("新增成功");
          this.establishDialog = false;
          this.getList();
        });
      } else {
        const list1 = postList.filter((item) => item.status == 1);
        const list2 = postList.filter((item) => !item.id);
        if (list2.length === 0) {
          this.$modal.msgWarning("请添加问题！！！");
        } else {
          updatePostPlanJoinProblem(list1).then((response) => {
            this.$modal.msgSuccess("修改成功");
            this.establishDialog = false;
            this.getList();
          });
        }
        if (list2.length > 0) {
          addPostPlanJoinProblem(list2).then((response) => {
            this.establishDialog = false;
            this.getList();
          });
        }
      }
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/post/export",
        {
          ...this.queryParams,
        },
        `post_${new Date().getTime()}.xlsx`
      );
    },

    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);
    },
    downloadTemplate() {
      download.resource(
        // "/template/附件1.《岗位责任制检查问题录入》（模板）.xlsx"
        "/template/问题清单批量导入（模板）.xls"
      );
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {},
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.uploadList.push({
        name: response.originalFilename,
        url: response.fileName,
      });
    },
    // 表单重置
    canceUpload() {
      this.uploadDialog = false;
      this.formUpload = this.$options.data().formUpload;
      this.fileList = [];
      this.uploadList = [];
    },
    /** 提交按钮 */
    submitUpload: function () {
      const uploadList = this.uploadList.map(item => item.url);
      batchImport(uploadList).then((response) => {
        this.$modal.msgSuccess("已导入");
        this.canceUpload();
        this.getList();
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.resetStyle {
  width: 100%;
  ::v-deep .el-upload {
    width: 100%;
    .el-upload-dragger {
      width: 100%;
    }
  }
}
::v-deep .el-radio-group {
  display: flex;
  flex-wrap: wrap;
}
.gwzr {
  ::v-deep .el-table__body-wrapper {
    height: calc(100% - 40px);
    overflow: auto;
  }
  ::v-deep .el-form-item {
    margin-bottom: 0;
  }
}
</style>
