<template>
  <div
    class="grid grid-cols-[auto_1fr] grid-rows-[auto_minmax(0,1fr)] gap-0 gap-x-4 h-[calc(100vh-20px-var(--top-tool-height)-var(--tags-view-height)-var(--app-footer-height))]">
    <DeptTreeSelect
      class="row-span-2"
      :top-id="rootDeptId"
      :deptId="deptId"
      v-model="queryParams.deptId"
      :init-select="false"
      :show-title="false"
      request-api="getSimpleDeptList"
      @node-click="handleDeptNodeClick" />

    <div class="mb-1">
      <el-form
        :model="queryParams"
        ref="queryFormRef"
        class="bg-white dark:bg-[#1d1e1f] rounded-lg shadow px-8 pt-4 flex items-center flex-wrap min-w-0">
        <div class="flex items-center gap-4 flex-wrap">
          <el-form-item label="应急物资名称" prop="emergencyCode">
            <el-input
              v-model="queryParams.emergencyCode"
              placeholder="请输入物资编号"
              clearable
              class="!w-150px" />
          </el-form-item>
          <el-form-item label="应急物资名称" prop="emergencyName">
            <el-input
              v-model="queryParams.emergencyName"
              placeholder="请输入物资名称"
              clearable
              class="!w-120px" />
          </el-form-item>
          <el-form-item label="责任人" prop="dutyPerson">
            <el-input
              v-model="queryParams.dutyPerson"
              placeholder="请输入责任人"
              clearable
              @keyup.enter="handleQuery"
              class="!w-120px" />
          </el-form-item>
          <el-form-item>
            <el-button @click="handleQuery">
              <Icon icon="ep:search" class="mr-5px" /> 搜索
            </el-button>
            <el-button @click="resetQuery">
              <Icon icon="ep:refresh" class="mr-5px" /> 重置
            </el-button>
            <el-button
              type="primary"
              plain
              @click="openForm('create')"
              v-hasPermi="['rq:qhse-emergency-book:create']">
              <Icon icon="ep:plus" class="mr-5px" /> 新增
            </el-button>
            <el-button
              type="success"
              v-hasPermi="['rq:qhse-emergency-book:export']"
              plain
              @click="handleExport"
              :loading="exportLoading">
              <Icon icon="ep:download" class="mr-5px" /> 导出
            </el-button>
          </el-form-item>
        </div>
      </el-form>
    </div>

    <div class="bg-white dark:bg-[#1d1e1f] shadow rounded-lg flex flex-col p-2 pt-4 min-w-0">
      <div class="flex-1 relative min-h-0">
        <el-auto-resizer class="absolute">
          <template #default="{ width, height }">
            <zm-table
              :loading="loading"
              :data="list"
              :width="width"
              :height="height"
              :max-height="height">
              <zm-table-column :label="t('monitor.serial')" width="70" align="center">
                <template #default="scope">
                  {{ scope.$index + 1 }}
                </template>
              </zm-table-column>
              <zm-table-column label="应急物资编号" align="center" prop="emergencyCode" />
              <zm-table-column
                label="应急物资名称"
                align="center"
                prop="emergencyName"
                min-width="140" />
              <zm-table-column
                label="应急物资单位"
                align="center"
                prop="emergencyUnit"
                min-width="120" />
              <zm-table-column label="数量" align="center" prop="emergencyNumber" width="90" />
              <zm-table-column
                label="存放位置"
                align="center"
                prop="emergencyLocation"
                min-width="140" />
              <zm-table-column label="责任人" align="center" prop="dutyPerson" width="100" />
              <zm-table-column label="联系电话" align="center" prop="mobile" min-width="120" />
              <!-- <zm-table-column label="部门名称" align="center" prop="deptName" min-width="140" /> -->
              <zm-table-column
                label="备注"
                align="center"
                prop="remark"
                min-width="160"
                show-overflow-tooltip />
              <zm-table-column label="附件" align="center" prop="file" min-width="90">
                <template #default="scope">
                  <el-button
                    v-if="scope.row.file"
                    link
                    type="primary"
                    @click="viewFile(scope.row.file)">
                    查看
                  </el-button>
                </template>
              </zm-table-column>
              <zm-table-column label="操作" align="center" width="160" fixed="right" action>
                <template #default="scope">
                  <el-button
                    v-hasPermi="['rq:qhse-emergency-book:update']"
                    link
                    type="primary"
                    @click="openCertDrawer(scope.row.id, scope.row.emergencyName)">
                    查看证书
                  </el-button>
                  <el-button
                    v-hasPermi="['rq:qhse-emergency-book:update']"
                    link
                    type="primary"
                    @click="openForm('update', scope.row.id)">
                    编辑
                  </el-button>
                  <el-button
                    link
                    type="danger"
                    v-hasPermi="['rq:qhse-emergency-book:delete']"
                    @click="handleDelete(scope.row.id)">
                    删除
                  </el-button>
                </template>
              </zm-table-column>
            </zm-table>
          </template>
        </el-auto-resizer>
      </div>
      <div class="h-8 mt-2 flex items-center justify-end">
        <Pagination
          :total="total"
          v-model:page="queryParams.pageNo"
          v-model:limit="queryParams.pageSize"
          @pagination="getList" />
      </div>
    </div>
  </div>

  <Dialog v-model="dialogFileView" title="附件">
    <div
      v-for="(file, index) in fileList"
      :key="index"
      class="mt-5 flex min-w-0 items-center justify-between gap-5">
      <span class="file-name-text flex-1 min-w-0">{{ extractFileName(file) }}</span>
      <div class="flex shrink-0 items-center gap-5 flex-nowrap">
        <el-button link type="primary" @click="viewFileInfo(file)">
          <Icon icon="ep:view" class="mr-2px" />查看
        </el-button>
        <el-button link type="primary" @click="handleDownload(file)">
          <Icon icon="ep:download" class="mr-2px" />下载
        </el-button>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer mt-10">
        <el-button type="primary" @click="dialogFileView = false">确认</el-button>
      </div>
    </template>
  </Dialog>

  <EmergencyDrillForm ref="formRef" @success="getList" />
  <CertDrawer ref="certDrawerRef" />
