<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
    >
      <el-form-item label="部门：">
        <el-cascader
          v-model="queryParams.checkedDeptId"
          :options="deptTreeList"
        >
        </el-cascader>
      </el-form-item>
      <el-form-item label="当前状态：">
        <el-select v-model="queryParams.status" placeholder="请选择">
          <el-option
            v-for="(item, k) in status"
            :key="item.value"
            :label="item"
            :value="k"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="问题级别：">
        <el-select v-model="queryParams.problemLevel" placeholder="请选择">
          <el-option
            v-for="(item, k) in levelData"
            :key="item.value"
            :label="item"
            :value="k"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="问题属性：">
        <el-select v-model="queryParams.problemAttribute" placeholder="请选择">
          <el-option
            v-for="(item, k) in problematicData"
            :key="item.value"
            :label="item"
            :value="k"
          >
          </el-option>
        </el-select>
      </el-form-item> -->
      <el-form-item label="职责类别：">
        <el-select v-model="queryParams.dutyType" placeholder="请选择">
          <el-option
            v-for="(item, k) in dutyData"
            :key="item.value"
            :label="item"
            :value="k"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="问题类别：">
        <el-select v-model="queryParams.problemCategory" placeholder="请选择">
          <el-option
            v-for="(item, k) in questionData"
            :key="item.value"
            :label="item"
            :value="k"
          >
          </el-option>
        </el-select>
      </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>
        <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="space-between">
      <el-col :span="1.5">
        <el-button
          type="primary"
          @click="handleCheck(false)"
          :disabled="multiple"
          >指定整改责任人</el-button
        >
      </el-col>
      <div>
        <el-col :span="1.5">
          <!--
           岗检问题导入导出再导入的业务说明：
            1、导入岗检问题：用户下载模板后，线下将问题录入到Excel中，将Excel上传到服务器，后台保存新增的问题
              POST /postCheck/postCheckedProblem/batchImport 参数数数组，放到请求的Body中
            2、导出岗检问题：选择选择需要导出的问题，导出成Excel文件
              GET /postCheck/postCheckedProblem/batchExport 参数Param类型的，参数属性是‘ids’逗号拼接（问题的id唯一主键），直接拼接到URL后面即可，例如：ids?123456,987654
            3、整改方案/整改实施：用户先导出文件，再在导出文件的基础上填充问题的方案和整改实施信息后将表格重新导入到系统中
              POST /postCheck/postCheckedProblem/batchImportRectification 参数数数组，放到请求的Body中

            注意看！！！
            注意看！！！
            注意看！！！
              这里不是下载模板，应该修改为问题导出，GET /postCheck/postCheckedProblem/batchExport 参数Param类型的，参数属性是‘ids’逗号拼接（问题的id唯一主键），直接拼接到URL后面即可，例如：ids?123456,987654
          <el-button type="primary" @click="downloadTemplate">模板下载</el-button>
          -->
          <el-button type="primary" @click="batchExport">问题导出</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="primary" @click="uploadDialog = true"
            >批量导入</el-button
          >
        </el-col>
      </div>
    </el-row>
    <el-table
      border
      v-loading="loading"
      :data="postList"
      @selection-change="handleSelectionChange"
      height="calc(100% - 150px)"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        label="问题编号"
        align="center"
        prop="problemNo"
        min-width="190px"
      />
      <el-table-column label="受检部门" align="center" min-width="180px">
        <template slot-scope="{ row }">
          <span>{{ row.checkedDeptName || "--" }}</span>
        </template>
      </el-table-column>
      <el-table-column label="问题级别" align="center">
        <template slot-scope="{ row }">
          <span>{{ levelData[row.problemLevel] || "--" }}</span>
        </template>
      </el-table-column>
      <el-table-column label="职责类别" align="center" min-width="180px">
        <template slot-scope="{ row }">
          <span>{{ dutyData[row.dutyType] || "--" }}</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" min-width="150px">
        <template slot-scope="{ row }">
          <span>{{ questionData[row.problemCategory] || "--" }}</span>
        </template>
      </el-table-column>
      <el-table-column label="问题原因" align="center" min-width="250px">
        <template slot-scope="{ row }">
          <span>{{ row.problemCause || "--" }}</span>
        </template>
      </el-table-column>
      <el-table-column label="整改责任人" align="center" min-width="150px">
        <template slot-scope="{ row }">
          <span>{{ row.rectificationResponsibleName || "--" }}</span>
        </template>
      </el-table-column>
      <el-table-column label="整改期限" align="center" min-width="190px">
        <template slot-scope="{ row }">
          <span>{{ row.rectificationPeriod || "--" }}</span>
        </template>
      </el-table-column>
      <el-table-column label="当前状态" align="center" min-width="150px">
        <template slot-scope="{ row }">
          <span :style="{ color: statusColor[row.status] }">{{
            status[row.status]
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="整改完成时间" align="center" min-width="190px">
        <template slot-scope="{ row }">
          <span>{{ row.rectificationCompletionTime || "--" }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        min-width="240"
        fixed="right"
      >
        <template slot-scope="scope">
          <el-button type="text" @click="handleUpdate('查看', scope.row)"
            >查看</el-button
          >
          <el-button
            type="text"
            v-if="[2, 12, 22, 42].includes(scope.row.status)"
            @click="handleUpdate('填写整改方案', scope.row, 1)"
            >填写整改方案</el-button
          >
          <el-button
            v-if="scope.row.status === 30"
            type="text"
            @click="handleUpdate('填写整改情况', scope.row, 2)"
            >填写整改情况</el-button
          >
          <el-dropdown
            size="mini"
            v-if="[2, 12, 22, 42].includes(scope.row.status)"
            @command="(command) => handleCommand(command, scope.row)"
          >
            <el-button size="mini" type="text" icon="el-icon-d-arrow-right"
              >邮件通知</el-button
            >
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="handleAuditor"
                >管理员</el-dropdown-item
              >
              <el-dropdown-item command="handlePrepared"
                >整改责任人</el-dropdown-item
              >
            </el-dropdown-menu>
          </el-dropdown>
        </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="open"
      :fullscreen="true"
      @close="cancel"
    >
      <el-row :gutter="30" style="padding: 0 40px">
        <el-col :span="12">
          <el-descriptions title="整改方案" :column="2" border>
            <el-descriptions-item :labelStyle="labelStyle">
              <template slot="label"> 岗检编号 </template>
              {{ form.problemNo }}
            </el-descriptions-item>
            <el-descriptions-item :labelStyle="labelStyle">
              <template slot="label"> 岗检工作组 </template>
              {{ form.checkWorkgroupName }}
            </el-descriptions-item>
            <el-descriptions-item :labelStyle="labelStyle">
              <template slot="label"> 岗检小组 </template>
              {{ form.checkGroupName }}
            </el-descriptions-item>
            <el-descriptions-item :labelStyle="labelStyle">
              <template slot="label"> 检查人员 </template>
              {{ form.checkUserName }}
            </el-descriptions-item>
            <el-descriptions-item :labelStyle="labelStyle">
              <template slot="label"> 问题级别 </template>
              {{ levelData[form.problemLevel] }}
            </el-descriptions-item>
            <el-descriptions-item :labelStyle="labelStyle">
              <template slot="label"> 问题属性 </template>
              {{ problematicData[form.problemAttribute] }}
            </el-descriptions-item>
            <el-descriptions-item :labelStyle="labelStyle">
              <template slot="label"> 问题类别 </template>
              {{ questionData[form.problemCategory] }}
            </el-descriptions-item>
            <el-descriptions-item :labelStyle="labelStyle">
              <template slot="label"> 检查时间 </template>
              {{ form.checkTime }}
            </el-descriptions-item>
          </el-descriptions>
          <el-descriptions :column="1" border>
            <el-descriptions-item :labelStyle="labelStyle">
              <template slot="label"> 职责类别 </template>
              {{ dutyData[form.dutyType] }}
            </el-descriptions-item>
            <el-descriptions-item :labelStyle="labelStyle">
              <template slot="label"> 问题原因 </template>
              <el-input
                type="textarea"
                :autosize="{ minRows: 4, maxRows: 6 }"
                placeholder="请输入"
                v-model="form.problemCause"
                :disabled="check || sszg"
              >
              </el-input>
            </el-descriptions-item>
            <el-descriptions-item :labelStyle="labelStyle">
              <template slot="label"> 是否立行立改问题 </template>
              <el-radio-group
                v-model="form.isImmediatelyCorrected"
                :disabled="check || sszg"
              >
                <el-radio :label="1">是</el-radio>
                <el-radio :label="2">否</el-radio>
              </el-radio-group>
            </el-descriptions-item>
            <el-descriptions-item :labelStyle="labelStyle">
              <template slot="label"> 整改措施/建议 </template>
              <el-input
                type="textarea"
                :autosize="{ minRows: 4, maxRows: 6 }"
                placeholder="请输入"
                v-model="form.rectificationMeasure"
                :disabled="check || sszg"
              >
              </el-input>
            </el-descriptions-item>
            <el-descriptions-item :labelStyle="labelStyle">
              <template slot="label"> 整改责任部门 </template>
              <el-cascader
                :disabled="check"
                v-model="form.checkedDeptId"
                :options="deptTreeList"
                @change="handleChange"
              >
              </el-cascader>
            </el-descriptions-item>
            <el-descriptions-item :labelStyle="labelStyle">
              <template slot="label"> 整改责任人 </template>
              <el-select
                v-model="form.rectificationResponsibleUserId"
                placeholder="请选择"
                :disabled="check || sszg"
              >
                <el-option
                  v-for="item in depUserList"
                  :key="item.userId"
                  :label="item.nickName"
                  :value="item.userId"
                >
                </el-option>
              </el-select>
            </el-descriptions-item>
            <el-descriptions-item :labelStyle="labelStyle">
              <template slot="label"> 整改期限 </template>
              <el-date-picker
                v-model="form.rectificationPeriod"
                type="date"
                placeholder="选择日期"
                value-format="yyyy-MM-DD"
                :disabled="check || sszg"
              >
              </el-date-picker>
            </el-descriptions-item>
            <el-descriptions-item
              :labelStyle="labelStyle"
              v-if="[30, 40, 41, 42].includes(form.status) && !fazg"
            >
              <template slot="label"> 整改完成 </template>
              <el-radio-group
                v-model="form.isRectificationCompleted"
                :disabled="check"
              >
                <el-radio :label="1">是</el-radio>
                <el-radio :label="2">否</el-radio>
              </el-radio-group>
            </el-descriptions-item>
            <el-descriptions-item
              :labelStyle="labelStyle"
              v-if="[30, 40, 41, 42].includes(form.status) && !fazg"
            >
              <template slot="label"> 整改完成证明（图片或文件）</template>
              <el-link
                v-if="check"
                type="primary"
                @click="handelPrevie(form.rectificationCompletionImg)"
                >{{ getFileName(form.rectificationCompletionImg) }}</el-link
              >
              <el-upload
                v-else
                ref="upload"
                :limit="1"
                accept="pdf,docx,xls,xlsx,png,jpg,jpeg"
                :headers="upload.headers"
                :action="upload.url"
                :disabled="upload.isUploading"
                :before-upload="handleBeforeUpload"
                :on-progress="handleFileUploadProgress"
                :on-success="handleFileSuccess"
                :auto-upload="false"
              >
                <i class="el-icon-upload"></i>
                <div slot="tip" class="el-upload__tip">
                  只能上传pdf/docx/xls/xlsx/png/jpg/jpeg文件
                </div>
              </el-upload>
            </el-descriptions-item>
            <el-descriptions-item
              :labelStyle="labelStyle"
              v-if="[30, 40, 41, 42].includes(form.status) && !fazg"
            >
              <template slot="label"> 整改完成时间 </template>
              <el-date-picker
                v-model="form.rectificationCompletionTime"
                type="date"
                placeholder="选择日期"
                :disabled="check"
                value-format="yyyy-MM-DD"
              >
              </el-date-picker>
            </el-descriptions-item>
          </el-descriptions>
          <div class="queryButton" v-if="!check">
            <el-button @click="cancel">取消</el-button>
            <el-button type="primary" @click="submitForm" v-if="fazg"
              >确定</el-button
            >
            <el-button v-if="fazg" type="primary" @click="handleCheck(true)"
              >选择专业部门审核人</el-button
            >
            <el-button
              v-if="sszg && !form.reviewDepartmentReviewerId"
              type="primary"
              @click="handleCheck(true)"
              >选择复查人</el-button
            >
            <el-button
              v-if="sszg && form.reviewDepartmentReviewerId"
              type="primary"
              @click="handelSSZG"
              >确认提交</el-button
            >
          </div>
        </el-col>
        <div style="height: 16px"></div>
        <el-col :span="12">
          <span class="el-descriptions__header"
            ><div class="el-descriptions__title">操作记录</div></span
          >
          <div class="col-body">
            <p v-for="(item, index) in recordList" :key="index">
              <span style="margin-right: 10px">{{ item.createTime }}</span
              ><span>"{{ item.userBy }}"{{ item.content }}</span>
            </p>
          </div>
          <div v-if="form.reason">
            <span class="el-descriptions__header"
              ><div class="el-descriptions__title">驳回原因</div></span
            >
            <el-input
              v-model="form.reason"
              placeholder="请输入"
              type="textarea"
              disabled
              :autosize="{ minRows: 4, maxRows: 6 }"
            />
          </div>
        </el-col>
      </el-row>
    </el-dialog>

    <el-dialog :visible.sync="checkDialog" :fullscreen="true">
      <el-form :model="userParams" size="small" :inline="true">
        <el-form-item label="部门：">
          <el-cascader v-model="userParams.deptId" :options="deptTreeList">
          </el-cascader>
        </el-form-item>
        <el-form-item label="岗位名称：">
          <el-input
            v-model="userParams.postName"
            placeholder="请输入"
            clearable
          />
        </el-form-item>
        <el-form-item label="人员名称：">
          <el-input
            v-model="userParams.nickName"
            placeholder="请输入"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            @click="handleQueryUser"
            >搜索</el-button
          >
          <el-button icon="el-icon-refresh" @click="resetQueryUser"
            >重置</el-button
          >
        </el-form-item>
      </el-form>
      <el-table border v-loading="loading" :data="userList">
        <el-table-column label="序号" align="center" type="index" width="80" />
        <!-- <el-table-column label="部门属性" align="center">
          <template slot-scope="{ row }">
            <span>{{ row.checkedDeptTypeView || "--" }}</span>
          </template>
        </el-table-column> -->
        <el-table-column label="姓名" align="center">
          <template slot-scope="{ row }">
            <span>{{ row.nickName || "--" }}</span>
          </template>
        </el-table-column>
        <el-table-column label="部门" align="center">
          <template slot-scope="{ row }">
            <span>{{ row.deptName || "--" }}</span>
          </template>
        </el-table-column>
        <el-table-column label="岗位" align="center">
          <template slot-scope="{ row }">
            <span>{{ row.postName || "--" }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
          width="200"
        >
          <template slot-scope="scope">
            <el-button type="text" @click="handleSH(scope.row)">{{
              isBatch ? "指定整改审核人" : "指定填写人"
            }}</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="userTotal > 0"
        :total="userTotal"
        :page.sync="userParams.pageNum"
        :limit.sync="userParams.pageSize"
        @pagination="getPostUserList"
      />
    </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"
        :preview-img-url="previewImgUrl"
        @handleDownload="handleDownload"
      />

      <div slot="footer" class="batch-dialog-footer">
        <el-button type="primary" @click="previewAnnex = false">
          关闭
        </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="handleFileSuccessUpload"
            :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 {
  listCheckedProblem,
  getCheckedProblem,
  delCheckedProblem,
  addCheckedProblem,
  updateCheckedProblem,
  setRectificationResponsibleUserId,
  updateRectificationMeasure,
  setSpecialityDepartmentReviewerId,
  setDeptApproveTime,
  setSpecialityDepartmentReviewTime,
  updateRectificationCompletionImg,
  setReviewDepartmentReviewerId,
  setReviewDepartmentReviewerTime,
  postCheckedProblemRecord,
  batchImportRectification,
  batchExport,
} from "@/api/postImplementation/remediationAction.js";
import {
  getPostUserList,
  getDeptTree,
} from "@/api/postInspectionPlanning/teamManagement.js";
import { getBase64 } from "@/api/postInspectionPlanning/projectManagement.js";
import { getToken } from "@/utils/auth";
import download from "@/plugins/download.js";
import { getBaseUrl } from "@/utils/baseUrl.js";
import { sendMailFile } from "@/api/postInspectionPlanning/projectManagement.js";
export default {
  data() {
    return {
      previewImgUrl: "",
      uploadDialog: false,
      fileList: [],
      formUpload: {},
      uploadList: [],
      uploadFileUrl: getBaseUrl() + "/common/upload",
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      valueYear: "",
      deptTreeList: [],
      labelStyle: {
        width: "150px",
        "font-weight": 600,
        color: "#000",
      },
      options: [
        {
          value: "选项1",
          label: "刘易斯",
        },
        {
          value: "选项2",
          label: "李涛",
        },
        {
          value: "选项3",
          label: "张三",
        },
      ],
      isBatch: false,
      checkDialog: false,
      textarea2: "",
      // 文件预览
      previewAnnex: false,
      previewUrl: "",
      previewType: "",
      filename: "",
      active: 0,
      establishDialog: false,
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: getBaseUrl() + "/common/upload",
      },
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 岗位表格数据
      levelData: {
        1: "一般",
        2: "重要",
      },
      dutyData: {
        1: "业务职责",
        2: "党建及党风廉政建设职责",
        3: "安全环保职责",
        4: "合规与保密职责",
        5: "任职资格与能力素质要求",
        6: "岗位责任制文件完整性与适宜性",
      },
      problematicData: {
        1: "完整性",
        2: "适宜性",
        3: "有效性",
      },
      questionData: {
        1: "职责权限问题",
        2: "工作内容问题",
        3: "工作标准问题",
        4: "考核奖励问题",
        5: "任职资格问题",
        6: "其他",
      },
      postList: [],
      status: {
        1: "待指定整改人",
        2: "待填写方案",
        10: "待部门审核",
        11: "部门审核通过",
        12: "部门审核驳回",
        20: "待专业部门人审核",
        21: "专业部门人审核通过",
        22: "专业部门人审核驳回",
        30: "上传实施图片",
        40: "待复查部门人审核",
        41: "复查部门人审核通过",
        42: "复查部门人审核驳回",
      },
      statusColor: {
        1: "#E6A23C",
        2: "#E6A23C",
        10: "#E6A23C",
        11: "#67C23A",
        12: "#F56C6C",
        20: "#E6A23C",
        21: "#67C23A",
        22: "#F56C6C",
        30: "#67C23A",
        40: "#E6A23C",
        41: "#67C23A",
        42: "#F56C6C",
      },
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        problemLevel: "",
        problemAttribute: "",
        status: "",
        problemCategory: "",
        dutyType: "",
        checkedDeptId: [],
      },
      // 表单参数
      form: {
        checkGroupId: "",
        checkTime: "",
        checkUserId: "",
        checkWorkgroupId: "",
        checkedDeptId: "",
        dutyType: "",
        isImmediatelyCorrected: "",
        isRectificationCompleted: "",
        problemAttribute: "",
        problemCategory: "",
        problemCause: "",
        problemLevel: "",
        problemNo: "",
        rectificationCompletionImg: "",
        rectificationMeasure: "",
        rectificationPeriod: "",
        rectificationResponsibleUserId: "",
        specialityDepartmentReviewTime: "",
        rectificationCompletionTime: "",
      },
      // 表单校验
      rules: {
        // postName: [
        //   { required: true, message: "岗位名称不能为空", trigger: "blur" },
        // ],
        // postCode: [
        //   { required: true, message: "岗位编码不能为空", trigger: "blur" },
        // ],
        // postSort: [
        //   { required: true, message: "岗位顺序不能为空", trigger: "blur" },
        // ],
      },
      userList: [],
      userParams: {
        pageNum: 1,
        pageSize: 10,
        nickName: "",
        postName: "",
        deptId: [],
      },
      userTotal: 0,
      typeSH: "",
      rowId: "",
      recordList: [],
      depUserList: [],
      userId: "",
    };
  },
  computed: {
    check() {
      return this.title === "查看";
    },
    sszg() {
      return this.title === "填写整改情况";
    },
    fazg() {
      return this.title === "填写整改方案";
    },
  },
  created() {
    this.initYear();
    this.getList();
    this.getPostUserList();
    this.getDeptTree();
  },
  methods: {
    // 发送邮件
    handleCommand(command, row) {
      const params = {
        content: "",
        serviceId: row.id,
        serviceType: "",
      };
      this.$confirm("是否发送？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          switch (command) {
            case "handleAuditor":
              params.serviceType = "problem_admin";
              sendMailFile(params).then(() => {
                this.$modal.msgSuccess("发送成功");
              });
              break;
            case "handlePrepared":
              params.serviceType = "problem_rectification_responsible_user";
              sendMailFile(params).then(() => {
                this.$modal.msgSuccess("发送成功");
              });
              break;
            default:
              break;
          }
        })
        .catch(() => false);
    },
    postCheckedProblemRecord() {
      postCheckedProblemRecord({ problemId: this.rowId }).then((data) => {
        this.recordList = data.rows;
      });
    },
    initYear() {
      let _now = new Date();
      let currentYear = _now.getFullYear();
      this.valueYear = `${currentYear}`;
    },
    handleChange(arr) {
      this.getUserList(arr);
    },
    getDeptTree() {
      getDeptTree().then((data) => {
        this.deptTreeList = data.data;
      });
    },
    // 上传前校检格式和大小
    handleBeforeUpload(file) {
      // 校检文件类型
      const fileName = file.name.split(".");
      const fileExt = fileName[fileName.length - 1];
      const isTypeOk =
        ["docx", "xls", "xlsx", "pdf", "png", "jpg", "jpeg"].indexOf(fileExt) >=
        0;
      if (!isTypeOk) {
        this.$modal.msgError(
          `文件格式不正确, 请上传${[
            "docx",
            "xls",
            "xlsx",
            "pdf",
            "png",
            "jpg",
            "jpeg",
          ].join("/")}格式文件!`
        );
        return false;
      }
      return true;
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.isUploading = false;
      const params = {
        id: this.rowId,
        isRectificationCompleted: this.form.isRectificationCompleted,
        rectificationCompletionImg: response.fileName,
        rectificationCompletionTime: this.form.rectificationCompletionTime,
      };
      if (this.form.reviewDepartmentReviewerId) {
        updateRectificationCompletionImg(params).then((data) => {
          this.cancel();
          this.$refs.upload.clearFiles();
          this.$modal.msgSuccess("保存成功");
          this.getList();
          this.checkDialog = false;
        });
        return;
      }
      updateRectificationCompletionImg(params).then((data) => {
        const params = {
          id: this.rowId,
          reviewDepartmentReviewerId: this.userId,
        };
        setReviewDepartmentReviewerId(params).then((data) => {
          this.cancel();
          this.$refs.upload.clearFiles();
          this.$modal.msgSuccess("保存成功");
          this.getList();
          this.checkDialog = false;
        });
      });
    },
    handelSSZG() {
      this.$refs.upload.submit();
    },
    handleSH(item) {
      if (this.typeSH === 1) {
        const params = {
          id: this.rowId,
          specialityDepartmentReviewerId: item.userId,
        };
        setSpecialityDepartmentReviewerId(params).then((data) => {
          this.submitForm();
          this.checkDialog = false;
        });
      } else if (this.typeSH === 2) {
        this.userId = item.userId;
        this.$refs.upload.submit();
      } else {
        const params = {
          ids: this.ids.join(","),
          rectificationResponsibleUserId: item.userId,
        };
        setRectificationResponsibleUserId(params).then((data) => {
          console.log(data, "data");
          this.checkDialog = false;
          this.$modal.msgSuccess("已指定填写人");
          this.getList();
        });
      }
    },
    getPostUserList() {
      const deptId = this.userParams.deptId[this.userParams.deptId.length - 1];
      getPostUserList({ ...this.userParams, deptId }).then((response) => {
        this.userList = response.rows;
        this.userTotal = response.total;
      });
    },
    /** 查询岗位列表 */
    getList() {
      this.loading = true;
      const dateRange = [`${this.valueYear}-01-01`, `${this.valueYear}-12-31`];
      const checkedDeptId =
        this.queryParams.checkedDeptId[
          this.queryParams.checkedDeptId.length - 1
        ];
      listCheckedProblem(
        this.addDateRange({ ...this.queryParams, checkedDeptId }, dateRange)
      ).then((response) => {
        this.postList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    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.queryParams = this.$options.data().queryParams;
      this.initYear();
      this.handleQuery();
    },
    /** 搜索按钮操作 */
    handleQueryUser() {
      this.getPostUserList();
    },
    /** 重置按钮操作 */
    resetQueryUser() {
      this.userParams = this.$options.data().userParams;
      this.handleQueryUser();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 查看 */
    handleCheck(type) {
      this.checkDialog = true;
      this.isBatch = type;
      // this.reset();
      // const postId = row.postId || this.ids;
      // getPost(postId).then((response) => {
      //   this.form = response.data;
      //   this.checkDialog = true;
      //   this.title = "查看";
      // });
    },
    handleUpdate(title, row, typeSH) {
      this.typeSH = typeSH;
      this.rowId = row.id;
      this.postCheckedProblemRecord();
      getCheckedProblem(row.id).then((data) => {
        this.form = data.data;
        this.open = true;
        this.title = title;
        this.form.checkedDeptId = this.getParentList(
          "value",
          this.form.checkedDeptId,
          this.deptTreeList
        );
        this.getUserList(this.form.checkedDeptId);
      });
    },
    getUserList(arr) {
      if (!arr) return;
      const id = arr[arr.length - 1];
      getPostUserList({ deptId: id }).then((response) => {
        this.depUserList = response.rows;
      });
    },
    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;
            }
          }
        }
      }
    },
    /** 提交按钮 */
    submitForm: function () {
      const params = {
        problemCause: this.form.problemCause,
        isImmediatelyCorrected: this.form.isImmediatelyCorrected,
        rectificationMeasure: this.form.rectificationMeasure,
        rectificationResponsibleUserId:
          this.form.rectificationResponsibleUserId,
        rectificationPeriod: this.form.rectificationPeriod,
        id: this.rowId,
      };
      updateRectificationMeasure(params).then((data) => {
        this.cancel();
        this.$modal.msgSuccess("保存成功");
        this.getList();
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const postIds = row.postId || this.ids;
      this.$modal
        .confirm('是否确认删除岗位编号为"' + postIds + '"的数据项？')
        .then(function () {
          return delPost(postIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },

    handelPrevie(path) {
      getBase64({ path }).then((res) => {
        let wj = encodeURIComponent(res.msg);
        wj = decodeURIComponent(wj);
        const myBlob = this.dataURLtoBlob(wj);
        this.previewUrl = myBlob;
        this.previewImgUrl = res.msg;
        this.previewType = this.iconByType(
          path.split(".")[path.split(".").length - 1]
        );
        this.filename = this.getFileName(path);
        this.previewAnnex = true;
      });
    },

    handleDown(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);
    },
    downloadTemplate() {
      download.resource("/template/附件1.《整改实施》（模板）.xlsx");
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {},
    // // 文件上传成功处理
    handleFileSuccessUpload(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);
      batchImportRectification(uploadList).then((response) => {
        this.$modal.msgSuccess("已导入");
        this.canceUpload();
        this.getList();
      });
    },
    batchExport() {
      batchExport({ ids: this.ids.join(",") }).then((res) => {
        download.resource(res.msg);
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.resetStyle {
  width: 100%;
  ::v-deep .el-upload {
    width: 100%;
    .el-upload-dragger {
      width: 100%;
    }
  }
}
.card {
  margin-right: 10px; //下边距
  margin-top: 10px;
  padding: 10px;
  background: transparent;
  border: 2px solid;
  border-color: #e5e5e5;
  border-image: none;
  ::v-deep .el-card__body {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  .el-avatar {
    width: 120px !important;
    height: 120px !important;
    margin: 14px 14px;
  }
  p {
    margin: 0;
    width: 100%;
    text-overflow: ellipsis;
    overflow: hidden;
    white-space: nowrap;
    line-height: 30px;
    font-size: 14px;
    &:first-child {
      margin-top: 10px;
      font-size: 18px;
    }
  }
}
.queryButton {
  display: flex;
  justify-content: flex-end;
  margin-top: 10px;
}
.col-body {
  width: 100%;
  padding: 16px;
  border: solid 1px #e5e5e5;
}
.el-image {
  border-radius: 5px;
  background-color: #ebeef5;
  box-shadow: 0 0 5px 1px #ccc;
  ::v-deep .el-image__inner {
    transition: all 0.3s;
    cursor: pointer;
    &:hover {
      transform: scale(1.2);
    }
  }
  ::v-deep .image-slot {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 100%;
    color: #909399;
    font-size: 30px;
  }
}
.el-icon-upload {
  font-size: 28px;
}
</style>
