<template>
  <div class="check-certificate-page">
    <div class="mb-1">
      <el-form
        :model="queryParams"
        ref="queryFormRef"
        class="rounded-lg shadow px-8 py-2 pt-4 flex items-center flex-wrap min-w-0">
        <div class="flex items-center gap-2 flex-wrap">
          <el-form-item label="设备名称" prop="deviceName">
            <el-input
              v-model="queryParams.deviceName"
              placeholder="请输入设备名称"
              clearable
              class="!w-150px" />
          </el-form-item>

          <el-form-item label="检测类型" prop="certType">
            <el-select
              v-model="queryParams.certType"
              placeholder="请选择检测类型"
              clearable
              style="width: 150px">
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.QHSE_DEVICE_CERT_TYPE)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="序列号" prop="certNo">
            <el-input
              v-model="queryParams.certNo"
              placeholder="请输入证书编号"
              clearable
              class="!w-150px" />
          </el-form-item>
          <el-form-item label="检测日期" prop="certTime">
            <el-date-picker
              v-model="queryParams.certTime"
              value-format="YYYY-MM-DD HH:mm:ss"
              type="daterange"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
              class="!w-200px" />
          </el-form-item>
          <el-form-item label="检测单位" prop="certOrg">
            <el-input
              v-model="queryParams.certOrg"
              placeholder="请输入检测单位"
              clearable
              @keyup.enter="handleQuery"
              class="!w-150px" />
          </el-form-item>
          <el-form-item label="有效期" prop="certExpire">
            <el-date-picker
              v-model="queryParams.certExpire"
              value-format="YYYY-MM-DD HH:mm:ss"
              type="daterange"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
              class="!w-200px" />
          </el-form-item>

          <el-form-item>
            <el-button @click="handleQuery" v-hasPermi="['rq:qhse-device-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
              v-hasPermi="['rq:qhse-device-cert:export']"
              type="success"
              plain
              @click="handleExport"
              :loading="exportLoading">
              <Icon icon="ep:download" class="mr-5px" /> 导出
            </el-button>
          </el-form-item>
        </div>
      </el-form>
    </div>

    <div class="shadow rounded-lg flex flex-col p-2 pt-4 min-w-0 cert-table-card">
      <div class="flex-1 relative min-h-0">
        <zm-table
          :loading="loading"
          :data="list"
          :row-style="tableRowStyle"
          :row-class-name="tableRowClassName">
          <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="deviceCode" />
          <zm-table-column label="设备名称" align="center" prop="deviceName" />
          <zm-table-column label="检测类型" align="center" width="100">
            <template #default="scope">
              <dict-tag :type="DICT_TYPE.QHSE_DEVICE_CERT_TYPE" :value="scope.row.certType" />
            </template>
          </zm-table-column>
          <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="deptName" />
          <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>
      </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 class="shadow rounded-lg p-3 min-w-0 flex gap-4 justify-between cert-alerts">
      <div
        class="bg-[#fef0f0] text-[#f57979] px-3 flex-1 flex items-center justify-center text-center py-2 text-sm rounded-md"
        ><el-icon class="stats-card__icon" :size="28"> <Icon icon="ep:info-filled" /> </el-icon
        >应检设备证书已过期红色预警</div
      >
      <div
        class="bg-[#fdf6ec] flex-1 text-[#e6a23c] text-center flex items-center justify-center px-3 py-2 text-sm rounded-md"
        ><el-icon class="stats-card__icon" :size="28"> <Icon icon="ep:bell-filled" /> </el-icon
        >应检设备证书90天橙色预警</div
      >
    </div>
  </div>

  <Dialog v-model="dialogFileView" title="附件" width="500">
    <div
      v-for="(file, index) in fileList"
      :key="index"
      class="flex items-center justify-between mt-5">
      <span class="file-name-text">{{ extractFileName(file) }}</span>
      <div>
        <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>
</template>

