<template>
  <div
    class="qhse-page grid grid-cols-[auto_1fr] grid-rows-[auto_auto_minmax(0,1fr)_auto] gap-3 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 min-w-0">
      <div
        class="stats-card stats-card--expired stats-card--clickable"
        @click="handleStatCardClick('expired')">
        <div class="stats-card__header">
          <el-icon class="stats-card__icon" :size="28">
            <Icon icon="ep:info-filled" />
          </el-icon>
          <div class="stats-card__label">已过期</div>
        </div>
        <div class="stats-card__value text-[40px]! pt-10 text-center!">
          <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="stats-card__header">
          <el-icon class="stats-card__icon" :size="28">
            <Icon icon="ep:bell-filled" />
          </el-icon>
          <div class="stats-card__label">90天预警(含过期)</div>
        </div>
        <div class="stats-card__value text-[40px]! pt-10 text-center!">
          <CountTo
            :duration="2600"
            :end-val="warn"
            :start-val="0"
            class="stats-card__value text-[40px]! pt-10 text-center! text-[#df8a28]!" />
        </div>
      </div>
      <div class="stats-chart-card">
        <div class="stats-card__label">分类统计</div>
        <div ref="staticChartRef" class="stats-chart"></div>
      </div>
    </div>
    <el-form
      ref="queryFormRef"
      :model="queryParams"
      size="small"
      label-width="auto"
      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-1 flex-wrap">
        <el-form-item label="计量器具名称" prop="measureName">
          <el-input
            v-model="queryParams.measureName"
            placeholder="请输入计量器具名称"
            clearable
            @keyup.enter="handleQuery"
            class="!w-120px" />
        </el-form-item>
        <el-form-item label="编码" prop="measureCode">
          <el-input
            v-model="queryParams.measureCode"
            placeholder="请输入计量器具编码"
            clearable
            @keyup.enter="handleQuery"
            class="!w-120px" />
        </el-form-item>
        <el-form-item label="是否过期" prop="expired">
          <el-select
            v-model="queryParams.expired"
            placeholder="请选择是否过期"
            clearable
            class="!w-120px">
            <el-option
              v-for="dict in getBoolDictOptions(DICT_TYPE.INFRA_BOOLEAN_STRING)"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="是否预警" prop="alertWarn">
          <el-select
            v-model="queryParams.alertWarn"
            placeholder="请选择是否预警"
            clearable
            class="!w-120px">
            <el-option
              v-for="dict in getBoolDictOptions(DICT_TYPE.INFRA_BOOLEAN_STRING)"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button @click="handleQuery">
            <Icon icon="ep:search" class="mr-5px" /> {{ t('devicePerson.search') }}
          </el-button>
          <el-button @click="resetQuery">
            <Icon icon="ep:refresh" class="mr-5px" /> {{ t('devicePerson.reset') }}
          </el-button>
          <el-button @click="handleAdd" type="primary">
            <Icon icon="ep:plus" class="mr-5px" />新增
          </el-button>
          <el-button @click="handleExport" type="success" plain :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 p-2 pt-3 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"
              :show-overflow-tooltip="true"
              :row-style="tableRowStyle"
              :row-class-name="tableRowClassName">
              <zm-table-column :label="t('monitor.serial')" width="70" align="center" fixed="left">
                <template #default="scope">
                  {{ scope.$index + 1 }}
                </template>
              </zm-table-column>
              <zm-table-column label="名称" align="center" prop="measureName" fixed="left" />
              <zm-table-column label="编码" align="center" prop="measureCode" fixed="left" />
              <zm-table-column label="序列号" align="center" prop="serialNo" fixed="left" />
              <zm-table-column label="部门名称" align="center" prop="deptName" />
              <zm-table-column label="精度" align="center" prop="measureUnit" />
              <zm-table-column label="责任人" align="center" prop="dutyPerson" />
              <zm-table-column label="品牌" align="center" prop="brand" />
              <zm-table-column label="规格型号" align="center" prop="modelName" />
              <zm-table-column label="分类" align="center" prop="classify" min-width="120px">
                <template #default="scope">
                  <dict-tag :type="DICT_TYPE.MEASURE_TYPE" :value="scope.row.classify" />
                </template>
              </zm-table-column>
              <zm-table-column label="状态" align="center" prop="status" min-width="100">
                <template #default="scope">
                  <dict-tag :type="DICT_TYPE.MEASURE_STATUS" :value="scope.row.status" />
                </template>
              </zm-table-column>
              <zm-table-column label="报废时间" align="center" prop="offTime" min-width="120">
                <template #default="scope">
                  {{ formatDateCorrectly(scope.row.offTime) }}
                </template>
              </zm-table-column>
              <zm-table-column label="采购日期" align="center" prop="buyDate">
                <template #default="scope">
                  {{ formatDateCorrectly(scope.row.buyDate) }}
                </template>
              </zm-table-column>
              <zm-table-column label="价格" align="center" prop="measurePrice">
                <template #default="scope">
                  {{ scope.row.measurePrice }}
                </template>
              </zm-table-column>
              <zm-table-column label="备注" align="center" prop="remark" />
              <!-- <zm-table-column label="检测信息" align="center" fixed="right">
                <template #default="scope">
                  <el-button link type="primary" @click="handleView(scope.row.id)">
                    查看
                  </el-button>
                </template>
              </zm-table-column> -->
              <zm-table-column
                :label="t('devicePerson.operation')"
                align="center"
                fixed="right"
                action
                min-width="180px">
                <template #default="scope">
                  <el-button link type="primary" @click="viewCert(scope.row)">查看证书</el-button>
                  <el-button link type="primary" @click="handleEdit(scope.row)"> 编辑 </el-button>
                  <el-button 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 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] flex items-center justify-center text-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 :title="dialogTitle" v-model="dialogVisible" destroy-on-close @close="closeDialog">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      v-loading="formLoading"
      label-width="auto">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="计量器具名称" prop="measureName">
            <el-input v-model="formData.measureName" placeholder="请输入计量器具名称" />
          </el-form-item>
        </el-col>
        <!-- <el-col :span="12">
          <el-form-item label="责任人" prop="dutyPerson">
            <el-input v-model="formData.dutyPerson" placeholder="请输入责任人" />
          </el-form-item>
        </el-col> -->

        <el-col :span="12">
          <el-form-item label="序列号" prop="serialNo">
            <el-input v-model="formData.serialNo" placeholder="请输入序列号" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="部门" prop="deptId">
            <el-tree-select
              clearable
              v-model="formData.deptId"
              :data="deptList2"
              :props="defaultProps"
              :check-strictly="false"
              node-key="id"
              filterable
              placeholder="请选择所在部门" />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="责任人" prop="dutyPerson">
            <el-input v-model="formData.dutyPerson" placeholder="请输入责任人" />
          </el-form-item>
        </el-col>
        <!-- <el-col :span="12">
          <el-form-item label="品牌" prop="brand">
            <el-input v-model="formData.brand" placeholder="请输入品牌" />
          </el-form-item>
        </el-col> -->
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="品牌" prop="brand">
            <el-input v-model="formData.brand" placeholder="请输入品牌" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="规格型号" prop="modelName">
            <el-input v-model="formData.modelName" placeholder="请输入规格型号" />
          </el-form-item>
        </el-col>
        <!-- <el-col :span="12">
          <el-form-item label="单位" prop="measureUnit">
            <el-input v-model="formData.measureUnit" placeholder="请输入单位" />
          </el-form-item>
        </el-col> -->
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="精度" prop="measureUnit">
            <el-input v-model="formData.measureUnit" placeholder="请输入精度" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="分类" prop="classify">
            <el-select
              v-model="formData.classify"
              placeholder="请选择分类"
              clearable
              class="!w-240px">
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.MEASURE_TYPE)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <!-- <el-col :span="12">
          <el-form-item label="价格" prop="measurePrice">
            <el-input-number
              v-model="formData.measurePrice"
              :precision="2"
              :step="1"
              placeholder="请输入价格"
              style="width: 100%" />
          </el-form-item>
        </el-col> -->
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="状态" prop="status">
            <el-select
              v-model="formData.status"
              placeholder="请选择状态"
              clearable
              class="!w-240px">
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.MEASURE_STATUS)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="isScrappedStatus(formData.status)">
          <div class="flex items-center relative">
            <span class="text-red absolute left-6 top-[-1px]">*</span>
            <el-form-item label="报废时间" prop="offTime">
              <el-date-picker
                v-model="formData.offTime"
                type="date"
                value-format="x"
                placeholder="请选择报废时间"
                style="width: 100%" />
            </el-form-item>
          </div>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="价格" prop="measurePrice">
            <el-input-number
              v-model="formData.measurePrice"
              :precision="2"
              :step="1"
              placeholder="请输入价格"
              style="width: 100%" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="采购日期" prop="buyDate">
            <el-date-picker
              v-model="formData.buyDate"
              type="date"
              value-format="x"
              placeholder="请选择采购日期"
              style="width: 100%" />
          </el-form-item>
        </el-col>
        <!-- <el-col :span="12">
          <el-form-item label="备注" prop="remark">
            <el-input v-model="formData.remark" type="textarea" placeholder="请输入描述" />
          </el-form-item>
        </el-col> -->
      </el-row>

      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="备注" prop="remark">
            <el-input v-model="formData.remark" type="textarea" placeholder="请输入描述" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <el-button @click="closeDialog">取 消</el-button>
      <el-button type="primary" @click="submitForm" :loading="submitLoading">确 定</el-button>
    </template>
  </Dialog>

  <el-drawer
    v-model="drawerVisible"
    title="检测信息"
    size="60%"
    direction="rtl"
    :before-close="closeDrawer">
    <div v-loading="drawerLoading">
      <zm-table
        :loading="loading"
        :data="measureDetectionData"
        :stripe="true"
        :row-style="tableRowStyle"
        :row-class-name="tableRowClassName"
        height="80vh"
        :show-overflow-tooltip="true">
        <zm-table-column :label="t('monitor.serial')" width="70" align="center" fixed="left">
          <template #default="scope">
            {{ scope.$index + 1 }}
          </template>
        </zm-table-column>
        <zm-table-column
          label="计量器具名称"
          align="center"
          prop="measureName"
          min-width="160"
          fixed="left" />
        <zm-table-column label="证书编码" align="center" prop="measureCertNo" min-width="160" />
        <zm-table-column label="检测/校准日期" align="center" prop="detectDate" width="140">
          <template #default="scope">
            <span class="iot-md-date">{{ formatDateCorrectly(scope.row.detectDate) }}</span>
          </template>
        </zm-table-column>
        <zm-table-column label="检测/校准机构" align="center" prop="detectOrg" min-width="160" />
        <zm-table-column
          label="检测/校准标准"
          align="center"
          prop="detectStandard"
          min-width="160" />
        <zm-table-column label="检测/校准内容" align="center" prop="detectContent" min-width="220">
          <template #default="scope">
            <div class="detect-content" v-html="scope.row.detectContent"></div>
          </template>
        </zm-table-column>
        <zm-table-column label="检测/校准有效期" align="center" prop="validityPeriod" width="140">
          <template #default="scope">
            <span class="iot-md-date">{{ formatDateCorrectly(scope.row.validityPeriod) }}</span>
          </template>
        </zm-table-column>
        <zm-table-column label="校准金额" align="center" prop="detectAmount" width="120" />
        <zm-table-column label="部门名称" align="center" prop="deptName" min-width="140" />
        <zm-table-column
          label="附件"
          align="center"
          prop="file"
          min-width="90"
          fixed="right"
          action>
          <template #default="scope">
            <el-button v-if="scope.row.file" link type="primary" @click="viewFile(scope.row.file)">
              查看
            </el-button>

            <span v-else class="text-[#999ca1]">暂无附件</span>
          </template>
        </zm-table-column>
      </zm-table>
      <div class="iot-md-pagination absolute right-2 bottom-2">
        <Pagination
          :total="totalMsg"
          v-model:page="queryParams2.pageNo"
          v-model:limit="queryParams2.pageSize"
          @pagination="getList2" />
      </div>
    </div>
  </el-drawer>

  <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>

  <MeasureCertDrawer ref="certDrawerRef" />
