<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="证书名称" prop="certificateName">
        <el-input
          v-model="queryParams.certificateName"
          placeholder="请输入证书名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="编号" prop="certificateNumber">
        <el-input
          v-model="queryParams.certificateNumber"
          placeholder="请输入编号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="发证部门" prop="issuingAuthority">
        <el-input
          v-model="queryParams.issuingAuthority"
          placeholder="请输入发证部门"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="责任人" prop="responsiblePerson">
        <el-input
          v-model="queryParams.responsiblePerson"
          placeholder="请输入责任人"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="到期日" prop="expiryDate">
        <el-date-picker
          v-model="queryParams.expiryDate"
          value-format="YYYY-MM-DD"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="datetimerange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          class="!w-240px"
        />
      </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')"
          v-hasPermi="['safe:permit:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['safe:permit:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
        <el-button
          type="info"
          plain
          @click="handleImport"
          v-hasPermi="['safe:permit:import']"
        >
          <Icon icon="ep:upload" class="mr-5px" /> 导入
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true" @row-click="handleRowClick">
      <el-table-column label="主键ID" align="center" prop="id" />
      <el-table-column label="证书名称" align="center" prop="certificateName" />
      <el-table-column label="编号" align="center" prop="certificateNumber" />
      <el-table-column label="发证部门" align="center" prop="issuingAuthority" />
      <el-table-column
        label="颁证日期"
        align="center"
        prop="issueDate"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column
        label="换证日期"
        align="center"
        prop="renewalDate"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column
        label="到期日"
        align="center"
        prop="expiryDate"
        :formatter="dateFormatter"
        width="180px"
      >
        <template #default="scope">
          <span :class="getExpiryClass(scope.row.expiryDate)">
            {{ dateFormatter(scope.row, scope.column, scope.row.expiryDate) }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="责任人" align="center" prop="responsiblePerson" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="操作" align="center" width="320">
        <template #default="scope">
          <el-button
            link
            type="info"
            @click="openForm('view', scope.row.id)"
            v-hasPermi="['safe:permit:query']"
          >
            查看
          </el-button>
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['safe:permit:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['safe:permit:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <PermitForm ref="formRef" @success="getList" />

  <!-- 导入对话框 -->
  <ImportForm ref="importFormRef" @success="getList" />
</template>

<script setup lang="ts">
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { PermitApi, PermitVO } from '@/api/safe/permit'
import PermitForm from './PermitForm.vue'
import ImportForm from './ImportForm.vue'

/** 许可证照 列表 */
defineOptions({ name: 'SafePermit' })

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

const loading = ref(true) // 列表的加载中
const list = ref<PermitVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  certificateName: undefined,
  certificateNumber: undefined,
  issuingAuthority: undefined,
  issueDate: [],
  renewalDate: [],
  expiryDate: [],
  responsiblePerson: undefined,
  createTime: []
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await PermitApi.getPermitPage(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 formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await PermitApi.deletePermit(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await PermitApi.exportPermit(queryParams)
    download.excel(data, '许可证照.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 导入按钮操作 */
const importFormRef = ref()
const handleImport = () => {
  importFormRef.value.open()
}

/** 行点击操作 */
const handleRowClick = (row: PermitVO) => {
  openForm('view', row.id)
}

/** 获取到期日样式 */
const getExpiryClass = (expiryDate: string) => {
  if (!expiryDate) return ''

  const today = new Date()
  const expiry = new Date(expiryDate)
  const diffTime = expiry.getTime() - today.getTime()
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))

  if (diffDays < 0) {
    return 'text-red-500' // 已过期
  } else if (diffDays <= 30) {
    return 'text-orange-500' // 30天内到期
  } else if (diffDays <= 90) {
    return 'text-yellow-500' // 90天内到期
  }
  return ''
}

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>