<script setup lang="ts">
import download from '@/utils/download'
import { InspectDeviceCertApi } from '@/api/pms/qhse/index'
import { formatDate } from '@/utils/formatTime'

import { useTableComponents } from '@/components/ZmTable/useTableComponents'
const { ZmTable, ZmTableColumn } = useTableComponents()

import { DICT_TYPE, getStrDictOptions } from '@/utils/dict'

/** 应检设备证书 列表 */
defineOptions({ name: 'QHSEDeviceCert' })
const props = defineProps<{
  deviceId?: number
}>()

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,
  deviceId: props.deviceId,
  deviceName: undefined,
  certNo: undefined,
  certOrg: undefined,
  certTime: [],
  certExpire: undefined,
  createTime: [],
  deptId: undefined,
  certType: undefined
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await InspectDeviceCertApi.getInspectDeviceCertList(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

const tableRowStyle = ({ row }) => {
  if (row.expired) {
    return { backgroundColor: '#ffe6e6' }
  }
  if (row.alertWarn) {
    return { backgroundColor: '#e19f1a' }
  }
  return {}
}

const tableRowClassName = ({ row }) => {
  if (row.expired) {
    return 'expired-row'
  }
  if (row.alertWarn) {
    return 'alert-warn-row'
  }
  return ''
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

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 resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await InspectDeviceCertApi.exportInspectDeviceCert(queryParams)
    download.excel(data, '应检设备证书.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

let dialogFileView = ref(false)
let fileList = ref([])
const viewFile = (file) => {
  fileList.value = file.split(',')
  dialogFileView.value = true
  // window.open(file)
}

const viewFileInfo = (file) => {
  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]
    // URL 解码
    return decodeURIComponent(fileName) || url
  } catch {
    // 如果解析失败，返回原始 URL
    return url
  }
}

const handleDownload = async (url) => {
  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() // 自动获取文件名‌:ml-citation{ref="3" data="citationList"}
    link.click()

    URL.revokeObjectURL(downloadUrl)
  } catch (error) {
    console.error('下载失败:', error)
  }
}
/** 初始化 **/
onMounted(() => {
  getList()
})
</script>

<style scoped lang="scss">
.check-certificate-page {
  display: grid;
  gap: 12px;
  min-width: 0;
  background: linear-gradient(180deg, #f8fbff 0, var(--el-bg-color) 96px), var(--el-bg-color);
}

.cert-table-card {
  min-width: 0;
}

.cert-alerts {
  width: 100%;
}

.file-name-text {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  margin-right: 12px;
  color: var(--el-text-color-primary);
}

/* 过期行的红色背景 - 基础状态 */
:deep(.el-table__body tr.expired-row > td.el-table__cell) {
  background-color: #ffe6e6 !important;
}

/* 过期行 - 鼠标悬浮状态 */
:deep(.el-table__body tr.expired-row:hover > td.el-table__cell) {
  background-color: #ffcccc !important;
}

/* 确保斑马纹不影响过期行 */
:deep(.el-table__body tr.expired-row.el-table__row--striped > td.el-table__cell) {
  background-color: #ffe6e6 !important;
}

:deep(.el-table__body tr.expired-row.el-table__row--striped:hover > td.el-table__cell) {
  background-color: #ffcccc !important;
}

/* 预警行的橙色背景 - 基础状态 */
:deep(.el-table__body tr.alert-warn-row > td.el-table__cell) {
  background-color: #fff1df !important;
}

/* 预警行 - 鼠标悬浮状态 */
:deep(.el-table__body tr.alert-warn-row:hover > td.el-table__cell) {
  background-color: #ffe2bf !important;
}

/* 确保斑马纹不影响预警行 */
:deep(.el-table__body tr.alert-warn-row.el-table__row--striped > td.el-table__cell) {
  background-color: #fff1df !important;
}

:deep(.el-table__body tr.alert-warn-row.el-table__row--striped:hover > td.el-table__cell) {
  background-color: #ffe2bf !important;
}
</style>