</template>

<script setup lang="ts">
import * as echarts from 'echarts'
import { IotInstrumentApi, IotMeasureDetectApi } from '@/api/pms/qhse/index'
import MeasureCertDrawer from './MeasureCertDrawer.vue'
import DeptTreeSelect from '@/components/DeptTreeSelect/index.vue'
import { defaultProps } from '@/utils/tree'
import * as DeptApi from '@/api/system/dept'
import { ElMessageBox } from 'element-plus'
const deptList2 = ref<Tree[]>([]) // 树形结构
import { formatDate } from '@/utils/formatTime'
import { useUserStore } from '@/store/modules/user'
import { DICT_TYPE, getStrDictOptions, getBoolDictOptions } from '@/utils/dict'
import { useTableComponents } from '@/components/ZmTable/useTableComponents'
const { ZmTable, ZmTableColumn } = useTableComponents()

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

defineOptions({ name: 'IotQHSEMeasure' })

const loading = ref(true) // 列表的加载中
const formLoading = ref(false) // 表单加载中
const submitLoading = ref(false) // 提交按钮加载中
let exportLoading = ref(false)

const { t } = useI18n()

type StaticItem = {
  classify: string
  count: number
}

const list = ref([]) // 列表的数据
const total = ref(0) // 列表的总页数
const staticChartRef = ref<HTMLDivElement>()
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  measureName: undefined,
  measureCertNo: undefined,
  deptId: undefined,
  expired: undefined,
  alertWarn: undefined
})
const queryFormRef = ref(null) // 搜索的表单

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 dialogVisible = ref(false)
const dialogTitle = ref('')
const isEdit = ref(false)

