<template>
  <div ref="containerRef" class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="70px" class="compact-form">
      <el-form-item label="工程类别" prop="engType">
        <el-select v-model="queryParams.engType" placeholder="请选择" clearable style="width: 130px">
          <el-option v-for="dict in eng_type" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="单位名称" prop="orgName">
        <el-input v-model="queryParams.orgName" placeholder="请输入" clearable style="width: 130px" @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="单位性质" prop="orgNature">
        <el-select v-model="queryParams.orgNature" placeholder="请选择" clearable style="width: 130px">
          <el-option v-for="dict in org_nature" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="督办状态" prop="supStat">
        <el-select v-model="queryParams.supStat" placeholder="请选择" clearable style="width: 130px">
          <el-option v-for="dict in sup_stat" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="隐患类别" prop="hiddClas">
        <el-select v-model="queryParams.hiddClas" placeholder="请选择" clearable style="width: 130px">
          <el-option v-for="dict in hidd_clas" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="整改情况" prop="hiddStat">
        <el-select v-model="queryParams.hiddStat" placeholder="请选择" clearable style="width: 130px">
          <el-option v-for="dict in hidd_stat" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['hidd:majhiddsup:export']">导出</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :columns="columns" storageKey="hidd-majhiddsup-index"></right-toolbar>
    </el-row>

    <div class="table-wrapper">
    <el-table :height="tableHeight" v-loading="loading" :data="supList" @selection-change="handleSelectionChange">
      <el-table-column label="序号" align="center" type="index" width="60" />
      <el-table-column label="隐患所属单位" align="center" prop="orgName" v-if="columns.orgName.visible" :show-overflow-tooltip="true" min-width="120" />
      <el-table-column label="隐患级别" align="center" prop="hiddGrad" v-if="columns.hiddGrad.visible" min-width="80">
        <template #default="scope">
          <dict-tag :options="hidd_grad" :value="scope.row.hiddGrad" />
        </template>
      </el-table-column>
      <el-table-column label="隐患名称" align="center" prop="hiddName" v-if="columns.hiddName.visible" :show-overflow-tooltip="true" min-width="150">
        <template #default="scope">
          <el-link type="primary" @click="handleDetail(scope.row)">{{ scope.row.hiddName }}</el-link>
        </template>
      </el-table-column>
      <el-table-column label="发现日期" align="center" prop="collTime" v-if="columns.collTime.visible" min-width="100">
        <template #default="scope">
          {{ formatDate(scope.row.collTime) }}
        </template>
      </el-table-column>
      <el-table-column label="督办情况" align="center" prop="supStat" v-if="columns.supStat.visible" min-width="80">
        <template #default="scope">
          <dict-tag :options="sup_stat" :value="scope.row.supStat" />
        </template>
      </el-table-column>
      <el-table-column label="整改情况" align="center" prop="hiddStat" v-if="columns.hiddStat.visible" min-width="80">
        <template #default="scope">
          <dict-tag :options="hidd_stat" :value="scope.row.hiddStat" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" min-width="150">
        <template #default="scope">
          <el-button link type="primary" v-if="scope.row.supStat === '0' && scope.row.hiddStat !== '2'" @click="handleSup(scope.row)" v-hasPermi="['hidd:majhiddsup:add']">督办</el-button>
          <el-button link type="primary" v-if="scope.row.supStat === '2'" @click="handleWriteOff(scope.row)" v-hasPermi="['hidd:majhiddsup:edit']">销号</el-button>
          <el-button link type="primary" @click="handleDetail(scope.row)">详情</el-button>
        </template>
      </el-table-column>
    </el-table>
    </div>

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

    <el-dialog title="隐患督办" v-model="supOpen" width="700px" append-to-body>
      <el-form :model="supForm" :rules="supRules" ref="supRef" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="隐患名称">
              <el-input v-model="supForm.hiddName" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="隐患级别">
              <el-select v-model="supForm.hiddGrad" disabled style="width: 100%">
                <el-option v-for="dict in hidd_grad" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="隐患部位">
              <el-input v-model="supForm.proPart" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属工程">
              <el-input v-model="supForm.engName" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="督办文号" prop="supLareId">
              <el-input v-model="supForm.supLareId" placeholder="请输入督办文号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="督办日期">
              <el-date-picker v-model="supForm.supDate" type="date" value-format="YYYY-MM-DD" placeholder="请选择督办日期" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="督办单位">
              <el-input v-model="supForm.supWiunName" placeholder="请输入督办单位" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="整改期限" prop="rectPeri">
              <el-date-picker v-model="supForm.rectPeri" type="date" value-format="YYYY-MM-DD" placeholder="请选择整改期限" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="是否挂牌督办">
              <el-radio-group v-model="supForm.isList">
                <el-radio value="1">是</el-radio>
                <el-radio value="0">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="督办意见" prop="supOpin">
              <el-input v-model="supForm.supOpin" type="textarea" :rows="4" placeholder="请输入督办意见" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="督办附件">
              <span style="color: #f56c6c; margin-right: 5px;">*</span>
              <el-upload
                ref="upload"
                :action="uploadUrl"
                :headers="uploadHeaders"
                :on-success="handleUploadSuccess"
                :on-remove="handleUploadRemove"
                :file-list="fileList"
                :limit="1"
              >
                <el-button type="primary" size="small">选择附件</el-button>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitSup">确 定</el-button>
          <el-button @click="supOpen = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog title="详情" v-model="detailOpen" width="800px" append-to-body>
      <div style="margin-bottom: 16px;">
        <div class="detail-section-header">隐患信息</div>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="隐患名称" :span="2">{{ detailForm.hiddName }}</el-descriptions-item>
          <el-descriptions-item label="隐患级别">
            <dict-tag :options="hidd_grad" :value="detailForm.hiddGrad" />
          </el-descriptions-item>
          <el-descriptions-item label="隐患部位">{{ detailForm.proPart }}</el-descriptions-item>
          <el-descriptions-item label="所属工程">{{ detailForm.engName }}</el-descriptions-item>
          <el-descriptions-item label="督办文号">{{ detailForm.supLareId }}</el-descriptions-item>
          <el-descriptions-item label="督办日期">{{ detailForm.supDate }}</el-descriptions-item>
          <el-descriptions-item label="督办单位">{{ detailForm.supWiunName }}</el-descriptions-item>
          <el-descriptions-item label="整改期限">{{ detailForm.rectPeri }}</el-descriptions-item>
          <el-descriptions-item label="是否挂牌督办">
            {{ detailForm.isList === '1' ? '是' : '否' }}
          </el-descriptions-item>
          <el-descriptions-item label="督办意见" :span="2">{{ detailForm.supOpin }}</el-descriptions-item>
          <el-descriptions-item label="督办附件" :span="2">
            <div v-if="detailForm.medGuid">
              <el-link type="primary" :href="`/common/download?fileName=${detailForm.medTitl}&delete=true`">
                <el-icon><Download /></el-icon>
                {{ detailForm.medTitl || '附件' }}
              </el-link>
            </div>
            <span v-else style="color: #909399">暂无附件</span>
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <div>
        <div class="detail-section-header">销号信息</div>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="治理完成日期">{{ detailForm.requCompDate }}</el-descriptions-item>
          <el-descriptions-item label="验收时间">{{ detailForm.accepDate }}</el-descriptions-item>
          <el-descriptions-item label="验收意见" :span="2">{{ detailForm.accepOpin }}</el-descriptions-item>
          <el-descriptions-item label="备注" :span="2">{{ detailForm.note }}</el-descriptions-item>
        </el-descriptions>
      </div>
      <template #footer>
        <el-button @click="detailOpen = false">关 闭</el-button>
      </template>
    </el-dialog>

    <el-dialog title="销号确认" v-model="writeOffOpen" width="400px" append-to-body align-center class="write-off-dialog">
      <div style="text-align: center; padding: 20px; display: flex; align-items: center; justify-content: center; gap: 8px;">
        <el-icon style="font-size: 24px; color: #e6a23c;"><WarningFilled /></el-icon>
        <span style="font-size: 16px;">确认对该隐患进行销号操作？</span>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitWriteOff">确 定</el-button>
          <el-button @click="writeOffOpen = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog title="撤销督办确认" v-model="cancelOpen" width="400px" append-to-body>
      <div style="text-align: center; padding: 20px;">
        <el-icon style="font-size: 48px; color: #f56c6c;"><WarningFilled /></el-icon>
        <p style="margin-top: 16px; font-size: 16px;">确认撤销对该隐患的督办？</p>
        <p style="color: #909399; font-size: 14px;">撤销后可重新进行督办</p>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="danger" @click="submitCancel">确 定</el-button>
          <el-button @click="cancelOpen = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="BisMajHiddSup">
