<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="emergencyName">
            <el-input
              v-model="queryParams.emergencyName"
              placeholder="请输入应急物资名称"
              clearable
              class="!w-150px" />
          </el-form-item>
          <el-form-item label="证书编号" prop="certNo">
            <el-input
              v-model="queryParams.certNo"
              placeholder="请输入证书编号"
              clearable
              @keyup.enter="handleQuery"
              class="!w-150px" />
          </el-form-item>
          <el-form-item>
            <el-button @click="handleQuery" v-hasPermi="['rq:qhse-emergency-cert:query']">
              <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-cert:create']">
              <Icon icon="ep:plus" class="mr-5px" /> 新增
            </el-button>
            <el-button
              type="success"
              v-hasPermi="['rq:qhse-emergency-cert: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="emergencyName" />
              <zm-table-column label="证书编号" align="center" prop="certNo" />
              <zm-table-column label="检测日期" align="center" prop="certTime" width="140">
                <template #default="scope">
                  <span class="iot-md-date">{{ formatDateCorrectly(scope.row.certTime) }}</span>
                </template>
              </zm-table-column>
              <zm-table-column label="检测单位" align="center" prop="certOrg" />
              <zm-table-column label="有效期" align="center" prop="certExpire" width="140">
                <template #default="scope">
                  <span class="iot-md-date">{{ formatDateCorrectly(scope.row.certExpire) }}</span>
                </template>
              </zm-table-column>

              <zm-table-column label="备注" align="center" prop="remark" 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="140" fixed="right" action>
                <template #default="scope">
                  <el-button
                    link
                    type="primary"
                    v-hasPermi="['rq:qhse-emergency-cert:update']"
                    @click="openForm('update', scope.row.id)">
                    编辑
                  </el-button>
                  <el-button
                    link
                    type="danger"
                    v-hasPermi="['rq:qhse-emergency-cert: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>

  <EmergencyBookForm ref="formRef" @success="getList" />
</template>

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

const { ZmTable, ZmTableColumn } = useTableComponents()

defineOptions({ name: 'QHSEEmergencyBook' })

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,
  certNo: undefined,
  deptId: undefined
})
const queryFormRef = ref()
const exportLoading = ref(false)

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

const formatDateCorrectly = (timestamp) => {
  if (!timestamp) return ''

  // 确保处理各种可能的时间戳格式
  let time = Number(timestamp)

  // 处理不同时间戳格式
  if (time < 10000000000) {
    time = time * 1000
  }

  // 检查是否为有效日期
  const date = new Date(time)
  if (isNaN(date.getTime())) {
    return ''
  }

  // 验证日期合理性（例如：不能是过于久远的日期）
  const minValidYear = 1900
  if (date.getFullYear() < minValidYear) {
    console.warn('Invalid date detected:', timestamp)
    return ''
  }

  return formatDate(time).substring(0, 10)
}

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 EmergencyDrillCertApi.deleteEmergencyDrillCert(id)
    message.success(t('common.delSuccess'))
    await getList()
  } catch {}
}

const handleExport = async () => {
  try {
    await message.exportConfirm()
    exportLoading.value = true
    const data = await EmergencyDrillCertApi.exportEmergencyDrillCert(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)
  }
}

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

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