<template>
  <div class="app-container">
    <el-form v-show="showSearch" :model="queryParams" ref="queryForm" size="small" inline>
      <el-form-item label="关键字" prop="keyWord">
        <el-input
          v-model="queryParams.keyWord"
          placeholder="请输入关键字"
          clearable
          v-no-whitespace
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="隐患问题编号" prop="hazardQuestionCode">
        <el-input
          v-model="queryParams.hazardQuestionCode"
          placeholder="请输入隐患问题编号"
          clearable
          v-no-whitespace
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="隐患问题类别" prop="hazardIssueCategories">
        <el-select v-model="queryParams.hazardIssueCategories" placeholder="请选择隐患问题类别" clearable>
          <el-option v-for="item in pitfallTypeOpts" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="隐患问题级别" prop="hazardIssueLevel">
        <el-select v-model="queryParams.hazardIssueLevel" placeholder="请选择隐患问题级别" clearable>
          <el-option v-for="item in pitfallLevelOpts" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="审批状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择审批状态" clearable>
          <el-option v-for="item in approvalStatusOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item style="display: flex; justify-content: flex-end">
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">查询</el-button>
        <el-button icon="el-icon-refresh" @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport">导出数据</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table :data="tableList" fit highlight-current-row style="width: 100%" border>
      <!-- 多选 -->
      <el-table-column type="selection" width="55" align="center" @selection-change="selectionChange" />
      <el-table-column
        type="index"
        width="55"
        label="序号"
        align="center"
        :index="indexContinuous(queryParams.pageNum, queryParams.pageSize)"
      />
      <el-table-column
        v-for="(column, index) in tableColumns"
        show-overflow-tooltip
        :key="column.prop"
        :label="column.label"
        :prop="column.prop"
        align="center"
      >
        <template v-slot="scope" v-if="column.prop == 'intoStatus'">
          <span>{{ updateStatus(scope.row.intoStatus) }}</span>
        </template>
        <template v-slot="scope" v-else-if="column.prop == 'isDelayCheck' && userType == '02'">
          <span v-if="scope.row.isDelayCheck == 0">未申请</span>
          <span v-else-if="scope.row.isDelayCheck == 1">申请中</span>
          <span v-else-if="scope.row.isDelayCheck == 2">已申请</span>
        </template>
      </el-table-column>
      <!-- 操作 -->
      <el-table-column label="操作" align="center" width="150">
        <template slot-scope="scope">
          <el-button type="text" size="mini" @click="handleRectify(scope.row, 5)">查看</el-button>
          <el-button
            type="text"
            size="mini"
            style="color: #f56c6c"
            @click="handleRectify(scope.row, 1)"
            v-if="scope.row.intoStatus == '1'"
          >
            审批
          </el-button>
          <el-button
            v-if="userType == '02' && scope.row.isDelayCheck == '1'"
            type="text"
            size="mini"
            style="color: #f56c6c"
            @click="handleDelayRevocation(scope.row)"
          >
            延期撤回
          </el-button>
          <el-button type="text" size="mini" style="color: #e6a23c" @click="handleRectify(scope.row, 4)">
            审批记录
          </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"
    />
  </div>
</template>

<script>
import { dictTableOption } from '@/api/tool/select'
import { encryptCBC } from '@/utils/aescbc'
import {
  getReviewOfDeferredApprovalList,
  getTypeOfViolationSelect,
  withdrawalOfExtension,
} from '@/api/hiddenDangerManagement'
import { retractApproval } from '@/api/terminalEquipment/deviceInformation'

