<!-- src/views/pms/qhse/certificate.vue -->
<template>
  <el-row :gutter="20">
    <!-- 左侧部门树 -->
    <DeptTree @node-click="handleDeptNodeClick" v-model:collapsed="isLeftContentCollapsed" />
    <el-col :span="isLeftContentCollapsed ? 24 : 20" :xs="24">
      <ContentWrap>
        <!-- 搜索工作栏 -->
        <el-form class="-mb-15px" :model="queryParams" ref="queryFormRef" :inline="true">
          <el-form-item label="证书类型" prop="type">
            <el-select v-model="queryParams.type" placeholder="请选择证书类型" style="width: 120px">
              <el-option label="个人证书" value="personal" />
              <el-option label="组织证书" value="organization" />
              <el-option label="其他" value="other" />
            </el-select>
          </el-form-item>

          <el-form-item label="证书类别" prop="classify">
            <el-select
              v-model="queryParams.classify"
              placeholder="证书类别"
              clearable
              class="!w-150px"
            >
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.PERSON_CERT).concat(
                  getStrDictOptions(DICT_TYPE.ORG_CERT)
                )"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="所属人" prop="userName">
            <el-input placeholder="输入所属人" v-model="queryParams.userName" />
          </el-form-item>

          <el-form-item label="是否过期" prop="expired">
            <el-select
              v-model="queryParams.expired"
              placeholder="请选择是否过期"
              clearable
              style="width: 150px"
            >
              <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="handleAdd" type="primary"
              ><Icon icon="ep:plus" class="mr-5px" />新增</el-button
            >
            <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="handleExport" type="success" plain :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"
          height="calc(80vh - 203px)"
          :show-overflow-tooltip="true"
          :row-style="tableRowStyle"
        >
          <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="type">
            <template #default="scope">
              {{ getCertificateTypeText(scope.row.type) }}
            </template>
          </el-table-column>

          <el-table-column label="证书类别" align="center" width="150" prop="classify">
            <template #default="scope">
              <dict-tag
                v-if="scope.row.type === 'organization'"
                :type="DICT_TYPE.ORG_CERT"
                :value="scope.row.classify"
              />
              <dict-tag v-else :type="DICT_TYPE.PERSON_CERT" :value="scope.row.classify" />
            </template>
          </el-table-column>
          <el-table-column
            label="证书名称"
            width="150"
            align="center"
            prop="certName"
            show-overflow-tooltip
          />

          <el-table-column label="所属人" align="center" prop="userName" />
          <el-table-column label="所在部门" align="center" prop="deptName" />

          <el-table-column label="颁发机构" align="center" prop="certOrg" width="120" />

          <el-table-column label="证书标准" align="center" prop="certStandard" width="120" />

          <el-table-column label="颁发时间" align="center" prop="certIssue">
            <template #default="scope">
              {{ formatDateCorrectly(scope.row.certIssue) }}
            </template>
          </el-table-column>

          <el-table-column label="有效期" align="center">
            <template #default="scope">
              {{ formatDateCorrectly(scope.row.certExpire) }}
            </template>
          </el-table-column>

          <el-table-column label="到期提醒" align="center">
            <template #default="scope"> {{ scope.row.noticeBefore }}天前提醒 </template>
          </el-table-column>

          <el-table-column label="备注" align="center" prop="remark" />
          <el-table-column
            :label="t('devicePerson.operation')"
            align="center"
            fixed="right"
            min-width="180px"
          >
            <template #default="scope">
              <el-button link type="primary" @click="handleEdit(scope.row)"> 编辑 </el-button>
              <el-button link type="danger" @click="handleDelete(scope.row.id)"> 删除 </el-button>
              <el-button
                link
                type="success"
                v-if="scope.row.certPic"
                @click="handleViewImage(scope.row.certPic)"
              >
                查看证书
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <Pagination
          :total="total"
          v-model:page="queryParams.pageNo"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
        />
      </ContentWrap>

      <ContentWrap style="margin-top: -5px">
        <el-alert title="证书已过期红色预警" type="error" show-icon :closable="false">
          <template #icon>
            <Bell />
          </template>
        </el-alert>
      </ContentWrap>
    </el-col>
  </el-row>

  <!-- 新增/编辑证书对话框 -->
  <el-dialog
    :title="dialogTitle"
    v-model="dialogVisible"
    width="600px"
    destroy-on-close
    @close="closeDialog"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      v-loading="formLoading"
    >
      <el-form-item label="证书类型" prop="type">
        <el-select
          v-model="formData.type"
          placeholder="请选择证书类型"
          @change="formData.classify = ''"
        >
          <el-option label="个人证书" value="personal" />
          <el-option label="组织证书" value="organization" />
          <el-option label="其他" value="other" />
        </el-select>
      </el-form-item>

      <span class="absolute left-16 text-red" v-if="formData.type !== 'other'">*</span>
      <el-form-item label="证书类别" prop="classify" v-show="formData.type !== 'other'">
        <el-select
          v-if="formData.type === 'personal'"
          v-model="formData.classify"
          placeholder="证书类别"
          clearable
        >
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.PERSON_CERT)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
        <el-select v-else v-model="formData.classify" placeholder="证书类别" clearable>
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.ORG_CERT)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="证书名称" prop="certName">
        <el-input v-model="formData.certName" placeholder="请输入证书名称" />
      </el-form-item>

      <el-form-item label="所在部门" prop="deptId">
        <el-tree-select
          clearable
          v-model="formData.deptId"
          :data="deptList2"
          :props="defaultProps"
          check-strictly
          node-key="id"
          filterable
          placeholder="请选择所在部门"
          @change="handleDeptChange"
        />
      </el-form-item>

      <el-form-item label="所属人" prop="userName">
        <el-input v-model="formData.userName" placeholder="请输入所属人" />
      </el-form-item>

      <el-form-item label="颁发机构" prop="certOrg">
        <el-input v-model="formData.certOrg" placeholder="请输入颁发机构" />
      </el-form-item>

      <el-form-item label="证书标准" prop="certStandard">
        <el-input v-model="formData.certStandard" placeholder="如国标、API等" />
      </el-form-item>

      <el-form-item label="颁发时间" prop="certIssue">
        <el-date-picker
          v-model="formData.certIssue"
          type="date"
          value-format="x"
          placeholder="请选择颁发时间"
          style="width: 100%"
        />
      </el-form-item>

      <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-form-item label="到期前提醒" prop="noticeBefore">
        <el-input-number
          v-model="formData.noticeBefore"
          :min="0"
          :max="365"
          placeholder="请输入提前多少天提醒"
          style="width: 100%"
        />
      </el-form-item>

      <el-form-item label="备注" prop="remark">
        <el-input
          type="textarea"
          v-model="formData.remark"
          :rows="2"
          placeholder="请输入备注"
          style="width: 100%"
        />
      </el-form-item>

      <el-form-item label="证书图片" prop="certPic">
        <UploadImage v-model="formData.certPic" />
      </el-form-item>
    </el-form>

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

  <!-- 查看证书图片对话框 -->
  <el-dialog :title="imageDialogTitle" v-model="imageDialogVisible" width="800px" center>
    <!-- <img :src="imagePreviewUrl" alt="证书图片" style="max-width: 100%; max-height: 80vh" /> -->
    <div
      style="display: flex; justify-content: center; align-items: center; flex-direction: column"
    >
      <img
        v-for="url in imagePreviewUrl"
        :src="url"
        :key="url"
        alt="证书图片"
        style="max-width: 100%"
      />
    </div>
  </el-dialog>
