<template>
  <el-drawer v-model="drawerVisible" title="证书检测列表" size="60%" :before-close="handleClose">
    <div class="cert-drawer-content">
      <el-form
        :model="queryParams"
        ref="queryFormRef"
        class="bg-white dark:bg-[#1d1e1f] rounded-lg shadow px-4 pt-4 mb-4">
        <div class="flex items-center gap-4 flex-wrap">
          <el-form-item label="应急物资名称" prop="emergencyName">
            <el-input
              v-model="queryParams.emergencyName"
              placeholder="请输入应急物资名称"
              clearable
              class="!w-150px" />
          </el-form-item>
          <el-form-item label="证书编号" prop="certNo">
            <el-input
              v-model="queryParams.certNo"
              placeholder="请输入证书编号"
              clearable
              class="!w-200px" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" plain @click="openForm('create')">
              <Icon icon="ep:plus" class="mr-5px" /> 新增
            </el-button>
            <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-form-item>
        </div>
      </el-form>

      <div class="cert-table-wrapper">
        <el-auto-resizer>
          <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" fixed="left">
                <template #default="scope">
                  {{ scope.$index + 1 }}
                </template>
              </zm-table-column>
              <zm-table-column
                label="物资名称"
                align="center"
                prop="emergencyName"
                fixed="left"
                min-width="140" />
              <zm-table-column label="证书编号" align="center" prop="certNo" min-width="140" />
              <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" min-width="160" />
              <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="remark"
                min-width="160"
                show-overflow-tooltip />
              <zm-table-column label="附件" fixed="right" align="center" prop="file" 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>
          </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>
  </el-drawer>

  <Dialog :title="formDialogTitle" v-model="formDialogVisible" width="50%">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="auto"
      v-loading="formLoading">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="关联物资" prop="emergencyId">
            <el-input
              v-model="formData.emergencyName"
              disabled
              placeholder="关联物资"
              style="width: 100%" />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="证书编号" prop="certNo">
            <el-input v-model="formData.certNo" placeholder="请输入证书编号" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="检测单位" prop="certOrg">
            <el-input v-model="formData.certOrg" placeholder="请输入检测单位" />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="检测日期" prop="certTime">
            <el-date-picker
              v-model="formData.certTime"
              type="date"
              value-format="x"
              placeholder="请选择检测日期"
              style="width: 100%" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="有效期至" prop="certExpire">
            <el-date-picker
              v-model="formData.certExpire"
              type="date"
              value-format="x"
              placeholder="请选择有效期至"
              style="width: 100%" />
          </el-form-item>
        </el-col>

        <!-- <el-col :span="12">
          <el-form-item label="部门" prop="deptId">
            <el-tree-select
              v-model="formData.deptId"
              :data="deptList"
              :props="defaultProps"
              node-key="id"
              filterable
              clearable
              placeholder="请选择部门"
              style="width: 100%" />
          </el-form-item>
        </el-col> -->
      </el-row>

      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="附件" prop="file">
            <UploadFile
              v-model="formData.file"
              :file-type="['doc', 'docx', 'pdf', 'jpg', 'png', 'jpeg', 'xls', 'xlsx', 'bmp']"
              :limit="3"
              :file-size="100"
              class="min-w-80px" />
          </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"
              :rows="3"
              placeholder="请输入备注" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="formDialogVisible = false">取 消</el-button>
    </template>
  </Dialog>

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

<script setup lang="ts">
import { EmergencyDrillCertApi, EmergencyDrillApi } from '@/api/pms/qhse/index'
import { useTableComponents } from '@/components/ZmTable/useTableComponents'
import { formatDate } from '@/utils/formatTime'
import { defaultProps } from '@/utils/tree'
import * as DeptApi from '@/api/system/dept'
import { useUserStore } from '@/store/modules/user'

const { ZmTable, ZmTableColumn } = useTableComponents()

defineOptions({ name: 'CertDrawer' })

const message = useMessage()
const { t } = useI18n()
const userStore = useUserStore()

const drawerVisible = ref(false)
const loading = ref(false)
const list = ref<any[]>([])
const total = ref(0)
const currentEmergencyId = ref<number | undefined>(undefined)
const currentEmergencyName = ref<string>('')

const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  emergencyId: undefined,
  certNo: undefined,
  emergencyName: undefined
})