</template>

<script setup lang="ts">
import download from '@/utils/download'
import { EmergencyDrillApi } from '@/api/pms/qhse/index'
import EmergencyDrillForm from './EmergencyDrillForm.vue'
import CertDrawer from './CertDrawer.vue'
import DeptTreeSelect from '@/components/DeptTreeSelect/index.vue'
import { useTableComponents } from '@/components/ZmTable/useTableComponents'
import { useUserStore } from '@/store/modules/user'

const { ZmTable, ZmTableColumn } = useTableComponents()

defineOptions({ name: 'QHSEEmergencyDrill' })

const rootDeptId = 156
const deptId = useUserStore().getUser.deptId || rootDeptId

const message = useMessage()
const { t } = useI18n()

const loading = ref(true)
const list = ref<any[]>([])
const total = ref(0)
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  emergencyName: undefined,
  emergencyCode: undefined,
  dutyPerson: undefined,
  deptId: undefined
})
const queryFormRef = ref()
const exportLoading = ref(false)

const getList = async () => {
  loading.value = true
  try {
    const data = await EmergencyDrillApi.getEmergencyDrillList(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

const handleDeptNodeClick = async (row) => {
  queryParams.deptId = row.id
  await getList()
}

const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

const handleDelete = async (id: number) => {
  try {
    await message.delConfirm()
    await EmergencyDrillApi.deleteEmergencyDrill(id)
    message.success(t('common.delSuccess'))
    await getList()
  } catch {}
}

const handleExport = async () => {
  try {
    await message.exportConfirm()
    exportLoading.value = true
    const data = await EmergencyDrillApi.exportEmergencyDrill(queryParams)
    download.excel(data, '应急物资台账.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

const dialogFileView = ref(false)
const fileList = ref<string[]>([])

const viewFile = (file: string) => {
  fileList.value = file.split(',')
  dialogFileView.value = true
}

const viewFileInfo = (file: string) => {
  window.open(
    'http://doc.deepoil.cc:8012/onlinePreview?url=' + encodeURIComponent(Base64.encode(file))
  )
}

const extractFileName = (url: string): string => {
  try {
    const cleanUrl = url.split('?')[0].split('#')[0]
    const parts = cleanUrl.split('/')
    const fileName = parts[parts.length - 1]
    return decodeURIComponent(fileName) || url
  } catch {
    return url
  }
}

const handleDownload = async (url: string) => {
  try {
    const response = await fetch(url)
    const blob = await response.blob()
    const downloadUrl = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = downloadUrl
    link.download = url.split('/').pop() || 'file'
    link.click()
    URL.revokeObjectURL(downloadUrl)
  } catch (error) {
    console.error('下载失败:', error)
  }
}

const certDrawerRef = ref()

const openCertDrawer = (emergencyId: number, emergencyName: string) => {
  certDrawerRef.value?.open(emergencyId, emergencyName)
}
onMounted(async () => {
  getList()
})
</script>

<style scoped>
.file-name-text {
  display: block;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>