</template>

<script setup lang="ts">
import { IotMeasureCertApi } from '@/api/pms/qhse/index'
import DeptTree from '@/views/system/user/DeptTree2.vue'
import { handleTree } from '@/utils/tree'
import * as DeptApi from '@/api/system/dept'
import { ElMessageBox, ElMessage } from 'element-plus'
const deptList = ref<Tree[]>([]) // 树形结构
const deptList2 = ref<Tree[]>([]) // 树形结构
import { formatDate } from '@/utils/formatTime'
import UploadImage from '@/components/UploadFile/src/QHSEUploadImgs.vue'
import { DICT_TYPE, getStrDictOptions, getBoolDictOptions } from '@/utils/dict'
import { defaultProps } from '@/utils/tree'
import { selectedDeptsEmployee } from '@/api/system/user'

defineOptions({ name: 'IotQHSECertificate' })

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

const { t } = useI18n()

const list = ref([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  type: undefined,
  classify: undefined,
  deptId: '',
  expired: undefined
})
const queryFormRef = ref(null) // 搜索的表单

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const isEdit = ref(false)

// 图片查看对话框
const imageDialogVisible = ref(false)
const imageDialogTitle = ref('证书图片')
const imagePreviewUrl = ref('')

// 表单相关
const formRef = ref()
const formData = ref({
  type: '', // 证书类型
  classify: '', // 证书类别
  userName: '',
  certName: '',
  certOrg: '', // 证书颁发机构
  certStandard: '', // 证书标准
  certIssue: '', // 证书颁发时间
  certExpire: '', // 证书有效期
  noticeBefore: '', // 到期前提醒
  certPic: '', // 证书图片上传
  remark: '', // 备注
  deptId: '' // 部门id
})

// 获取证书类型文本
const getCertificateTypeText = (type: string) => {
  const map: Record<string, string> = {
    personal: '个人证书',
    organization: '组织证书',
    other: '其他'
  }
  return map[type] || type
}

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

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

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