const queryFormRef = ref()

const getList = async () => {
  if (!currentEmergencyId.value) return

  loading.value = true
  try {
    const data = await EmergencyDrillCertApi.getEmergencyDrillCertList(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

const formDialogVisible = ref(false)
const formDialogTitle = ref('')
const formLoading = ref(false)
const formType = ref('')
const formRef = ref()
const deptList = ref<Tree[]>([])

const createDefaultFormData = () => ({
  id: undefined,
  emergencyId: undefined,
  emergencyName: '',
  deptId: undefined,
  certNo: '',
  certOrg: '',
  certTime: undefined,
  certExpire: undefined,
  file: '',
  remark: ''
})

const formData = ref(createDefaultFormData())

const formRules = reactive({
  emergencyId: [{ required: true, message: '关联设备不能为空', trigger: 'blur' }],
  certNo: [{ required: true, message: '证书编号不能为空', trigger: 'blur' }],
  certOrg: [{ required: true, message: '检测单位不能为空', trigger: 'blur' }],
  certTime: [{ required: true, message: '检测日期不能为空', trigger: 'blur' }],
  certExpire: [{ required: true, message: '有效期不能为空', trigger: 'blur' }],
  file: [{ required: true, message: '请上传附件', trigger: 'blur' }],
  deptId: [{ required: true, message: '所在部门不能为空', trigger: 'blur' }]
})

const openForm = (type: string, id?: number) => {
  formDialogVisible.value = true
  formDialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()

  if (type === 'create') {
    formData.value.emergencyId = currentEmergencyId.value
    formData.value.emergencyName = currentEmergencyName.value
    formData.value.deptId = userStore.getUser.deptId
  } else if (id) {
    loadFormData(id)
  }
}

const resetForm = () => {
  formData.value = createDefaultFormData()
  formRef.value?.resetFields()
}

const loadFormData = async (id: number) => {
  formLoading.value = true
  try {
    const res = await EmergencyDrillCertApi.getEmergencyDrillCert(id)
    formData.value = {
      ...createDefaultFormData(),
      ...res,
      certTime: res.certTime ? Number(res.certTime) : undefined,
      certExpire: res.certExpire ? Number(res.certExpire) : undefined
    }
  } finally {
    formLoading.value = false
  }
}

const submitForm = async () => {
  await formRef.value.validate()
  formLoading.value = true
  try {
    const data = { ...formData.value } as any
    if (data.file instanceof Array) {
      data.file = data.file.join(',')
    }

    if (formType.value === 'create') {
      await EmergencyDrillCertApi.createEmergencyDrillCert(data)
      message.success(t('common.createSuccess'))
    } else {
      await EmergencyDrillCertApi.updateEmergencyDrillCert(data)
      message.success(t('common.updateSuccess'))
    }

    formDialogVisible.value = false
    getList()
  } finally {
    formLoading.value = false
  }
}

const open = async (emergencyId: number, emergencyName?: string) => {
  currentEmergencyId.value = emergencyId
  currentEmergencyName.value = emergencyName || ''
  queryParams.emergencyId = emergencyId
  queryParams.pageNo = 1
  queryParams.certNo = undefined
  queryParams.emergencyName = undefined
  drawerVisible.value = true

  if (deptList.value.length === 0) {
    deptList.value = await DeptApi.getSimpleDeptList()
  }

  getList()
}

const handleClose = () => {
  drawerVisible.value = false
  currentEmergencyId.value = undefined
  currentEmergencyName.value = ''
  list.value = []
  total.value = 0
}

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 dialogFileView = ref(false)
const fileList = ref<string[]>([])

const viewFile = (file: string) => {
  fileList.value = file.split(',')
  dialogFileView.value = true
}

const viewFileInfo = (file: string) => {
  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]
    return decodeURIComponent(fileName) || url
  } catch {
    return url
  }
}

const handleDownload = async (url: string) => {
  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() || 'file'
    link.click()
    URL.revokeObjectURL(downloadUrl)
  } catch (error) {
    console.error('下载失败:', error)
  }
}

defineExpose({
  open
})
</script>

<style scoped>
.cert-drawer-content {
  height: 100%;
  display: flex;
  flex-direction: column;
  margin-top: -20px;
}

.cert-table-wrapper {
  flex: 1;
  min-height: 0;
  position: relative;
}

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