<template>
  <el-row :gutter="20">
    <DeptTree @node-click="handleDeptNodeClick" v-model:collapsed="isLeftContentCollapsed" />

    <el-col :span="isLeftContentCollapsed ? 24 : 20" :xs="24">
      <ContentWrap>
        <!-- 搜索工作栏 -->
        <el-form :model="queryParams" ref="queryFormRef" :inline="true">
          <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"
              type="date"
              placeholder="选择检测/校准有效期"
              clearable
              class="!w-150px"
            />
          </el-form-item>
          <el-form-item label="校准金额" prop="detectAmount">
            <el-input
              v-model="queryParams.detectAmount"
              placeholder="请输入校准金额"
              clearable
              @keyup.enter="handleQuery"
              class="!w-150px"
            />
          </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>
        </el-form>
      </ContentWrap>

      <!-- 列表 -->
      <ContentWrap class="flex-1 overflow-hidden mt-15px">
        <el-table
          v-loading="loading"
          :data="list"
          :stripe="true"
          height="calc(85vh - 187px)"
          :show-overflow-tooltip="true"
        >
          <el-table-column :label="t('monitor.serial')" width="70" align="center">
            <template #default="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column label="计量器具名称" align="center" prop="measureName" min-width="160" />
          <el-table-column label="证书编码" align="center" prop="measureCertNo" min-width="160" />
          <el-table-column label="检测/校准日期" align="center" prop="detectDate" width="140">
            <template #default="scope">
              <span class="iot-md-date">{{ formatDateCorrectly(scope.row.detectDate) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="检测/校准机构" align="center" prop="detectOrg" min-width="160" />
          <el-table-column
            label="检测/校准标准"
            align="center"
            prop="detectStandard"
            min-width="160"
          />
          <el-table-column
            label="检测/校准内容"
            align="center"
            prop="detectContent"
            min-width="220"
          >
            <template #default="scope">
              <div class="detect-content" v-html="scope.row.detectContent"></div>
            </template>
          </el-table-column>
          <el-table-column label="检测/校准有效期" align="center" prop="validityPeriod" width="140">
            <template #default="scope">
              <span class="iot-md-date">{{ formatDateCorrectly(scope.row.validityPeriod) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="校准金额" align="center" prop="detectAmount" width="120" />
          <el-table-column label="部门名称" align="center" prop="deptName" min-width="140" />
          <el-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>
          </el-table-column>
          <el-table-column label="操作" align="center" width="140" fixed="right">
            <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>
          </el-table-column>
        </el-table>
        <div class="iot-md-pagination">
          <Pagination
            :total="total"
            v-model:page="queryParams.pageNo"
            v-model:limit="queryParams.pageSize"
            @pagination="getList"
          />
        </div>
      </ContentWrap>
    </el-col>
  </el-row>

  <el-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>
  </el-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 DeptTree from '@/views/system/user/DeptTree2.vue'

/** 计量器具-检测校准明细 列表 */
defineOptions({ name: 'IotMeasureDetect' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const isLeftContentCollapsed = ref(false)

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
})
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 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 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>
::deep(.el-tree--highlight-current) {
  height: 200px !important;
}
::deep(.el-transfer-panel__body) {
  height: 700px !important;
}

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