// 表单验证规则
const formRules = {
  type: [{ required: true, message: '证书类型不能为空', trigger: 'blur' }],
  classify: [
    {
      required: false, // 默认设为非必填
      validator: (rule, value, callback) => {
        // 只有当证书类型不是 "other" 时才验证
        if (formData.value.type !== 'other') {
          if (!value) {
            callback(new Error('证书类别不能为空'))
          } else {
            callback()
          }
        } else {
          callback() // other 类型时不需要验证
        }
      },
      trigger: ['blur', 'change']
    }
  ],
  deptId: [{ required: true, message: '所在部门不能为空', trigger: 'blur' }],

  certOrg: [{ required: true, message: '颁发机构不能为空', trigger: 'blur' }],
  certIssue: [{ required: true, message: '颁发时间不能为空', trigger: 'blur' }],
  certExpire: [{ required: true, message: '有效期不能为空', trigger: 'blur' }]
}

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

const handleExport = async () => {
  try {
    exportLoading.value = true
    const response = await IotMeasureCertApi.exportIotMeasureCert(queryParams)
    downloadFile(response)
    exportLoading.value = false
  } catch (error) {
    ElMessage.error('导出失败，请重试')
    console.error('导出错误:', error)
  } finally {
    exportLoading.value = false
  }
}

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

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

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

// 显示新增对话框
const handleAdd = () => {
  isEdit.value = false
  dialogTitle.value = '新增证书'
  resetForm()
  dialogVisible.value = true
}

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

  formData.value = {
    ...row,
    // 确保日期字段正确处理
    issueDate: row.issueDate ? ensureMillisecondTimestamp(row.issueDate) : null,
    validityPeriod: row.validityPeriod ? ensureMillisecondTimestamp(row.validityPeriod) : null,
    certPic: row.certPic.split(',')
  }

  dialogVisible.value = true
}

// 查看证书图片
const handleViewImage = (imageUrl: any) => {
  imagePreviewUrl.value = imageUrl.split(',')
  imageDialogTitle.value = '证书图片'
  imageDialogVisible.value = true
}

// 确保时间戳是毫秒级的
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 IotMeasureCertApi.deleteIotMeasureCert(id)
        ElMessage.success('删除成功')
        getList()
      } catch (error) {
        console.error(error)
      }
    })
    .catch(() => {
      // 取消操作
    })
}

// 重置表单
const resetForm = () => {
  formData.value = {
    type: '', // 证书类型
    classify: '',
    certOrg: '', // 证书颁发机构
    certStandard: '', // 证书标准
    certIssue: '', // 证书颁发时间
    certExpire: '', // 证书有效期
    noticeBefore: '', // 到期前提醒
    certPic: '', // 证书图片上传
    remark: '', // 备注
    deptId: '', // 部门id
    userId: ''
  }
  formRef.value?.clearValidate()
}

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

const tableRowStyle = ({ row }) => {
  if (row.expired) {
    return { backgroundColor: '#ffe6e6' }
  }
  return {}
}

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

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

    // 准备提交数据
    const submitData = {
      ...formData.value,
      // 确保日期字段以正确的格式提交
      certIssue: formData.value.certIssue,
      certExpire: formData.value.certExpire,
      certPic: formData.value.certPic ? formData.value.certPic.join(',') : '' // 将图片数组转换为逗号分隔的字符串
    }

    if (isEdit.value) {
      // 编辑
      await IotMeasureCertApi.updateIotMeasureCert(submitData)
      ElMessage.success('编辑成功')
    } else {
      // 新增
      await IotMeasureCertApi.createIotMeasureCert(submitData)
      ElMessage.success('新增成功')
    }

    dialogVisible.value = false
    getList()
  } catch (error) {
    console.error(error)
  } finally {
    submitLoading.value = false
  }
}

// 下载文件函数
const downloadFile = (response: any) => {
  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)
}

let userList = ref([])
const handleDeptChange = async (value) => {
  const res = await selectedDeptsEmployee({
    deptIds: value
  })

  userList.value = res
  console.log('value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>', userList.value)
}

onMounted(async () => {
  getList()

  deptList.value = handleTree(await DeptApi.getSimpleDeptList())
  deptList2.value = handleTree(await DeptApi.getSimpleDeptList())
})
</script>

<style scoped>
::deep(.el-tree--highlight-current) {
  height: 200px !important;
}
::deep(.el-transfer-panel__body) {
  height: 700px !important;
}
.image-preview {
  margin-top: 10px;
  display: flex;
  justify-content: center;
}

::deep(.el-table__body tr.expired-row) {
  background-color: #ffe6e6 !important;
}

::deep(.el-table__body tr.expired-row:hover td) {
  background-color: #ffcccc !important;
}
</style>