// 表单相关
const formRef = ref()
const formData = ref({
  measureName: '',
  measureUnit: '',
  dutyPerson: '',
  brand: '',
  modelName: '',
  classify: '',
  status: '',
  offTime: null,
  buyDate: null,
  remark: '',
  deptId: '',
  measureCode: '',
  // validity: null, // 有效期
  serialNo: '',
  measurePrice: 0, // 价格
  measureCertNo: ''
})

// 正确格式化日期的函数
const formatDateCorrectly = (timestamp) => {
  if (!timestamp) return ''

  // 如果是秒级时间戳，转换为毫秒级
  let time = Number(timestamp)
  if (time < 10000000000) {
    // 小于这个数通常表示秒级时间戳
    time = time * 1000
  }

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

const isScrappedStatus = (status) => {
  const option = getStrDictOptions(DICT_TYPE.MEASURE_STATUS).find((item) => item.value === status)
  return option?.label === '报废'
}

const validateOffTime = (_rule, value, callback) => {
  if (isScrappedStatus(formData.value.status) && !value) {
    callback(new Error('报废状态必须填写报废时间'))
    return
  }
  callback()
}

// 表单验证规则
const formRules = {
  measureName: [{ required: true, message: '计量器具名称不能为空', trigger: 'blur' }],
  dutyPerson: [{ required: true, message: '责任人不能为空', trigger: 'blur' }],
  classify: [{ required: true, message: '分类不能为空', trigger: 'blur' }],
  status: [{ required: true, message: '状态不能为空', trigger: 'change' }],
  deptId: [{ required: true, message: '部门不能为空', trigger: 'blur' }],
  measureCertNo: [{ required: true, message: '证书编码不能为空', trigger: 'blur' }],
  validity: [{ required: true, message: '有效期不能为空', trigger: 'blur' }],
  serialNo: [{ required: true, message: '序列号不能为空', trigger: 'blur' }],
  measureUnit: [{ required: true, message: '精度不能为空', trigger: 'blur' }],
  offTime: [{ validator: validateOffTime, trigger: ['change', 'blur'] }]
}

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

const downloadFile = (response: any) => {
  // 创建 blob 对象
  const blob = new Blob([response], {
    type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'
  })

  // 获取文件名
  let fileName = '计量器具台账.xlsx'
  const disposition = response.headers ? response.headers['content-disposition'] : ''
  if (disposition) {
    const filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/
    const matches = filenameRegex.exec(disposition)
    if (matches != null && matches[1]) {
      fileName = matches[1].replace(/['"]/g, '')
    }
  }

  // 创建下载链接
  const url = window.URL.createObjectURL(blob)
  const link = document.createElement('a')
  link.href = url
  link.setAttribute('download', fileName)

  // 触发下载
  document.body.appendChild(link)
  link.click()

  // 清理
  document.body.removeChild(link)
  window.URL.revokeObjectURL(url)
}

const handleExport = async () => {
  try {
    exportLoading.value = true
    // 调用导出接口
    const response = await IotInstrumentApi.exportInstrument(queryParams)

    // 下载文件
    downloadFile(response)
    exportLoading.value = false
  } catch (error) {
    ElMessage.error('导出失败，请重试')
    console.error('导出错误:', error)
  } finally {
  }
}

/** 首页处理部门被点击 */
const handleDeptNodeClick = async (row) => {
  queryParams.deptId = row.id
  await getList()
  await getStatic()
}

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

const handleStatCardClick = (type: 'expired' | 'warn') => {
  queryParams.pageNo = 1

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

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

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields()
  handleQuery()
}

// 显示新增对话框
const handleAdd = () => {
  isEdit.value = false
  dialogTitle.value = '新增台账'
  resetForm()
  formData.value.deptId = queryParams.deptId || userStore.getUser.deptId
  dialogVisible.value = true
}

// 显示编辑对话框
const handleEdit = (row) => {
  isEdit.value = true
  dialogTitle.value = '编辑台账'

  formData.value = {
    ...row,
    // 确保日期字段正确处理
    offTime: row.offTime ? ensureMillisecondTimestamp(row.offTime) : null,
    buyDate: row.buyDate ? ensureMillisecondTimestamp(row.buyDate) : null,
    validity: row.validity ? ensureMillisecondTimestamp(row.validity) : null
  }

  dialogVisible.value = true
}

// 关闭抽屉
const closeDrawer = () => {
  drawerVisible.value = false
  measureDetectionData.value = []
}

const certDrawerRef = ref()

const viewCert = (row) => {
  certDrawerRef.value?.open({
    id: row.id,
    measureName: row.measureName,
    measureCode: row.measureCode,
    deptId: row.deptId
  })
}

// 抽屉相关响应式数据
const drawerVisible = ref(false)
const drawerLoading = ref(false)
const measureDetectionData = ref([])
let totalMsg = ref(0)
let currentId = ref(null)
let queryParams2 = reactive({
  pageNo: 1,
  pageSize: 10,
  measureId: null
})

const handleView = async (id: any) => {
  drawerLoading.value = true
  currentId.value = id
  try {
    const response = await IotMeasureDetectApi.getIotMeasureDetectPage({
      pageNo: queryParams2.pageNo,
      pageSize: queryParams2.pageSize,
      measureId: id
    })
    measureDetectionData.value = response.list || []
    totalMsg.value = response.total
    drawerVisible.value = true
  } catch (error) {
    console.error('获取检测信息失败:', error)
  } finally {
    drawerLoading.value = false
  }
}

const getList2 = async () => {
  drawerLoading.value = true
  try {
    const response = await IotMeasureDetectApi.getIotMeasureDetectPage({
      pageNo: queryParams2.pageNo,
      pageSize: queryParams2.pageSize,
      measureId: currentId.value
    })
    measureDetectionData.value = response.list || []
    totalMsg.value = response.total
    drawerVisible.value = true
  } catch (error) {
    console.error('获取检测信息失败:', error)
  } finally {
    drawerLoading.value = false
  }
}

// 确保时间戳是毫秒级的
const ensureMillisecondTimestamp = (timestamp) => {
  let time = Number(timestamp)
  if (time < 10000000000) {
    // 秒级时间戳转为毫秒级
    return time * 1000
  }
  return time
}

//删除成套
const handleDelete = async (id: number) => {
  ElMessageBox.confirm('确定要删除该台账吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      try {
        await IotInstrumentApi.deleteInstrument(id)
        ElMessage.success('删除成功')
        getList()
      } catch (error) {
        console.error(error)
      }
    })
    .catch(() => {
      // 取消操作
    })
}

// 重置表单
const resetForm = () => {
  formData.value = {
    measureName: '',
    measureUnit: '',
    dutyPerson: '',
    brand: '',
    modelName: '',
    classify: '',
    status: '',
    offTime: null,
    buyDate: null,
    remark: '',
    deptId: '',
    measureCode: '',
    // validity: null, // 有效期

    measurePrice: 0, // 价格
    measureCertNo: ''
  }
  formRef.value?.clearValidate()
}

// 关闭对话框
const closeDialog = () => {
  dialogVisible.value = false
  resetForm()
}

watch(
  () => formData.value.status,
  (value) => {
    if (!isScrappedStatus(value)) {
      formData.value.offTime = null
    }
  }
)

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    submitLoading.value = true

    // 准备提交数据
    const submitData = {
      ...formData.value,
      // 确保日期字段以正确的格式提交
      offTime: formData.value.offTime,
      buyDate: formData.value.buyDate,
      validity: formData.value.validity
    }

    if (isEdit.value) {
      // 编辑
      await IotInstrumentApi.updateInstrument(submitData)
      ElMessage.success('编辑成功')
    } else {
      // 新增
      await IotInstrumentApi.createInstrument(submitData)
      ElMessage.success('新增成功')
    }

    dialogVisible.value = false
    getList()
  } catch (error) {
    console.error(error)
  } finally {
    submitLoading.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 staticData = ref<StaticItem[]>([])
let expired = ref(0)
let warn = ref(0)
let staticChart: echarts.ECharts | null = null

function getStaticChartOption(): echarts.EChartsOption {
  return {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: 16,
      right: 16,
      top: 24,
      bottom: 16,
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: staticData.value.map((item) => item.classify),
      axisTick: {
        show: false
      },
      axisLine: {
        lineStyle: {
          color: '#d9e2ef'
        }
      },
      axisLabel: {
        color: '#6b7280',
        fontSize: 12,
        interval: 0
      }
    },
    yAxis: {
      type: 'value',
      axisLine: {
        show: false
      },
      axisTick: {
        show: false
      },
      axisLabel: {
        color: '#94a3b8',
        fontSize: 12
      },
      splitLine: {
        lineStyle: {
          color: '#edf2f7',
          type: 'dashed'
        }
      }
    },
    series: [
      {
        type: 'bar',
        barWidth: 32,
        data: staticData.value.map((item) => item.count),
        itemStyle: {
          borderRadius: [8, 8, 0, 0],
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#79b8ff' },
            { offset: 1, color: '#2f78f6' }
          ])
        },
        label: {
          show: true,
          position: 'top',
          color: '#2563eb',
          fontSize: 12,
          fontWeight: 700
        }
      }
    ]
  }
}