import { listBisMajHiddSup, getBisMajHiddSup, addBisMajHiddSup, updateBisMajHiddSup, delBisMajHiddSup, writeOffBisMajHiddSup, cancelBisMajHiddSup, listBisHiddRectAcce } from "@/api/slaj/hidd"
import { useTableHeight } from '@/hooks/useTableHeight'
import { listObjHidd, getObjHidd } from "@/api/slaj/hidd"

const { tableHeight, containerRef } = useTableHeight()

import useUserStore from '@/store/modules/user'

const userStore = useUserStore()
const token = computed(() => userStore.token)

const uploadUrl = ref('/common/upload')
const uploadHeaders = computed(() => ({ Authorization: 'Bearer ' + token.value }))
const fileList = ref([])

const { proxy } = getCurrentInstance()
const { hidd_grad, hidd_stat, sup_stat, hidd_clas, eng_type, org_nature } = proxy.useDict("hidd_grad", "hidd_stat", "sup_stat", "hidd_clas", "eng_type", "org_nature")

const supList = ref([])
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const dateRange = ref([])

const supOpen = ref(false)
const supForm = ref({})
const supRules = {
  supOpin: [{ required: true, message: "督办意见不能为空", trigger: "blur" }],
  supLareId: [{ required: true, message: "文号不能为空", trigger: "blur" }],
  rectPeri: [{ required: true, message: "请选择督办期限", trigger: "change" }]
}

