<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
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="隐患问题编号" prop="pitfallCode">
        <el-input
          v-model="queryParams.pitfallCode"
          placeholder="请输入隐患问题编号"
          clearable v-no-whitespace
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="隐患问题类别" prop="pitfallTypeId">
        <el-select v-model="queryParams.pitfallTypeId" 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="pitfallLevelId">
        <el-select v-model="queryParams.pitfallLevelId" 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="findTimeRange">
        <el-date-picker
          v-model="queryParams.findTimeRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          clearable
          value-format="yyyy-MM-dd"
          format="yyyy-MM-dd"
        />
      </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-button v-if="userType == '00'" type="text" style="margin-left: 30px; color: #409eff" @click="drawer = true">
          高级筛选
        </el-button>
      </el-form-item>
    </el-form>

    <el-drawer title="高级筛选" :visible.sync="drawer" :direction="direction" size="40%">
      <div class="app-container">
        <el-form v-show="showSearch" :model="queryParams" ref="queryForm" size="small" label-width="110px">
          <el-row :gutter="20">
            <!-- <el-col :span="12" :offset="0">
              <el-form-item label="关键字" prop="keyWord">
                <el-input
                  v-model="queryParams.keyWord"
                  placeholder="请输入关键字"
                  clearable
                  @keyup.enter.native="handleQuery"
                  class="ipt-width"
                />
              </el-form-item>
            </el-col> -->
            <el-col :span="12" :offset="0">
              <el-form-item label="隐患工程" prop="proName">
                <el-input
                  v-model="queryParams.proName"
                  placeholder="请输入隐患工程"
                  clearable v-no-whitespace
                  @keyup.enter.native="handleQuery"
                  class="ipt-width"
                />
              </el-form-item>
            </el-col>

            <el-col :span="12" :offset="0">
              <el-form-item label="隐患问题类别" prop="pitfallTypeId">
                <el-select
                  v-model="queryParams.pitfallTypeId"
                  placeholder="请选择隐患问题类别"
                  clearable
                  class="ipt-width"
                >
                  <el-option
                    v-for="item in pitfallTypeOpts"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12" :offset="0">
              <el-form-item label="隐患问题级别" prop="pitfallLevelId">
                <el-select
                  v-model="queryParams.pitfallLevelId"
                  placeholder="请选择隐患问题级别"
                  clearable
                  class="ipt-width"
                >
                  <el-option
                    v-for="item in pitfallLevelOpts"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="12" :offset="0">
              <el-form-item label="隐患采集来源" prop="isFrom">
                <el-select v-model="queryParams.isFrom" placeholder="请选择隐患采集来源" clearable class="ipt-width">
                  <el-option
                    v-for="item in hazardCollectionSourceOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12" :offset="0">
              <el-form-item label="隐患整改状态" prop="checkStatus">
                <el-select
                  v-model="queryParams.checkStatus"
                  placeholder="请选择隐患整改状态"
                  clearable
                  class="ipt-width"
                >
                  <el-option
                    v-for="item in hazardRectificationStatusOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="12" :offset="0">
              <el-form-item label="整改责任承包商" prop="subName">
                <el-input
                  v-model="queryParams.subName"
                  placeholder="请输入整改责任承包商"
                  clearable v-no-whitespace
                  class="ipt-width"
                />
              </el-form-item>
            </el-col>
            <!-- <el-col :span="12" :offset="0">
              <el-form-item label="承包商负责人" prop="contractorLeader">
                <el-input
                  v-model="queryParams.contractorLeader"
                  placeholder="请输入承包商负责人"
                  clearable
                  class="ipt-width"
                />
              </el-form-item>
            </el-col> -->

            <el-col :span="12" :offset="0">
              <el-form-item label="隐患问题编号" prop="pitfallCode">
                <el-input
                  v-model="queryParams.pitfallCode"
                  placeholder="请输入隐患问题编号"
                  clearable v-no-whitespace
                  class="ipt-width"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12" :offset="0">
              <el-form-item label="创建人" prop="createUserName">
                <el-input v-model="queryParams.createUserName" placeholder="请输入创建人" clearable class="ipt-width" v-no-whitespace />
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="发现日期" prop="findTimeRange">
            <el-date-picker
              v-model="queryParams.findTimeRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              clearable
              value-format="yyyy-MM-dd"
              format="yyyy-MM-dd"
            />
          </el-form-item>
          <el-form-item label="创建日期" prop="createTimeRange">
            <el-date-picker
              v-model="queryParams.createTimeRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              clearable
              value-format="yyyy-MM-dd"
              format="yyyy-MM-dd"
            />
          </el-form-item>
          <el-form-item label="审批状态" prop="checkState">
            <el-select v-model="queryParams.checkState" 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>
      </div>
    </el-drawer>

    <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%">
      <!-- 多选 -->
      <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>
      </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
            v-if="userType == '00' && scope.row.isCheck == '1'"
            type="text"
            size="mini"
            style="color: #f56c6c"
            @click="handleRectify(scope.row, 6)"
          >
            验收
          </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 {
  getHiddenDangerRectificationApprovalList,
  getHiddenDangerRectificationList,
  getTypeOfViolationSelect,
  exportHiddenDangerRectificationList,
  exportHiddenDangerRectificationApprovalList,
} from '@/api/hiddenDangerManagement'