function renderStaticChart() {
  if (!staticChartRef.value) return
  if (!staticChart) {
    staticChart = echarts.init(staticChartRef.value)
  }
  staticChart.setOption(getStaticChartOption(), true)
}

function resizeStaticChart() {
  staticChart?.resize()
}

function destroyStaticChart() {
  if (staticChart) {
    staticChart.dispose()
    staticChart = null
  }
}

async function getStatic() {
  if (queryParams.deptId) {
    const res = await IotInstrumentApi.getInstrumentStatistics(queryParams.deptId)
    staticData.value = res.classify
    expired.value = res.expired
    warn.value = res.warn
  } else {
    const res = await IotInstrumentApi.getInstrumentStatistics(userStore.user.deptId)
    staticData.value = res.classify
    expired.value = res.expired
    warn.value = res.warn
  }
  nextTick(() => {
    renderStaticChart()
  })
}

onMounted(async () => {
  getList()
  getStatic()

  deptList2.value = await DeptApi.getSimpleDeptList()
  window.addEventListener('resize', resizeStaticChart)
})

onUnmounted(() => {
  window.removeEventListener('resize', resizeStaticChart)
  destroyStaticChart()
})
</script>

<style scoped>
.file-name-text {
  display: block;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
::deep(.el-tree--highlight-current) {
  height: 200px !important;
}
::deep(.el-transfer-panel__body) {
  height: 700px !important;
}

.qhse-page {
  grid-template-columns: auto minmax(0, 1fr);
}

.stats-cards {
  display: grid;
  grid-template-columns: minmax(180px, 0.7fr) minmax(180px, 0.7fr) minmax(360px, 1.6fr);
  gap: 12px;
  align-items: stretch;
}

.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;
}

@media (width <= 1440px) {
  .stats-cards {
    grid-template-columns: minmax(180px, 0.8fr) minmax(180px, 0.8fr) minmax(300px, 1.3fr);
  }
}

@media (max-width: 768px) {
  .qhse-page {
    grid-template-columns: 1fr;
    grid-template-rows: auto auto auto minmax(420px, 1fr) auto;
    height: auto;
    min-height: calc(
      100vh - 20px - var(--top-tool-height) - var(--tags-view-height) - var(--app-footer-height)
    );
  }

  .stats-cards {
    grid-template-columns: 1fr;
  }
}

.stats-chart-card {
  padding: 14px 16px 10px;
  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-chart {
  height: 130px;
  margin-top: 6px;
}

.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__header {
  display: flex;
  align-items: center;
  gap: 8px;
}

.stats-card__icon {
  color: inherit;
  opacity: 0.85;
}

.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__desc {
  margin-top: 8px;
  font-size: 12px;
  color: #9ca3af;
  font-weight: 500;
}

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

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

.stats-card--expired .stats-card__icon {
  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--warn .stats-card__icon {
  color: #d97706;
}

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