<template>
  <div ref="containerRef" class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="auto">
      <el-form-item label="危险源名称" prop="hazName">
        <el-input v-model="queryParams.hazName" placeholder="请输入危险源名称" clearable style="width: 180px" @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="所属单位" prop="orgGuid">
        <el-input v-model="queryParams.orgGuid" placeholder="请输入所属单位" clearable style="width: 180px" @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="所属工程" prop="engGuid">
        <el-input v-model="queryParams.engGuid" placeholder="请输入所属工程" clearable style="width: 180px" @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="危险源等级" prop="hiddGrad">
        <el-select v-model="queryParams.hiddGrad" placeholder="请选择危险源等级" clearable style="width: 150px">
          <el-option v-for="dict in haz_grad" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="危险源状态" prop="hazStat">
        <el-select v-model="queryParams.hazStat" placeholder="请选择危险源状态" clearable style="width: 150px">
          <el-option v-for="dict in haz_stat" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="风险等级" prop="riskGrad">
        <el-select v-model="queryParams.riskGrad" placeholder="请选择风险等级" clearable style="width: 150px">
          <el-option v-for="dict in risk_grad" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="采集时间">
        <el-date-picker v-model="dateRange" value-format="YYYY-MM-DD" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['hazard:objhaz:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate" v-hasPermi="['hazard:objhaz:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete" v-hasPermi="['hazard:objhaz:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Top" :disabled="multiple" @click="handleBatchSubmit" v-hasPermi="['hazard:objhaz:edit']">批量报送</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['hazard:objhaz:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :columns="columns" storageKey="hazard-objhaz-index"></right-toolbar>
    </el-row>

    <div class="table-wrapper">
    <el-table :height="tableHeight" v-loading="loading" :data="objHazList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="危险源编码" align="center" prop="hazCode" v-if="columns.hazCode.visible" :show-overflow-tooltip="true" />
      <el-table-column label="危险源名称" align="center" prop="hazName" v-if="columns.hazName.visible" :show-overflow-tooltip="true" />
      <el-table-column label="危险源等级" align="center" prop="hiddGrad" v-if="columns.hiddGrad.visible">
        <template #default="scope">
          <dict-tag :options="haz_grad" :value="scope.row.hiddGrad" />
        </template>
      </el-table-column>
      <el-table-column label="风险等级" align="center" prop="riskGrad" v-if="columns.riskGrad.visible">
        <template #default="scope">
          <dict-tag :options="risk_grad" :value="scope.row.riskGrad" />
        </template>
      </el-table-column>
      <el-table-column label="涉及部位" align="center" prop="proPart" v-if="columns.proPart.visible" :show-overflow-tooltip="true" />
      <el-table-column label="责任人" align="center" prop="supPers" v-if="columns.supPers.visible" />
      <el-table-column label="巡查人员" align="center" prop="patPers" v-if="columns.patPers.visible" />
      <el-table-column label="危险源状态" align="center" prop="hazStat" v-if="columns.hazStat.visible">
        <template #default="scope">
          <dict-tag :options="haz_stat" :value="scope.row.hazStat" />
        </template>
      </el-table-column>
      <el-table-column label="是否管控" align="center" prop="ifControl" v-if="columns.ifControl.visible">
        <template #default="scope">
          <dict-tag :options="sys_yes_no" :value="scope.row.ifControl" />
        </template>
      </el-table-column>
      <el-table-column label="类型" align="center" prop="type" v-if="columns.type.visible" />
      <el-table-column label="采集时间" align="center" prop="collTime" v-if="columns.collTime.visible" width="180" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="320">
        <template #default="scope">
          <el-tooltip content="报送" placement="top" v-if="scope.row.hazStat === '0'">
            <el-button link type="primary" icon="Top" @click="handleSubmit(scope.row)" v-hasPermi="['hazard:objhaz:edit']">报送</el-button>
          </el-tooltip>
          <el-tooltip content="监管" placement="top" v-if="scope.row.hazStat === '1'">
            <el-button link type="warning" icon="User" @click="handleSupervise(scope.row)" v-hasPermi="['hazard:objhaz:edit']">监管</el-button>
          </el-tooltip>
          <el-tooltip content="备案" placement="top" v-if="scope.row.hazStat === '0' || scope.row.hazStat === '1'">
            <el-button link type="primary" icon="Edit" @click="handleRegister(scope.row)" v-hasPermi="['hazard:bishazmajregwrit:add']"></el-button>
          </el-tooltip>
          <el-tooltip content="核销" placement="top" v-if="scope.row.hazStat === '2' || scope.row.hazStat === '3'">
            <el-button link type="primary" icon="CircleCheck" @click="handleWriteOff(scope.row)" v-hasPermi="['hazard:bishazmajregwrit:add']"></el-button>
          </el-tooltip>
          <el-tooltip content="修改" placement="top">
            <el-button link type="primary" icon="Edit" :disabled="scope.row.hazStat !== '0'" @click="handleUpdate(scope.row)" v-hasPermi="['hazard:objhaz:edit']"></el-button>
          </el-tooltip>
          <el-tooltip content="详情" placement="top">
            <el-button link type="primary" icon="View" @click="handleDetail(scope.row)"></el-button>
          </el-tooltip>
          <el-tooltip content="删除" placement="top">
            <el-button link type="primary" icon="Delete" :disabled="scope.row.hazStat !== '0'" @click="handleDelete(scope.row)" v-hasPermi="['hazard:objhaz:remove']"></el-button>
          </el-tooltip>
        </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="title" v-model="open" width="800px" append-to-body>
      <el-form :model="form" :rules="rules" ref="objHazRef" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="危险源编码" prop="hazCode">
              <el-input v-model="form.hazCode" placeholder="请输入危险源编码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="危险源名称" prop="hazName">
              <el-input v-model="form.hazName" placeholder="请输入危险源名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="危险源等级" prop="hiddGrad">
              <el-select v-model="form.hiddGrad" placeholder="请选择危险源等级">
                <el-option v-for="dict in haz_grad" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="风险等级" prop="riskGrad">
              <el-select v-model="form.riskGrad" placeholder="请选择风险等级">
                <el-option v-for="dict in risk_grad" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="涉及部位" prop="proPart">
              <el-input v-model="form.proPart" placeholder="请输入涉及部位" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="危险源状态" prop="hazStat">
              <el-select v-model="form.hazStat" placeholder="请选择危险源状态">
                <el-option v-for="dict in haz_stat" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="部位经度" prop="partLong">
              <el-input v-model="form.partLong" placeholder="请输入部位经度" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="部位纬度" prop="partLat">
              <el-input v-model="form.partLat" placeholder="请输入部位纬度" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="责任人" prop="supPers">
              <el-input v-model="form.supPers" placeholder="请输入责任人" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="巡查人员" prop="patPers">
              <el-input v-model="form.patPers" placeholder="请输入巡查人员" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="是否管控" prop="ifControl">
              <el-select v-model="form.ifControl" placeholder="请选择是否管控">
                <el-option v-for="dict in sys_yes_no" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="类型" prop="type">
              <el-input v-model="form.type" placeholder="请输入类型" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="危害风险" prop="harmRisk">
              <el-input v-model="form.harmRisk" type="textarea" placeholder="请输入危害风险" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="危险源描述" prop="otlcolQgwNbokgir">
              <el-input v-model="form.otlcolQgwNbokgir" type="textarea" placeholder="请输入危险源描述" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="note">
              <el-input v-model="form.note" type="textarea" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="ObjHaz">
import { listObjHaz, getObjHaz, delObjHaz, addObjHaz, updateObjHaz } from "@/api/slaj/hazard"
import { useTableHeight } from '@/hooks/useTableHeight'

const { tableHeight, containerRef } = useTableHeight()

const { proxy } = getCurrentInstance()
const { haz_grad, haz_stat, risk_grad, sys_yes_no } = proxy.useDict("haz_grad", "haz_stat", "risk_grad", "sys_yes_no")

const objHazList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const dateRange = ref([])

const columns = ref({
  hazCode: { label: '危险源编码', visible: true },
  hazName: { label: '危险源名称', visible: true },
  hiddGrad: { label: '危险源等级', visible: true },
  riskGrad: { label: '风险等级', visible: true },
  proPart: { label: '涉及部位', visible: true },
  supPers: { label: '责任人', visible: true },
  patPers: { label: '巡查人员', visible: true },
  hazStat: { label: '危险源状态', visible: true },
  ifControl: { label: '是否管控', visible: true },
  type: { label: '类型', visible: true },
  collTime: { label: '采集时间', visible: true }
})

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    hazName: undefined,
    hiddGrad: undefined,
    hazStat: undefined,
    riskGrad: undefined,
    orgGuid: undefined,
    engGuid: undefined
  },
  rules: {
    hazName: [{ required: true, message: "危险源名称不能为空", trigger: "blur" }],
    hiddGrad: [{ required: true, message: "危险源等级不能为空", trigger: "change" }],
    hazStat: [{ required: true, message: "危险源状态不能为空", trigger: "change" }]
  }
})

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

