<template>
  <div
    class="grid grid-cols-[auto_1fr] grid-rows-[auto_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-4"
      :top-id="rootDeptId"
      :deptId="deptId"
      v-model="queryParams.deptId"
      :init-select="false"
      :show-title="false"
      request-api="getSimpleDeptList"
      @node-click="handleDeptNodeClick" />

    <div class="stats-cards">
      <div
        class="stats-card stats-card--expired stats-card--clickable"
        @click="handleStatCardClick('expired')">
        <div class="flex items-center gap-2">
          <Icon icon="ep:info-filled" color="#de3b3b" />
          <div class="stats-card__label">已过期</div>
        </div>

        <div class="stats-card__value">
          <CountTo
            :duration="2600"
            :end-val="expired"
            :start-val="0"
            class="stats-card__value text-[40px]! pt-10 text-center! text-[#e35656]!" />
        </div>
      </div>
      <div
        class="stats-card stats-card--warn stats-card--clickable"
        @click="handleStatCardClick('warn')">
        <div class="flex items-center gap-2">
          <Icon icon="ep:bell-filled" color="#d97706" />
          <div class="stats-card__label">90天预警(含过期)</div>
        </div>
        <div class="stats-card__value">
          <CountTo
            :duration="2600"
            :end-val="warn"
            :start-val="0"
            class="stats-card__value text-[40px]! pt-10 text-center! text-[#d97706]!" />
        </div>
      </div>
      <div
        class="stats-card stats-card--total stats-card--clickable"
        @click="handleStatCardClick('total')">
        <div class="flex items-center gap-2">
          <Icon icon="eos-icons:counting" color="#2563eb" />
          <div class="stats-card__label">证书总数</div>
        </div>

        <div class="stats-card__value">
          <CountTo
            :duration="2600"
            :end-val="totalCert"
            :start-val="0"
            class="stats-card__value text-[40px]! pt-10 text-center! text-[#2563eb]!" />
        </div>
      </div>
    </div>

    <el-form
      :model="queryParams"
      ref="queryFormRef"
      class="bg-white dark:bg-[#1d1e1f] 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:create']"
            type="primary"
            plain
            @click="openForm('create')">
            <Icon icon="ep:plus" 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 class="bg-white dark:bg-[#1d1e1f] shadow rounded-lg flex flex-col mt-1 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"
              :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-column label="操作" align="center" width="140" fixed="right" action>
                <template #default="scope">
                  <el-button
                    link
                    v-hasPermi="['rq:qhse-device-cert:update']"
                    type="primary"
                    @click="openForm('update', scope.row.id)">
                    编辑
                  </el-button>
                  <el-button
                    v-hasPermi="['rq:qhse-device-cert:delete']"
                    link
                    type="danger"
                    @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
      class="bg-white dark:bg-[#1d1e1f] shadow rounded-lg p-3 mt-1 min-w-0 flex gap-4 justify-between">
      <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="附件">
    <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>

  <!-- 表单弹窗：添加/修改 -->
  <DeviceCertForm ref="formRef" @success="getList" />
</template>

<script setup lang="ts">
import download from '@/utils/download'
import { InspectDeviceCertApi } from '@/api/pms/qhse/index'
import DeviceCertForm from './DeviceCertForm.vue'
import { formatDate } from '@/utils/formatTime'
import DeptTreeSelect from '@/components/DeptTreeSelect/index.vue'
import { useTableComponents } from '@/components/ZmTable/useTableComponents'
const { ZmTable, ZmTableColumn } = useTableComponents()
import { useUserStore } from '@/store/modules/user'
import { DICT_TYPE, getStrDictOptions } from '@/utils/dict'

/** 应检设备证书 列表 */
defineOptions({ name: 'QHSEDeviceCert' })
const userStore = useUserStore()
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,
  deviceId: undefined,
  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 handleStatCardClick = (type: 'expired' | 'warn' | 'total') => {
  queryParams.pageNo = 1

  if (type === 'expired') {
    queryParams.expired = true
    queryParams.alertWarn = undefined
    queryParams.type = undefined
    getList()
    return
  }

  if (type === 'warn') {
    queryParams.alertWarn = true
    queryParams.expired = undefined
    queryParams.type = undefined
    getList()
    return
  }

  queryParams.type = undefined
  queryParams.expired = undefined
  queryParams.alertWarn = undefined
  getList()
}

const selectedDept = ref<{ id: number; name: string }>()

const handleDeptNodeClick = async (row) => {
  selectedDept.value = { id: row.id, name: row.name }
  queryParams.deptId = row.id
  await getList()
  await getStatic()
}

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 handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await InspectDeviceCertApi.deleteInspectDeviceCert(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
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)
  }
}

let totalCert = ref(0)
let expired = ref(0)
let warn = ref(0)

async function getStatic() {
  if (queryParams.deptId) {
    const res = await InspectDeviceCertApi.getInspectDeviceCertStat(queryParams.deptId)
    totalCert.value = res.total
    expired.value = res.expired
    warn.value = res.warn
  } else {
    const res = await InspectDeviceCertApi.getInspectDeviceCertStat(userStore.user.deptId)
    totalCert.value = res.total
    expired.value = res.expired
    warn.value = res.warn
  }
}
/** 初始化 **/
onMounted(() => {
  getList()
  getStatic()
})
</script>

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

.stats-cards {
  display: grid;
  grid-template-columns: repeat(3, minmax(0, 1fr));
  gap: 12px;
  margin-bottom: 5px;
}

.stats-card {
  padding: 14px 16px;
  background: linear-gradient(180deg, #ffffff 0%, #f7faff 100%);
  border: 1px solid #e4ecf7;
  border-radius: 10px;
  box-shadow: 0 4px 12px rgb(31 91 184 / 8%);
}

.stats-card--clickable {
  cursor: pointer;
  transition:
    transform 0.18s ease,
    box-shadow 0.18s ease,
    border-color 0.18s ease;
}

.stats-card--clickable:hover {
  transform: translateY(-2px);
  box-shadow: 0 10px 24px rgb(31 91 184 / 14%);
}

.stats-card__label {
  font-size: 14px;
  font-weight: 600;
  color: #6b7280;
  line-height: 1.4;
}

.stats-card__value {
  margin-top: 8px;
  font-size: 28px;
  font-weight: 700;
  line-height: 1;
  color: #1f5bb8;
}

.stats-card--expired {
  background: linear-gradient(180deg, #fff4f4 0%, #ffe8e8 100%);
  border-color: #ffcfcf;
}

.stats-card--expired .stats-card__value {
  color: #de3b3b;
}

.stats-card--warn {
  background: linear-gradient(180deg, #fff8ef 0%, #ffeed9 100%);
  border-color: #ffd7a1;
}

.stats-card--warn .stats-card__value {
  color: #d97706;
}

.stats-card--total .stats-card__value {
  color: #2563eb;
}

.stats-card--personal .stats-card__value {
  color: #16a34a;
}

.stats-card--organization .stats-card__value {
  color: #7c3aed;
}

/* 过期行的红色背景 - 基础状态 */
: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>
