<template>
  <div class="special-personnel-container">


    <!-- 搜索区域 -->
    <el-card shadow="never" class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="姓名">
          <el-input v-model="searchForm.name" placeholder="请输入姓名" clearable />
        </el-form-item>
        <el-form-item label="岗位">
          <el-input v-model="searchForm.position" placeholder="请输入岗位" clearable />
        </el-form-item>
        <el-form-item label="证件编号">
          <el-input v-model="searchForm.certificateNumber" placeholder="请输入证件编号" clearable />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="searchForm.remark" placeholder="请输入备注" clearable />
        </el-form-item>
        <el-form-item label="发证日期">
          <el-date-picker
            v-model="searchForm.issueDateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="有效日期">
          <el-date-picker
            v-model="searchForm.validDateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <Icon icon="mdi:magnify" class="mr-4px" />
            搜索
          </el-button>
          <el-button @click="handleReset">
            <Icon icon="mdi:refresh" class="mr-4px" />
            重置
          </el-button>
          <el-button @click="handleExport">
            <Icon icon="ep:download" class="mr-5px" /> 导出
          </el-button>
          <el-button @click="handleImport">
            <Icon icon="ep:upload" class="mr-5px" /> 导入
          </el-button>
          <el-button type="primary" @click="handleAdd">
            <Icon icon="ep:plus" class="mr-5px" /> 新增
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card shadow="never" class="table-card">
      <el-table
        v-loading="loading"
        :data="tableData"
        stripe
        style="width: 100%"
        @selection-change="handleSelectionChange"
        @row-click="handleRowClick"
        :row-style="{ cursor: 'pointer' }"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="编号" width="80" />
        <el-table-column prop="name" label="姓名" width="120" />
        <el-table-column prop="position" label="岗位" width="150" />
        <el-table-column prop="trainingContent" label="培训内容" min-width="200" show-overflow-tooltip />
        <el-table-column prop="certificateNumber" label="证件编号" width="150" />
        <el-table-column prop="issueDate" label="发证日期" width="120" />
        <el-table-column prop="validDate" label="有效日期" width="120">
          <template #default="{ row }">
            <span :class="getValidDateClass(row.validDate)">
              {{ row.validDate }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="attachments" label="附件" width="100">
          <template #default="{ row }">
            <el-button
              v-if="row.attachments && row.attachments.length > 0"
              type="text"
              @click.stop="handleViewAttachments(row)"
            >
              查看({{ row.attachments.length }})
            </el-button>
            <span v-else>无</span>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" min-width="150" show-overflow-tooltip />
        <el-table-column prop="createTime" label="创建时间" width="160" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="text" @click.stop="handleView(row)">查看</el-button>
            <el-button type="text" @click.stop="handleEdit(row)">编辑</el-button>
            <el-button type="text" style="color: #f56c6c" @click.stop="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.pageNo"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="800px"
      :before-close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="120px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="姓名">
              <el-input v-model="formData.name" placeholder="请输入姓名" :readonly="isViewMode" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="岗位">
              <el-input v-model="formData.position" placeholder="请输入岗位" :readonly="isViewMode" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="培训内容">
          <el-input
            v-model="formData.trainingContent"
            type="textarea"
            :rows="3"
            placeholder="请输入培训内容"
            :readonly="isViewMode"
          />
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="证件编号">
              <el-input v-model="formData.certificateNumber" placeholder="请输入证件编号" :readonly="isViewMode" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="发证日期">
              <el-date-picker
                v-model="formData.issueDate"
                type="date"
                placeholder="请选择发证日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                style="width: 100%"
                :disabled="isViewMode"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="有效日期">
              <el-date-picker
                v-model="formData.validDate"
                type="date"
                placeholder="请选择有效日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                style="width: 100%"
                :disabled="isViewMode"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注">
          <el-input
            v-model="formData.remark"
            type="textarea"
            :rows="2"
            placeholder="请输入备注信息"
            :readonly="isViewMode"
          />
        </el-form-item>
        <el-form-item label="上传附件">
          <el-upload
            ref="uploadRef"
            :file-list="fileList"
            :on-change="handleFileChange"
            :on-remove="handleFileRemove"
            :before-upload="beforeUpload"
            :auto-upload="false"
            :disabled="isViewMode"
            multiple
            drag
          >
            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
            <div class="el-upload__text">
              将文件拖到此处，或<em>点击上传</em>
            </div>
            <template #tip>
              <div class="el-upload__tip">
                支持 jpg/png/gif/pdf/doc/docx 文件，且不超过 10MB
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleDialogClose">{{ isViewMode ? '关闭' : '取消' }}</el-button>
          <el-button v-if="!isViewMode" type="primary" @click="handleSubmit" :loading="submitLoading">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 附件查看对话框 -->
    <el-dialog v-model="attachmentDialogVisible" title="附件列表" width="600px">
      <el-table :data="currentAttachments" stripe>
        <el-table-column prop="name" label="文件名" />
        <el-table-column prop="size" label="文件大小" width="120">
          <template #default="{ row }">
            {{ formatFileSize(row.size) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100">
          <template #default="{ row }">
            <el-button type="text" @click="handleDownload(row)">下载</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <!-- 导入对话框 -->
    <el-dialog v-model="importDialogVisible" title="导入Excel" width="400px">
      <el-upload
        ref="importUploadRef"
        :auto-upload="false"
        :on-change="handleImportFileChange"
        accept=".xlsx,.xls"
        drag
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">
          将Excel文件拖到此处，或<em>点击上传</em>
        </div>
        <template #tip>
          <div class="el-upload__tip">
            <div>
              <el-link type="primary" :underline="false" @click="handleDownloadTemplate">
                下载导入模板
              </el-link>
            </div>
            <div style="color: red; margin-top: 5px;">
              只能上传 xlsx/xls 文件
            </div>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="importDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleImportSubmit" :loading="importLoading">确定导入</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { UploadFilled } from '@element-plus/icons-vue'
import type { FormInstance, UploadFile, UploadFiles } from 'element-plus'
import { SpecialPersonnelApi } from '@/api/safe/special'
import type { SpecialPersonnelVO, SpecialPersonnelPageReqVO } from '@/api/safe/special'
import download from '@/utils/download'

// 响应式数据
const loading = ref(false)
const submitLoading = ref(false)
const importLoading = ref(false)
const dialogVisible = ref(false)
const attachmentDialogVisible = ref(false)
const importDialogVisible = ref(false)
const isViewMode = ref(false)
const tableData = ref<SpecialPersonnelVO[]>([])
const selectedRows = ref<SpecialPersonnelVO[]>([])
const currentAttachments = ref<any[]>([])
const fileList = ref<UploadFile[]>([])
const formRef = ref<FormInstance>()
const uploadRef = ref()
const importUploadRef = ref()
const importFile = ref<File>()

// 分页数据
const pagination = reactive({
  pageNo: 1,
  pageSize: 10,
  total: 0
})

// 搜索表单
const searchForm = reactive<SpecialPersonnelPageReqVO>({
  name: '',
  position: '',
  certificateNumber: '',
  remark: '',
  issueDateRange: [],
  validDateRange: []
})

// 表单数据
const formData = reactive<SpecialPersonnelVO>({
  id: undefined,
  name: '',
  position: '',
  trainingContent: '',
  certificateNumber: '',
  issueDate: '',
  validDate: '',
  attachments: [],
  remark: ''
})

// 表单验证规则（所有字段都设置为非必填）
const formRules = {
  // 所有字段都设置为非必填
}

// 计算属性
const dialogTitle = computed(() => {
  if (isViewMode.value) {
    return '查看特种岗位人员'
  }
  return formData.id ? '编辑特种岗位人员' : '新增特种岗位人员'
})

// 生命周期
onMounted(() => {
  getList()
})

// 方法
const getList = async () => {
  loading.value = true
  try {
    const params = {
      ...searchForm,
      pageNo: pagination.pageNo,
      pageSize: pagination.pageSize,
      issueDateStart: searchForm.issueDateRange?.[0],
      issueDateEnd: searchForm.issueDateRange?.[1],
      validDateStart: searchForm.validDateRange?.[0],
      validDateEnd: searchForm.validDateRange?.[1]
    }
    delete params.issueDateRange
    delete params.validDateRange

    const response = await SpecialPersonnelApi.getSpecialPersonnelPage(params)
    console.log('API响应数据:', response)

    // 检查响应数据结构
    if (response && response.list !== undefined) {
      tableData.value = response.list || []
      pagination.total = response.total || 0
    } else {
      console.error('API返回数据格式异常:', response)
      tableData.value = []
      pagination.total = 0
      ElMessage.warning('数据格式异常，请检查后端接口')
    }
  } catch (error) {
    console.error('获取数据失败:', error)
    tableData.value = []
    pagination.total = 0
    ElMessage.error('获取数据失败，请重试')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.pageNo = 1
  getList()
}

const handleReset = () => {
  Object.assign(searchForm, {
    name: '',
    position: '',
    certificateNumber: '',
    remark: '',
    issueDateRange: [],
    validDateRange: []
  })
  handleSearch()
}

const handleAdd = () => {
  resetForm()
  isViewMode.value = false
  dialogVisible.value = true
}

const handleRowClick = (row: SpecialPersonnelVO) => {
  handleView(row)
}

const handleEdit = (row: SpecialPersonnelVO) => {
  resetForm()
  isViewMode.value = false
  Object.assign(formData, { ...row })
  if (row.attachments) {
    fileList.value = row.attachments.map((item, index) => ({
      name: item.name,
      url: item.url,
      size: item.size,
      status: 'success' as const,
      uid: Date.now() + index
    }))
  }
  dialogVisible.value = true
}

const handleView = (row: SpecialPersonnelVO) => {
  resetForm()
  isViewMode.value = true
  Object.assign(formData, { ...row })
  if (row.attachments) {
    fileList.value = row.attachments.map((item, index) => ({
      name: item.name,
      url: item.url,
      size: item.size,
      status: 'success' as const,
      uid: Date.now() + index
    }))
  }
  dialogVisible.value = true
}

const handleDelete = async (row: SpecialPersonnelVO) => {
  try {
    await ElMessageBox.confirm('确定要删除这条记录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    await SpecialPersonnelApi.deleteSpecialPersonnel(row.id!)
    ElMessage.success('删除成功')
    getList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
    }
  }
}

const handleSubmit = async () => {
  try {
    submitLoading.value = true

    // 处理附件数据
    const submitData = {
      ...formData,
      attachments: fileList.value.map(file => ({
        name: file.name || '',
        url: file.url || '',
        size: file.size || 0
      }))
    }

    if (submitData.id) {
      await SpecialPersonnelApi.updateSpecialPersonnel(submitData)
      ElMessage.success('更新成功')
    } else {
      await SpecialPersonnelApi.createSpecialPersonnel(submitData)
      ElMessage.success('创建成功')
    }

    dialogVisible.value = false
    getList()
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('提交失败，请重试')
  } finally {
    submitLoading.value = false
  }
}

const handleDialogClose = () => {
  dialogVisible.value = false
  isViewMode.value = false
  resetForm()
}

const resetForm = () => {
  Object.assign(formData, {
    id: undefined,
    name: '',
    position: '',
    trainingContent: '',
    certificateNumber: '',
    issueDate: '',
    validDate: '',
    attachments: [],
    remark: ''
  })
  fileList.value = []
  formRef.value?.clearValidate()
}

const handleSelectionChange = (selection: SpecialPersonnelVO[]) => {
  selectedRows.value = selection
}

const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  getList()
}

const handleCurrentChange = (page: number) => {
  pagination.pageNo = page
  getList()
}

const handleViewAttachments = (row: SpecialPersonnelVO) => {
  currentAttachments.value = row.attachments || []
  attachmentDialogVisible.value = true
}

const handleDownload = (attachment: any) => {
  window.open(attachment.url, '_blank')
}

const handleExport = async () => {
  try {
    const params = {
      ...searchForm,
      issueDateStart: searchForm.issueDateRange?.[0],
      issueDateEnd: searchForm.issueDateRange?.[1],
      validDateStart: searchForm.validDateRange?.[0],
      validDateEnd: searchForm.validDateRange?.[1]
    }
    delete params.issueDateRange
    delete params.validDateRange

    const data = await SpecialPersonnelApi.exportSpecialPersonnelExcel(params)
    download.excel(data, '特种岗位人员台账.xls')
    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败，请重试')
  }
}

const handleDownloadTemplate = async () => {
  try {
    const data = await SpecialPersonnelApi.downloadImportTemplate()
    download.excel(data, '特种岗位人员台账导入模板.xls')
    ElMessage.success('模板下载成功')
  } catch (error) {
    console.error('模板下载失败:', error)
    ElMessage.error('模板下载失败，请重试')
  }
}

const handleImport = () => {
  importDialogVisible.value = true
}

const handleImportFileChange = (file: UploadFile) => {
  importFile.value = file.raw
}

const handleImportSubmit = async () => {
  if (!importFile.value) {
    ElMessage.warning('请选择要导入的文件')
    return
  }

  try {
    importLoading.value = true
    await SpecialPersonnelApi.importSpecialPersonnelExcel(importFile.value)
    ElMessage.success('导入成功')
    importDialogVisible.value = false
    getList()
  } catch (error) {
    console.error('导入失败:', error)
  } finally {
    importLoading.value = false
  }
}

const handleFileChange = (_file: UploadFile, _files: UploadFiles) => {
  // 这里可以添加文件上传逻辑
}

const handleFileRemove = (_file: UploadFile) => {
  // 文件移除逻辑
}

const beforeUpload = (file: File) => {
  const isValidType = ['image/jpeg', 'image/png', 'image/gif', 'application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'].includes(file.type)
  const isValidSize = file.size / 1024 / 1024 < 10

  if (!isValidType) {
    ElMessage.error('文件格式不正确!')
    return false
  }
  if (!isValidSize) {
    ElMessage.error('文件大小不能超过 10MB!')
    return false
  }
  return true
}

const getValidDateClass = (validDate: string) => {
  if (!validDate) return ''

  const today = new Date()
  const valid = new Date(validDate)
  const diffTime = valid.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' // 即将过期
  }
  return ''
}

const formatFileSize = (size: number) => {
  if (!size) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(size) / Math.log(k))
  return parseFloat((size / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}
</script>

<style scoped>
.special-personnel-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.search-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.text-red-500 {
  color: #f56c6c;
}

.text-orange-500 {
  color: #e6a23c;
}
</style>
