<template>
  <div class="app-container">
    <div class="filter-container">
      <el-form :model="queryParams" ref="queryFormRef" :inline="true" class="search-form">
        <el-form-item label="姓名" prop="userName">
          <UserSelect v-model="queryParams.userId" placeholder="请输入姓名搜索" style="width: 200px" />
        </el-form-item>

        <el-form-item label="证书等级" prop="certLevel">
          <el-select v-model="queryParams.certLevel" placeholder="请选择证书等级" clearable style="width: 200px">
            <el-option v-for="dict in sys_user_qualification_level" :key="dict.value" :label="dict.label" :value="dict.label" />
          </el-select>
        </el-form-item>

        <el-form-item label="发证时间" prop="issueDate" style="width: 300px">
          <el-date-picker v-model="queryParams.issueDate" value-format="YYYY-MM-DD" type="date" placeholder="请选择发证时间" clearable />
        </el-form-item>

        <el-form-item label="到期日期" prop="expiryDate" style="width: 300px">
          <el-date-picker v-model="queryParams.expiryDate" value-format="YYYY-MM-DD" type="date" placeholder="请选择到期日期" clearable />
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-input v-model="queryParams.status" placeholder="请输入状态" clearable style="width: 200px" />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">查询</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="operation-container">
      <el-button type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
      <el-button type="info" plain icon="Upload" @click="handleImport">导入</el-button>
      <el-button type="warning" plain icon="Download" @click="handleExport">导出</el-button>
    </div>

    <el-table v-loading="loading" :data="list" border fit highlight-current-row style="width: 100%; margin-top: 20px;">
      <el-table-column label="序号" type="index" width="60" align="center">
        <template #default="scope">
          {{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="姓名" prop="personName" align="center" min-width="100" />
      <el-table-column label="单位" prop="unitName" align="center" min-width="120" />
      <el-table-column label="证书等级" prop="certLevel" align="center" min-width="100">
        
      </el-table-column>
      <el-table-column label="发证时间" prop="issueDate" align="center" min-width="120" />
      <el-table-column label="证书编号" prop="certNo" align="center" min-width="150" show-overflow-tooltip />
      <el-table-column label="理论考核成绩" prop="theoryScore" align="center" min-width="120" />
      <el-table-column label="实操考核成绩" prop="practiceScore" align="center" min-width="120" />
      <el-table-column label="评定成绩" prop="evalScore" align="center" min-width="100" />
      <el-table-column label="服务期（月）" prop="serviceMonths" align="center" min-width="110" />
      <el-table-column label="到期日期" prop="expiryDate" align="center" min-width="120" />
      <el-table-column label="状态" prop="status" align="center" min-width="90">
      
      </el-table-column>
      <el-table-column label="到期天数" prop="expireDays" align="center" min-width="100">
        <template #default="scope">
          <span :style="{ color: scope.row.expireDays <= 30 ? '#f56c6c' : scope.row.expireDays <= 90 ? '#e6a23c' : '#67c23a' }">
            {{ scope.row.expireDays }}天
          </span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="150" fixed="right">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改证书信息对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body destroy-on-close>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="姓名" prop="userId">
          <UserSelect v-model="form.userId" placeholder="请选择姓名" style="width: 100%" />
        </el-form-item>
        <el-form-item label="单位" prop="unitName">
          <el-input v-model="form.unitName" placeholder="请输入单位" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select v-model="form.gender" placeholder="请选择性别" clearable style="width: 100%">
            <el-option label="男" value="0" />
            <el-option label="女" value="1" />
          </el-select>
        </el-form-item>
        <el-form-item label="出生日期" prop="birthDate">
          <el-date-picker v-model="form.birthDate" value-format="YYYY-MM-DD" type="date" placeholder="请选择出生日期" style="width: 100%" />
        </el-form-item>
        <el-form-item label="身份证号" prop="idCard">
          <el-input v-model="form.idCard" placeholder="请输入身份证号" />
        </el-form-item>
        <el-form-item label="证书等级" prop="certLevel">
          <el-select v-model="form.certLevel" placeholder="请选择证书等级" clearable style="width: 100%">
            <el-option v-for="dict in sys_user_qualification_level" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="发证时间" prop="issueDate">
          <el-date-picker v-model="form.issueDate" value-format="YYYY-MM-DD" type="date" placeholder="请选择发证时间" style="width: 100%" />
        </el-form-item>
        <el-form-item label="证书编号" prop="certNo">
          <el-input v-model="form.certNo" placeholder="请输入证书编号" />
        </el-form-item>
        <el-form-item label="理论考核成绩" prop="theoryScore">
          <el-input v-model="form.theoryScore" placeholder="请输入理论考核成绩" />
        </el-form-item>
        <el-form-item label="实操考核成绩" prop="practiceScore">
          <el-input v-model="form.practiceScore" placeholder="请输入实操考核成绩" />
        </el-form-item>
        <el-form-item label="评定成绩" prop="evalScore">
          <el-input v-model="form.evalScore" placeholder="请输入评定成绩" />
        </el-form-item>
        <el-form-item label="用工形式" prop="employmentType">
          <el-input v-model="form.employmentType" placeholder="请输入用工形式" />
        </el-form-item>
        <el-form-item label="服务期（月）" prop="serviceMonths">
          <el-input-number v-model="form.serviceMonths" :min="0" placeholder="请输入服务期（月）" style="width: 100%" />
        </el-form-item>
        <el-form-item label="到期日期" prop="expiryDate">
          <el-date-picker v-model="form.expiryDate" value-format="YYYY-MM-DD" type="date" placeholder="请选择到期日期" style="width: 100%" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-input v-model="form.status" placeholder="请输入状态" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
      <el-upload ref="uploadRef" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url"
        :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess"
        :auto-upload="false" 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 text-center">
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline"
              @click="downloadTemplate">下载模板</el-link>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="QualificationSummary">
import { ref, reactive, getCurrentInstance, onMounted } from 'vue'
import { UploadFilled } from '@element-plus/icons-vue'
import UserSelect from '@/components/UserSelect/index.vue'
import { listQualificationSummary, getQualificationSummary, addQualificationSummary, updateQualificationSummary, delQualificationSummary, exportQualificationSummary } from '@/api/ledgerManage/qualificationSummary'
import { getToken } from '@/utils/auth'

const { proxy } = getCurrentInstance()

const { sys_user_qualification_level, certificate_status } = proxy.useDict('sys_user_qualification_level', 'certificate_status')

const loading = ref(false)
const total = ref(0)
const list = ref([])
const queryFormRef = ref(null)
const formRef = ref(null)

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  userId: '',
  certLevel: '',
  issueDate: '',
  expiryDate: '',
  status: ''
})

