<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="measureCode">
            <el-input
              v-model="queryParams.measureCode"
              placeholder="请输入计量器具编码"
              clearable
              class="!w-150px" />
          </el-form-item>
          <el-form-item label="检测/校准日期" prop="detectDate">
            <el-date-picker
              v-model="queryParams.detectDate"
              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="detectOrg">
            <el-input
              v-model="queryParams.detectOrg"
              placeholder="请输入检测/校准机构"
              clearable
              @keyup.enter="handleQuery"
              class="!w-150px" />
          </el-form-item>
          <el-form-item label="检测/校准有效期" prop="validityPeriod">
            <el-date-picker
              v-model="queryParams.validityPeriod"
              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">
              <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')">
              <Icon icon="ep:plus" class="mr-5px" /> 新增
            </el-button>
            <el-button 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">
              <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="measureCode" />
              <zm-table-column label="序列号" align="center" prop="serialNo" />
              <zm-table-column label="计量器具名称" align="center" prop="measureName" />
              <zm-table-column label="证书编码" align="center" prop="measureCertNo" />
              <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" />
              <zm-table-column label="检测/校准标准" align="center" prop="detectStandard" />
              <zm-table-column
                label="检测/校准内容"
                align="center"
                prop="detectContent"
                width="140">
                <template #default="scope">
                  <el-button
                    v-if="getDetectContentText(scope.row.detectContent) !== '-'"
                    link
                    type="primary"
                    @click="openDetectContentDialog(scope.row.detectContent)">
                    查看详情
                  </el-button>
                </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" width="140">
                <template #default="scope">
                  <dict-tag :type="DICT_TYPE.QHSE_DETECT_CYCLE" :value="scope.row.detect_cycle" />
                </template>
              </zm-table-column>
              <zm-table-column label="精度" align="center" prop="precisions" />
              <zm-table-column label="校准金额" align="center" prop="detectAmount" />
              <zm-table-column label="部门名称" align="center" prop="deptName" />
              <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" @click="openForm('update', scope.row.id)">
                    编辑
                  </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>

  <Dialog v-model="dialogFileView" title="附件">
    <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>

  <!-- 表单弹窗：添加/修改 -->
  <Dialog v-model="detectContentDialogVisible" title="检测/校准内容" width="720">
    <div
      v-if="detectContentDialogHtml"
      class="detect-content-rich"
      v-html="detectContentDialogHtml"></div>
    <el-empty v-else description="暂无内容" />
  </Dialog>

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

<script setup lang="ts">
import download from '@/utils/download'
import { IotMeasureDetectApi, IotMeasureDetectVO } from '@/api/pms/qhse/index'
import IotMeasureDetectForm from './IotMeasureDetectForm.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 } from '@/utils/dict'

/** 计量器具-检测校准明细 列表 */
defineOptions({ name: 'IotMeasureDetect' })
// 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<IotMeasureDetectVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  measureId: undefined,
  detectDate: [],
  detectOrg: undefined,
  detectContent: undefined,
  validityPeriod: undefined,
  detectAmount: undefined,
  createTime: [],
  deptId: undefined,
  measureCode: undefined
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

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

/** 搜索按钮操作 */
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 stripHtml = (html?: string) => {
  if (!html) return ''
  if (typeof window === 'undefined') {
    return html
      .replace(/<[^>]+>/g, ' ')
      .replace(/\s+/g, ' ')
      .trim()
  }

  const div = document.createElement('div')
  div.innerHTML = html
  return (div.textContent || div.innerText || '')
    .replace(/\u00a0/g, ' ')
    .replace(/\s+/g, ' ')
    .trim()
}

const getDetectContentText = (html?: string) => {
  return stripHtml(html) || '-'
}

const getDetectContentSummary = (html?: string, maxLength = 36) => {
  const text = getDetectContentText(html)
  if (text === '-' || text.length <= maxLength) return text
  return `${text.slice(0, maxLength)}...`
}

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 IotMeasureDetectApi.deleteIotMeasureDetect(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await IotMeasureDetectApi.exportIotMeasureDetect(queryParams)
    download.excel(data, '计量器具-检测校准明细.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

let dialogFileView = ref(false)
let fileList = ref([])
const detectContentDialogVisible = ref(false)
const detectContentDialogHtml = ref('')

const openDetectContentDialog = (html?: string) => {
  detectContentDialogHtml.value = html || ''
  detectContentDialogVisible.value = true
}

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">
.file-name-text {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  margin-right: 12px;
  color: var(--el-text-color-primary);
}

.detect-content-text {
  display: block;
  width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  color: var(--el-text-color-primary);
  cursor: default;
}

.detect-content-cell {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  width: 100%;
}

.detect-content-rich {
  max-height: 60vh;
  overflow-y: auto;
  padding: 4px 2px;
  line-height: 1.75;
  color: var(--el-text-color-primary);
  word-break: break-word;
}

.detect-content-rich :deep(p) {
  margin: 0 0 12px;
}

.detect-content-rich :deep(ul),
.detect-content-rich :deep(ol) {
  margin: 0 0 12px;
  padding-left: 20px;
}

.detect-content-rich :deep(li) {
  margin-bottom: 6px;
}

.detect-content-rich :deep(img) {
  max-width: 100%;
  height: auto;
}

.detect-content-rich :deep(table) {
  width: 100%;
  border-collapse: collapse;
}

.detect-content-rich :deep(td),
.detect-content-rich :deep(th) {
  border: 1px solid var(--el-border-color-lighter);
  padding: 8px;
}
</style>