export default {
  data() {
    return {
      userId: this.$store.state.user.id, // 用户id
      proId: this.$store.state.user.thisIds.proId, // 工程id
      userType: this.$store.state.user.userType, // 用户类型
      showSearch: true,
      drawer: false,
      direction: 'rtl', // 抽屉方向-右侧
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        keyWord: '', // 关键字
        pitfallCode: '', // 隐患问题编号
        pitfallTypeId: '', // 隐患问题类别
        pitfallLevelId: '', // 隐患问题级别
        isFrom: '', // 隐患采集来源
        checkStatus: '', // 隐患整改状态
        subName: '', // 整改责任承包商
        contractorLeader: '', // 承包商负责人
        proName: '', // 隐患工程
        createUserName: '', // 创建人
        findTimeRange: [], // 发现时间范围
        createTimeRange: [], // 创建日期
        checkState: '', // 审批状态
      },
      // 隐患问题类别-下拉
      pitfallTypeOpts: [],
      // 隐患问题级别-下拉
      pitfallLevelOpts: [],
      // 隐患采集来源-下拉
      hazardCollectionSourceOptions: [],
      // 隐患整改状态-下拉
      hazardRectificationStatusOptions: [],
      // 审批状态-下拉
      approvalStatusOptions: [],
      total: 0, // 总条数
      // 表头
      tableColumns: [
        { label: '隐患问题编号', prop: 'pitfallCode' },
        { label: '隐患工程', prop: 'proName' },
        { label: '整改责任承包商', prop: 'subName' },
        { label: '隐患问题类别', prop: 'pitfallTypeName' },
        { label: '隐患问题级别', prop: 'pitfallLevelName' },
        { label: '隐患采集来源', prop: 'isFrom' },
        { label: '发现时间', prop: 'findTime' },
        { label: '隐患整改状态', prop: 'checkStatus' },
        { label: '创建时间', prop: 'createTime' },
        { label: '创建人', prop: 'createUserName' },
        { label: '审批状态', prop: 'checkState' },
      ],
      // 表格数据
      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 = this.tableColumns.filter(item => item.prop !== 'proName' && item.prop !== 'subName')
    }
    this.getList()
    this.getTroubleType()
    this.getTroubleLevel()
    this.getStatus()
  },
  methods: {
    updateStatus(status) {
      return this.approvalStatusOpts.find(item => item.value === status)?.label
    },
    // 状态-下拉
    getStatus() {
      try {
        const params = {
          dictType: 'sys_approval_state',
          dictValue: '',
        }
        dictTableOption(params).then(res => {
          console.log('🚀 ~ 审批状态 ~ res:', res)
          this.approvalStatusOptions = res.data
        })
        // yn_check_status
        const params2 = {
          dictType: 'yn_check_status',
          dictValue: '',
        }
        dictTableOption(params2).then(res => {
          console.log('🚀 ~ 整改状态 ~ res:', res)
          this.hazardRectificationStatusOptions = res.data
        })
        // yn_collection_source
        const params3 = {
          dictType: 'yn_collection_source',
          dictValue: '',
        }
        dictTableOption(params3).then(res => {
          console.log('🚀 ~ 隐患采集来源 ~ res:', res)
          this.hazardCollectionSourceOptions = res.data
        })
      } catch (error) {
        console.log('获取状态-下拉失败', error)
      }
    },
    // 隐患问题类别-下拉
    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.queryParams.pageNum = 1
      this.queryParams.pageSize = 10
      this.$refs.queryForm.resetFields()
      this.getList()
    },
    // 获取列表
    async getList() {
      try {
        let startTime = ''
        let endTime = ''
        let createStartTime = ''
        let createEndTime = ''
        if (this.queryParams.findTimeRange && this.queryParams.findTimeRange.length > 0) {
          startTime = this.queryParams.findTimeRange[0]
          endTime = this.queryParams.findTimeRange[1]
        } else {
          startTime = ''
          endTime = ''
        }
        if (this.queryParams.createTimeRange && this.queryParams.createTimeRange.length > 0) {
          createStartTime = this.queryParams.createTimeRange[0]
          createEndTime = this.queryParams.createTimeRange[1]
        } else {
          createStartTime = ''
          createEndTime = ''
        }
        let params = {
          ...this.queryParams,
          startTime,
          endTime,
          createStartTime,
          createEndTime,
          typeId: 1, // 1-验收 2-审批
          userId: this.userId,
        }
        delete params.findTimeRange
        delete params.createTimeRange
        let res = {}
        if (this.userType == '02') {
          params.proId = this.proId
          res = await getHiddenDangerRectificationList(params)
        } else {
          res = await getHiddenDangerRectificationApprovalList(params)
        }
        console.log('🚀 ~ getList ~ res:', res)
        this.tableList = res.rows
        this.total = res.total || 0
      } 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 isAcceptance = 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 = '审批记录'
      } else if (type === 5) {
        title = '工程隐患详情'
      } else if (type === 6) {
        isAcceptance = true
        title = '隐患整改验收'
      }
      this.$router.push({
        path: '/hiddenDangerManagement/hazardRectificationManagement/components/hazardApprove',
        query: {
          ...row,
          title,
          isApprove,
          isRectify,
          isDelay,
          isRecord,
          isAcceptance,
          active,
        },
      })
    },
    // 撤回
    handleRevocation(row) {
      console.log('撤回', row)
      // 弹框
      this.$confirm('是否确认撤回?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        // 撤回操作
      })
    },
    // 开关
    changeSwitch(row) {
      console.log('开关', row)
    },
    // 导出数据
    handleExport() {
      try {
        let fileName = ''
        let url = ''
        if (this.userType == '02') {
          fileName = `隐患整改列表_${new Date().getTime()}.xLsx`
          url = exportHiddenDangerRectificationList()
        } else {
          fileName = `隐患整改验收列表_${new Date().getTime()}.xLsx`
          url = exportHiddenDangerRectificationApprovalList()
        }
        let startTime = ''
        let endTime = ''
        let createStartTime = ''
        let createEndTime = ''
        if (this.queryParams.findTimeRange && this.queryParams.findTimeRange.length > 0) {
          startTime = this.queryParams.findTimeRange[0]
          endTime = this.queryParams.findTimeRange[1]
        } else {
          startTime = ''
          endTime = ''
        }
        if (this.queryParams.createTimeRange && this.queryParams.createTimeRange.length > 0) {
          createStartTime = this.queryParams.createTimeRange[0]
          createEndTime = this.queryParams.createTimeRange[1]
        } else {
          createStartTime = ''
          createEndTime = ''
        }
        const params = {
          ...this.queryParams,
          startTime,
          endTime,
          createStartTime,
          createEndTime,
          proId: this.proId,
          typeId: 1, // 1-验收 2-审批
          userId: this.userId,
        }
        delete params.findTimeRange
        delete params.createTimeRange
        this.derive(url, params, fileName)
      } catch (error) {
        console.log('导出数据失败', error)
      }
    },
  },
}
</script>

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