const writeOffOpen = ref(false)
const writeOffRow = ref({})

const cancelOpen = ref(false)
const cancelRow = ref({})

const detailOpen = ref(false)
const detailForm = ref({})

const columns = ref({
  orgName: { label: '隐患所属单位', visible: true },
  hiddGrad: { label: '隐患级别', visible: true },
  hiddName: { label: '隐患名称', visible: true },
  collTime: { label: '发现日期', visible: true },
  supStat: { label: '督办情况', visible: true },
  hiddStat: { label: '整改情况', visible: true }
})

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    engType: undefined,
    orgName: undefined,
    orgNature: undefined,
    supStat: undefined,
    hiddClas: undefined,
    hiddStat: undefined
  },
  rules: {}
})

const { queryParams, form, rules } = toRefs(data)

function getList() {
  loading.value = true
  listBisMajHiddSup(proxy.addDateRange(queryParams.value, dateRange.value)).then(res => {
    loading.value = false
    supList.value = res.rows
    total.value = res.total
  })
}

function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

function resetQuery() {
  dateRange.value = []
  proxy.resetForm("queryRef")
  handleQuery()
}

function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.guid)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

function handleSup(row) {
  supForm.value = {
    hiddGuid: row.guid,
    hiddName: row.hiddName,
    hiddGrad: row.hiddGrad,
    proPart: row.proPart || '',
    engName: row.engName || '',
    supDate: '',
    supWiunName: row.supWiunName || '',
    supWiunCode: row.supWiunCode || '',
    supOpin: undefined,
    supLareId: undefined,
    rectPeri: undefined,
    isList: '0',
    medGuid: undefined,
    medTitl: undefined
  }
  fileList.value = []
  supOpen.value = true
}

function submitSup() {
  proxy.$refs["supRef"].validate(valid => {
    if (valid) {
      const submitData = {
        ...supForm.value,
        medGuid: supForm.value.medGuid || (fileList.value.length > 0 ? fileList.value[0].response ? fileList.value[0].response.msg : '' : ''),
        medTitl: supForm.value.medTitl || (fileList.value.length > 0 ? fileList.value[0].name : '')
      }
      addBisMajHiddSup(submitData).then(response => {
        proxy.$modal.msgSuccess("督办成功")
        supOpen.value = false
        getList()
      })
    }
  })
}

function handleUploadSuccess(response, file, fileList) {
  if (response.code === 200) {
    supForm.value.medGuid = response.msg
    supForm.value.medTitl = file.name
  }
}

function handleUploadRemove(file, fileList) {
  supForm.value.medGuid = undefined
  supForm.value.medTitl = undefined
}

function handleDetail(row) {
  const guid = row.guid || ids.value
  getBisMajHiddSup(guid).then(response => {
    const supData = response.data
    const hiddGuid = supData.hiddGuid
    if (hiddGuid) {
      listBisHiddRectAcce({ hiddGuid: hiddGuid }).then(acceRes => {
        const acceData = (acceRes.rows && acceRes.rows.length > 0) ? acceRes.rows[0] : {}
        detailForm.value = { ...supData, ...acceData }
      }).catch(() => {
        detailForm.value = supData
      })
    } else {
      detailForm.value = supData
    }
    detailOpen.value = true
  })
}

function handleWriteOff(row) {
  writeOffRow.value = row
  writeOffOpen.value = true
}

function submitWriteOff() {
  writeOffBisMajHiddSup({ guid: writeOffRow.value.guid }).then(response => {
    proxy.$modal.msgSuccess("销号成功")
    writeOffOpen.value = false
    getList()
  }).catch(() => {})
}

function handleCancel(row) {
  cancelRow.value = row
  cancelOpen.value = true
}

function submitCancel() {
  cancelBisMajHiddSup(cancelRow.value.guid).then(response => {
    proxy.$modal.msgSuccess("撤销督办成功")
    cancelOpen.value = false
    getList()
  }).catch(() => {})
}

function handleExport() {
  proxy.download("hidd/majhiddsup/export", {
    ...queryParams.value
  }, `majHiddSup_${new Date().getTime()}.xlsx`)
}

function formatDate(dateStr) {
  if (!dateStr) return ''
  return dateStr.substring(0, 10)
}

onMounted(() => {
  getList()
})
</script>

<style scoped>
.compact-form :deep(.el-form-item) {
  margin-bottom: 10px;
  margin-right: 5px;
}
.compact-form :deep(.el-form-item__label) {
  padding-right: 4px;
}
.detail-section-header {
  font-size: 14px;
  font-weight: bold;
  margin-bottom: 12px;
  padding-left: 8px;
  border-left: 3px solid #409eff;
}
</style>

<style>
.write-off-dialog {
  margin-top: 0 !important;
}
</style>
