<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="mb-1">
      <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-4 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="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>

    <div class="min-w-0"></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"
              :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="deviceName" />
              <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 min-w-0 mt-2">
      <el-alert title="应检设备证书已过期红色预警" type="error" show-icon :closable="false">
        <template #icon>
          <Bell />
        </template>
      </el-alert>
      <el-alert
        title="应检设备证书90天橙色预警"
        type="warning"
        show-icon
        :closable="false"
        style="margin-top: 5px">
        <template #icon>
          <Bell />
        </template>
      </el-alert>
    </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>

  <!-- 表单弹窗：添加/修改 -->
  <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'

/** 应检设备证书 列表 */
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
})
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 selectedDept = ref<{ id: number; name: string }>()

const handleDeptNodeClick = async (row) => {
  selectedDept.value = { id: row.id, name: row.name }
  queryParams.deptId = row.id
  await 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 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)
  }
}
/** 初始化 **/
onMounted(() => {
  getList()
})
</script>

<style scoped>
.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>