export default {
  data() {
    return {
      userType: this.$store.state.user.userType, // 用户类型
      showSearch: true,
      queryParams: {
        proId: this.$store.state.user.thisIds.proId,
        pageNum: 1,
        pageSize: 10,
        keyWord: '', // 关键字
        hazardQuestionCode: '', // 隐患问题编号
        hazardIssueCategories: '', // 隐患问题类别
        hazardIssueLevel: '', // 隐患问题级别
        status: '', // 审批状态
      },
      // 隐患问题类别-下拉
      pitfallTypeOpts: [],
      // 隐患问题级别-下拉
      pitfallLevelOpts: [],
      // 审批状态-下拉
      approvalStatusOptions: [],
      total: 0, // 总条数
      // 表头
      tableColumns: [
        { label: '隐患问题编号', prop: 'pitfallCode' },
        { label: '隐患问题类别', prop: 'pitfallTypeName' },
        { label: '隐患问题级别', prop: 'pitfallLevelName' },
        { label: '隐患工程', prop: 'proName' },
        { label: '整改责任承包商', prop: 'subName' },
        { label: '期限整改时间', prop: 'correctionTime' },
        { label: '延期日期', prop: 'delayTime' },
        { label: '延期原因', prop: 'delayReason' },
        { label: '审批状态', prop: 'intoStatus' },
        { label: '审批驳回原因', prop: 'delayRejectReason' },
        { label: '延期驳回原因', prop: 'rejectionDelay' },
      ],
      // 表格数据
      tableList: [],
      approvalStatusOpts: [
        { label: '未提交', value: '0' },
        { label: '待审批', value: '1' },
        { label: '审批中', value: '2' },
        { label: '已审批', value: '3' },
        { label: '已驳回', value: '4' },
        { label: '已撤回', value: '5' },
      ],
    }
  },
  created() {
    if (this.userType == '02') {
      this.tableColumns.splice(9, 0, { label: '延期状态', prop: 'isDelayCheck' })
    }
    this.getList()
    this.getTroubleType()
    this.getTroubleLevel()
    this.getStatus()
  },
  methods: {
    updateStatus(status) {
      return this.approvalStatusOpts.find(item => item.value === status)?.label
    },
    // 审批状态-下拉
    getStatus() {
      const params = {
        dictType: 'sys_approval_state',
        dictValue: '',
      }
      dictTableOption(params).then(response => {
        console.log('🚀 ~ 审批状态 ~ response:', response)
        this.approvalStatusOptions = response.data
      })
    },
    // 隐患问题类别-下拉
    async getTroubleType() {
      try {
        const res = await getTypeOfViolationSelect({ type: '1' })
        this.pitfallTypeOpts = res.data
      } catch (error) {
        console.log('获取隐患问题类别-下拉失败', error)
      }
    },
    // 隐患问题级别-yn_trouble_level
    async getTroubleLevel() {
      try {
        const params = {
          dictType: 'yn_trouble_level',
          dictValue: '',
        }
        const res = await dictTableOption(params)
        this.pitfallLevelOpts = res.data
      } catch (error) {
        console.log('获取隐患问题级别-下拉失败', error)
      }
    },
    // 查询
    handleQuery() {
      console.log('查询', this.queryParams)
      this.getList()
    },
    // 重置
    handleReset() {
      console.log('重置')
      this.$refs.queryForm.resetFields()
      this.getList()
    },
    // 获取列表
    async getList() {
      try {
        this.tableList = []
        console.log('this.queryParams', this.queryParams)
        this.queryParams.proId = this.$store.state.user.thisIds.proId
        getReviewOfDeferredApprovalList(this.queryParams).then(res => {
          console.log('🚀 ~ getReviewOfDeferredApprovalList ~ res:', res)
          this.tableList = res.rows
          this.total = res.total
        })
      } catch (error) {}
    },
    // 多选
    selectionChange(val) {
      console.log('selectionChange', val)
    },
    // 整改回传单
    handleRectify(row, type) {
      console.log('🚀 ~ 隐患整改单', row)
      let isApprove = false
      let isRectify = false
      let isDelay = false
      let isRecord = false
      let isDetail = false
      let active = '1'
      let title = '整改回传'
      if (type === 1) {
        isApprove = true
        title = '隐患整改审批'
      } else if (type === 2) {
        isRectify = true
        title = '整改回传'
      } else if (type === 3) {
        isDelay = true
        title = '延期申请'
      } else if (type === 4) {
        isRecord = true
        active = '2'
        title = '审批记录'
        this.$router.push(
          '/flow/auditRecord/' +
            encryptCBC(
              JSON.stringify({
                taskId: row.taskId,
              })
            )
        )
        return
      } else if (type === 5) {
        isDetail = true
        title = '隐患整改详情'
      }
      this.$router.push({
        path: '/hiddenDangerManagement/hazardRectificationManagement/components/hazardApprove',
        query: {
          ...row,
          title,
          isApprove,
          isRectify,
          isDelay,
          isRecord,
          active,
          isDetail,
        },
      })
    },
    // 撤回
    handleRevocation(row) {
      console.log('撤回', row)
      // 弹框
      this.$confirm('是否确认撤回?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        // 撤回操作
      })
    },
    handleDelayRevocation(row) {
      console.log('延期撤回', row)
      // const taskId = row.taskId
      // const param = {
      //   taskId: taskId,
      //   uuid: row.id,
      //   procInstId: row.procInsId,
      //   taskType: '17',
      // }
      // console.log('param=' + JSON.stringify(param))
      this.$modal
        .confirm('是否撤回此延期申请？')
        .then(function () {
          return withdrawalOfExtension(row.id)
        })
        .then(() => {
          this.getList()
          this.$modal.msgSuccess('撤回成功！')
        })
        .catch(() => {})
    },
    // 开关
    changeSwitch(row) {
      console.log('开关', row)
    },
    // 导出数据
    handleExport() {
      try {
        let fileName = `延期申请列表_${new Date().getTime()}.xLsx`
        let url = '/project/securityCheck/deferredApprovalViewExport'
        const params = { ...this.queryParams }
        this.derive(url, params, fileName)
      } catch (error) {
        console.log('导出数据失败', error)
      }
    },
  },
}
</script>

<style lang="scss" scoped>
.ipt-width {
  width: 220px;
}
</style>