const upload = reactive({
  open: false,
  title: '',
  isUploading: false,
  url: '',
  headers: {
    Authorization: 'Bearer ' + getToken()
  }
})

const title = ref('')
const open = ref(false)

const form = ref({
  id: undefined,
  userId: '',
  unitName: '',
  gender: '',
  birthDate: '',
  idCard: '',
  certLevel: '',
  issueDate: '',
  certNo: '',
  theoryScore: '',
  practiceScore: '',
  evalScore: '',
  employmentType: '',
  serviceMonths: undefined,
  expiryDate: '',
  status: '',
  remark: ''
})

const rules = reactive({
  userId: [{ required: true, message: '请选择姓名', trigger: 'change' }],
  certLevel: [{ required: true, message: '请选择证书等级', trigger: 'change' }],
  certNo: [{ required: true, message: '请输入证书编号', trigger: 'blur' }],
  issueDate: [{ required: true, message: '请选择发证时间', trigger: 'change' }],
  expiryDate: [{ required: true, message: '请选择到期日期', trigger: 'change' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }]
})

const getList = async () => {
  loading.value = true
  try {
    const res = await listQualificationSummary(queryParams)
    list.value = res.rows || []
    total.value = res.total || 0
  } finally {
    loading.value = false
  }
}

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

const resetQuery = () => {
  queryFormRef.value.resetFields()
  queryParams.userId = ''
  queryParams.certLevel = ''
  queryParams.issueDate = ''
  queryParams.expiryDate = ''
  queryParams.status = ''
  handleQuery()
}

const handleAdd = () => {
  reset()
  open.value = true
  title.value = '添加证书信息'
}

const handleUpdate = async (row) => {
  reset()
  const res = await getQualificationSummary(row.id)
  form.value = res.data || {}
  open.value = true
  title.value = '修改证书信息'
}

const handleDelete = (row) => {
  proxy.$modal.confirm('是否确认删除证书信息编号为"' + row.id + '"的数据项？').then(() => {
    return delQualificationSummary(row.id)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess('删除成功')
  }).catch(() => { })
}

const submitForm = async () => {
  const valid = await formRef.value.validate().catch(() => false)
  if (!valid) return

  loading.value = true
  try {
    if (form.value.id) {
      await updateQualificationSummary(form.value)
      proxy.$modal.msgSuccess('修改成功')
    } else {
      await addQualificationSummary(form.value)
      proxy.$modal.msgSuccess('新增成功')
    }
    open.value = false
    getList()
  } finally {
    loading.value = false
  }
}

const cancel = () => {
  open.value = false
  reset()
}

const reset = () => {
  form.value = {
    id: undefined,
    userId: '',
    unitName: '',
    gender: '',
    birthDate: '',
    idCard: '',
    certLevel: '',
    issueDate: '',
    certNo: '',
    theoryScore: '',
    practiceScore: '',
    evalScore: '',
    employmentType: '',
    serviceMonths: undefined,
    expiryDate: '',
    status: '',
    remark: ''
  }
  formRef.value && formRef.value.resetFields()
}

const handleExport = () => {
  proxy.download(
    'ledger/certificate/export',
    queryParams,
    `资质汇总表_${new Date().getTime()}.xlsx`,
    'post'
  )
}

const handleImport = () => {
  upload.title = '证书信息导入'
  upload.url = import.meta.env.VITE_APP_BASE_API + '/ledger/certificate/importData'
  upload.open = true
}

const downloadTemplate = () => {
  proxy.download(
    'ledger/certificate/importTemplate',
    {},
    `资质汇总表模板_${new Date().getTime()}.xlsx`,
    'post'
  )
}

const handleFileUploadProgress = () => {
  upload.isUploading = true
}

const handleFileSuccess = (response, file) => {
  upload.open = false
  upload.isUploading = false
  proxy.$refs.uploadRef.handleRemove(file)
  proxy.$alert(
    "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
      response.msg +
      '</div>',
    '导入结果',
    { dangerouslyUseHTMLString: true }
  )
  getList()
}

const submitFileForm = () => {
  proxy.$refs.uploadRef.submit()
}

onMounted(() => {
  getList()
})
</script>

<style scoped lang="less">
.app-container {
  padding: 20px;
}

.filter-container {
  margin-bottom: 10px;
}

.operation-container {
  margin-top: 10px;
}
</style>