/** 查询危险源列表 */
function getList() {
  loading.value = true
  listObjHaz(proxy.addDateRange(queryParams.value, dateRange.value)).then(res => {
    loading.value = false
    objHazList.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 handleAdd() {
  reset()
  open.value = true
  title.value = "添加危险源"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  const guid = row.guid || ids.value
  if (row.hazStat && row.hazStat !== '0') {
    proxy.$modal.msgWarning("已报送的危险源不可修改")
    return
  }
  reset()
  getObjHaz(guid).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改危险源"
  })
}

/** 报送按钮操作 - 将危险源状态改为已报送 */
function handleSubmit(row) {
  if (row.hazStat && row.hazStat !== '0') {
    proxy.$modal.msgWarning("该危险源已报送，无需重复操作")
    return
  }
  const guid = row.guid
  proxy.$modal.confirm('确认报送危险源"' + row.hazName + '"到上级单位？报送后不可修改和删除。').then(function () {
    return updateObjHaz({ guid: guid, hazStat: '1' })
  }).then(() => {
    proxy.$modal.msgSuccess("报送成功")
    getList()
  }).catch(() => {})
}

/** 批量报送操作 */
function handleBatchSubmit() {
  if (!ids.value.length) {
    proxy.$modal.msgWarning("请选择要报送的危险源")
    return
  }
  proxy.$modal.confirm('确认批量报送选中的危险源到上级单位？').then(function () {
    const filtered = ids.value.filter(id => {
      const row = objHazList.value.find(r => r.guid === id)
      return row && (row.hazStat === '0' || !row.hazStat)
    })
    if (!filtered.length) {
      proxy.$modal.msgWarning("选中的危险源均已报送，无需重复操作")
      return Promise.reject()
    }
    const promises = filtered.map(guid => updateObjHaz({ guid: guid, hazStat: '1' }))
    return Promise.all(promises)
  }).then(() => {
    proxy.$modal.msgSuccess("批量报送成功")
    getList()
  }).catch(() => {})
}

/** 监管按钮操作 - 跳转到监管页面 */
function handleSupervise(row) {
  proxy.$router.push({ path: '/slaj/hazard/supervise', query: { hazGuid: row.guid } })
}

/** 详情按钮操作 */
function handleDetail(row) {
  const guid = row.guid || ids.value
  proxy.$router.push({ path: '/slaj/hazard/detail', query: { guid: guid } })
}

/** 备案按钮操作 */
function handleRegister(row) {
  proxy.$router.push({ path: '/slaj/hazard/register', query: { hazGuid: row.guid } })
}

/** 核销按钮操作 */
function handleWriteOff(row) {
  proxy.$router.push({ path: '/slaj/hazard/writeOff', query: { hazGuid: row.guid } })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["objHazRef"].validate(valid => {
    if (valid) {
      if (form.value.guid != undefined) {
        updateObjHaz(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addObjHaz(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const guids = row.guid || ids.value
  if (row.hazStat && row.hazStat !== '0') {
    proxy.$modal.msgWarning("已报送的危险源不可删除")
    return
  }
  proxy.$modal.confirm('是否确认删除危险源编号为"' + guids + '"的数据项？').then(function () {
    return delObjHaz(guids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

function cancel() {
  open.value = false
  reset()
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download("hazard/objhaz/export", {
    ...queryParams.value
  }, `objHaz_${new Date().getTime()}.xlsx`)
}

/** 重置表单 */
function reset() {
  form.value = {
    guid: undefined,
    hazCode: undefined,
    hazName: undefined,
    orgGuid: undefined,
    engGuid: undefined,
    tendGuid: undefined,
    hiddGrad: undefined,
    proPart: undefined,
    partLong: undefined,
    partLat: undefined,
    harmRisk: undefined,
    moniPrec: undefined,
    offiTel: undefined,
    patPers: undefined,
    supPers: undefined,
    ifLiceNoti: undefined,
    note: undefined,
    collTime: undefined,
    updTime: undefined,
    recPers: undefined,
    supPersDept: undefined,
    safePrec: undefined,
    emerPrec: undefined,
    riskGrad: undefined,
    monitorMeans: undefined,
    monitorMeasure: undefined,
    riskGuid: undefined,
    organizingPrec: undefined,
    techniquePrec: undefined,
    systemPrec: undefined,
    toDate: undefined,
    otlcolQgwNbokgir: undefined,
    writCollTime: undefined,
    orgPers: undefined,
    orgpersTel: undefined,
    onsitePers: undefined,
    onsitepersTel: undefined,
    hazStat: undefined,
    supTime: undefined,
    supOrg: undefined,
    regTime: undefined,
    ifControl: undefined,
    major: undefined,
    project: undefined,
    type: undefined,
    regOrgGuid: undefined
  }
  proxy.resetForm("objHazRef")
}

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