<template>
  <div ref="containerRef" class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="档案状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择档案状态" clearable style="width: 240px">
          <el-option v-for="dict in archive_status" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间" style="width: 308px">
        <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:tbusihazardarchive:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate" v-hasPermi="['hazard:tbusihazardarchive:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete" v-hasPermi="['hazard:tbusihazardarchive:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['hazard:tbusihazardarchive:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :columns="columns" storageKey="hazard-tbusihazardarchive-index"></right-toolbar>
    </el-row>

    <div class="table-wrapper">
    <el-table :height="tableHeight" v-loading="loading" :data="archiveList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="档案状态" align="center" prop="status" v-if="columns.status.visible">
        <template #default="scope">
          <dict-tag :options="archive_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="创建人" align="center" prop="createPer" v-if="columns.createPer.visible" />
      <el-table-column label="创建时间" align="center" prop="createTime" v-if="columns.createTime.visible" width="180" />
      <el-table-column label="更新时间" align="center" prop="updateTime" v-if="columns.updateTime.visible" width="180" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="240">
        <template #default="scope">
          <el-tooltip content="提交归档" placement="top" v-if="scope.row.status === '0'">
            <el-button link type="primary" icon="Top" @click="handleSubmitArchive(scope.row)">提交</el-button>
          </el-tooltip>
          <el-tooltip content="审核通过" placement="top" v-if="scope.row.status === '1'">
            <el-button link type="success" icon="Check" @click="handleApprove(scope.row)">通过</el-button>
          </el-tooltip>
          <el-tooltip content="审核退回" placement="top" v-if="scope.row.status === '1'">
            <el-button link type="danger" icon="Close" @click="handleReject(scope.row)">退回</el-button>
          </el-tooltip>
          <el-tooltip content="修改" placement="top" v-if="scope.row.status === '0'">
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['hazard:tbusihazardarchive: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" v-if="scope.row.status === '0'">
            <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['hazard:tbusihazardarchive: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="archiveRef" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="危险源辨识" prop="hazIdenGuid">
              <el-select v-model="form.hazIdenGuid" placeholder="请选择危险源辨识" filterable>
                <el-option v-for="item in idenOptions" :key="item.guid" :label="item.hazRemark" :value="item.guid" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="档案状态" prop="status">
              <el-select v-model="form.status" placeholder="请选择档案状态">
                <el-option v-for="dict in archive_status" :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="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" 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>

    <!-- 档案详情对话框 -->
    <el-dialog title="档案详情" v-model="detailOpen" width="600px" append-to-body>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="档案状态">
          <dict-tag :options="archive_status" :value="detailRow.status" />
        </el-descriptions-item>
        <el-descriptions-item label="创建人">{{ detailRow.createPer }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ detailRow.createTime }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ detailRow.updateTime }}</el-descriptions-item>
        <el-descriptions-item label="退回原因" :span="2" v-if="detailRow.status === '3'">{{ detailRow.remark }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <el-button @click="detailOpen = false">关 闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="TBusiHazardArchive">
import { listTBusiHazardArchive, getTBusiHazardArchive, delTBusiHazardArchive, addTBusiHazardArchive, updateTBusiHazardArchive } from "@/api/slaj/hazard"
import { useTableHeight } from '@/hooks/useTableHeight'
import { listTBusiHazIden } from "@/api/slaj/hazard"

const { tableHeight, containerRef } = useTableHeight()

const { proxy } = getCurrentInstance()
const { archive_status } = proxy.useDict("archive_status")

const archiveList = ref([])
const idenOptions = 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 detailOpen = ref(false)
const detailRow = ref({})

const columns = ref({
  status: { label: '档案状态', visible: true },
  createPer: { label: '创建人', visible: true },
  createTime: { label: '创建时间', visible: true },
  updateTime: { label: '更新时间', visible: true }
})

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    status: undefined
  },
  rules: {
    hazIdenGuid: [{ required: true, message: "危险源辨识不能为空", trigger: "change" }],
    status: [{ required: true, message: "档案状态不能为空", trigger: "change" }]
  }
})

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

/** 查询档案列表 */
function getList() {
  loading.value = true
  listTBusiHazardArchive(proxy.addDateRange(queryParams.value, dateRange.value)).then(res => {
    loading.value = false
    archiveList.value = res.rows
    total.value = res.total
  })
}

/** 查询危险源辨识下拉选项 */
function getIdenOptions() {
  listTBusiHazIden({ pageNum: 1, pageSize: 1000 }).then(res => {
    idenOptions.value = res.rows
  })
}

/** 搜索按钮操作 */
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) {
  reset()
  const guid = row.guid || ids.value
  getTBusiHazardArchive(guid).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改档案"
  })
}

/** 提交归档 */
function handleSubmitArchive(row) {
  proxy.$modal.confirm('确认提交档案编号为"' + row.guid + '"的审核？').then(function () {
    return updateTBusiHazardArchive({ guid: row.guid, status: '1' })
  }).then(() => {
    proxy.$modal.msgSuccess("提交成功，等待审核")
    getList()
  }).catch(() => {})
}

/** 审核通过 */
function handleApprove(row) {
  proxy.$modal.confirm('确认审核通过该档案？').then(function () {
    return updateTBusiHazardArchive({ guid: row.guid, status: '2' })
  }).then(() => {
    proxy.$modal.msgSuccess("审核通过")
    getList()
  }).catch(() => {})
}

/** 审核退回 */
function handleReject(row) {
  proxy.$modal.prompt("请输入退回原因", "审核退回", {
    confirmButtonText: "确认退回",
    cancelButtonText: "取消",
    inputPattern: /.+/,
    inputErrorMessage: "退回原因不能为空"
  }).then(({ value }) => {
    return updateTBusiHazardArchive({ guid: row.guid, status: '3', remark: value })
  }).then(() => {
    proxy.$modal.msgSuccess("已退回")
    getList()
  }).catch(() => {})
}

/** 详情按钮操作 */
function handleDetail(row) {
  detailRow.value = row
  detailOpen.value = true
}

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

/** 删除按钮操作 */
function handleDelete(row) {
  const guids = row.guid || ids.value
  proxy.$modal.confirm('是否确认删除档案编号为"' + guids + '"的数据项？').then(function () {
    return delTBusiHazardArchive(guids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

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

/** 重置表单 */
function reset() {
  form.value = {
    guid: undefined,
    hazIdenGuid: undefined,
    orgGuid: undefined,
    status: '0',
    wiunGuid: undefined,
    remark: undefined,
    createPer: undefined,
    updatePer: undefined,
    createTime: undefined,
    updateTime: undefined
  }
  proxy.resetForm("archiveRef")
}

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