<!-- 证书记录 -->
<script lang="ts" setup name="person">
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import addDialog from './components/addRecord.vue'
import type { StaffListType, StaffType } from './person-interface'
import { CertificateListList, getCertificateList, getCertificateRemind, getCertificateRemove, getCertificateUpload } from '@/api/measure/person'
// import { uploadApi } from '@/api/system/notice'
import { getDeptTreeList } from '@/api/system/dept'
import { exportFile } from '@/utils/exportUtils'
import type { DeptTreeNode } from '@/views/system/dept/dept-interface'
const props = defineProps({
  isRemind: {
    type: Boolean,
    default: false,
  },
  authority: {
    type: String,
    default: 'certificateLog',
  },
})
const { proxy } = getCurrentInstance() as any
const searchQuery = reactive<StaffListType>({
  staffNo: '', // 人员编号
  name: '', // 姓名
  deptId: '', // 工作部门
  // major: '', // 计量专业
  verifierCertificateNo: '', // 证书号
  certificateStatus: '', // 证书状态
  limit: 10,
  offset: 1,
}) // 查询参数
const loadingTable = ref<boolean>(false) // 表格loading
const total = ref<number>(0) // 数据总条数
const columns = ref([
  { text: '人员编号', value: 'staffNo', align: 'center', width: '150' },
  { text: '姓名', value: 'name', align: 'center', width: '80' },
  { text: '性别', value: 'sex', align: 'center', width: '55' },
  { text: '工作部门', value: 'deptId', align: 'center', width: '140' },
  { text: '技术职务', value: 'technologyJob', align: 'center', width: '120' },
  { text: '行政职务', value: 'administrationJob', align: 'center', width: '90' },
  { text: '证书号', value: 'certificateNo', align: 'center', width: '150' },
  { text: '发证单位', value: 'certificateCompany', align: 'center', width: '90' },
  { text: '发证日期', value: 'certificateDate', align: 'center', width: '200' },
  { text: '证书有效日期', value: 'certificateDate', align: 'center', width: '200' },
  { text: '证书状况', value: 'certificateStatus', align: 'center', width: '85' },
]) // 表格
const certificateStatusList = ref([
  {
    name: '全部',
    id: 'status01',
    value: '',
  },
  {
    name: '已失效',
    id: 'status02',
    value: '1',
  },
  {
    name: '正常',
    id: 'status02',
    value: '0',
  },
])
const printObj = ref({
  id: 'print', // 需要打印元素的id
  popTitle: '计量人员列表', // 打印配置页上方的标题
  extraHead: '', // 最上方的头部文字，附加在head标签上的额外标签，使用逗号分割
  preview: false, // 是否启动预览模式，默认是false
  previewBeforeOpenCallback() { console.log('正在加载预览窗口！') }, // 预览窗口打开之前的callback
  previewOpenCallback() { console.log('已经加载完预览窗口，预览打开了！') }, // 预览窗口打开时的callback
  beforeOpenCallback() { console.log('开始打印之前！') }, // 开始打印之前的callback
  openCallback() { console.log('执行打印了！') }, // 调用打印时的callback
  closeCallback() { console.log('关闭了打印工具！') }, // 关闭打印的callback(无法区分确认or取消)
  clickMounted() { console.log('点击v-print绑定的按钮了！') },
  standard: '',
  extarCss: '',
})
const list = ref([]) // 表格数据
const addRef = ref() // 添加/编辑/详情/组件
const dialogVisible = ref<boolean>(false) // 添加组件的显示与隐藏
// 获取所有部门
const deptList = ref<DeptTreeNode[]>([])
const getDeptList = async () => {
  getDeptTreeList().then((res) => {
    deptList.value = res.data
  })
}
// 获取数据列表
const getList = () => {
  loadingTable.value = true
  getCertificateList(searchQuery).then((res) => {
    if (res.code === 200) {
      res.data.records = res.data.records.map(item => ({ ...item, sex: item.sex == '1' ? '男' : '女', certificateStatus: item.certificateStatus == '0' ? '正常' : '已失效' }))
      list.value = res.data.records
      total.value = Number(res.data.total)
    }
    loadingTable.value = false
  }).catch((_) => {
    loadingTable.value = false
  })
}
// 页数发生变化后的操作，可能是页码变化，可能是每页容量变化，此函数必写
const changePage = (val: { size?: number; page?: number }) => {
  if (val && val.size) {
    searchQuery.limit = val.size
  }
  if (val && val.page) {
    searchQuery.offset = val.page
  }
  getList()
}
// 详情
const detail = (row: StaffType) => {
  dialogVisible.value = true
  addRef.value.initDialog({
    ...row,
    title: '详情',
  })
}
// 编辑
const update = (row: StaffType) => {
  dialogVisible.value = true
  addRef.value.initDialog({
    ...row,
    title: '编辑',
  })
}

// 删除
const remove = (row: StaffType) => {
  ElMessageBox.confirm(
    `确认删除${row.name}吗？`,
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    },
  )
    .then(() => {
      getCertificateRemove({ id: row.id as string }).then((res) => {
        if (res.code === 200) {
          ElMessage({
            type: 'success',
            message: '删除成功',
          })
          getList()
        }
      })
    })
}
// 提醒
const remind = (row: StaffType) => {
  ElMessageBox.confirm(
    `确认提醒${row.name}吗？`,
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    },
  ).then(() => {
    getCertificateRemind({ id: row.id }).then((res) => {
      if (res.code == 200) {
        ElMessage({
          type: 'success',
          message: '操作成功',
        })
        getList()
      }
    })
  })
}
// 搜索
const search = () => {
  getList()
}
// 重置
const reset = () => {
  searchQuery.staffNo = ''
  searchQuery.name = ''
  searchQuery.deptId = ''
  searchQuery.certificateStatus = ''
  searchQuery.verifierCertificateNo = ''
  getList()
}
// 模板下载
const templateDownload = () => {

}
// 新增
const add = () => {
  dialogVisible.value = true
  addRef.value.initDialog({
    title: '新建',
  })
}
// 导出
const exportExcelBtn = () => {
  const loading = ElLoading.service({
    lock: true,
    text: 'Loading',
    background: 'rgba(255, 255, 255, 0.8)',
  })
  CertificateListList({ ...searchQuery }).then((res) => {
    exportFile(res.data, '证书记录列表')
    loading.close()
  }).catch((_) => {
    loading.close()
  })
}
// 打印
const print = () => {

}
const fileRef = ref() // 文件上传input
const onFileChange = (event: any) => {
  // 原生上传图片
  // console.log(event.target.files)
  // if (event.target.files[0].type === 'application/pdf') {
  if (event.target.files?.length !== 0) {
    // 创建formdata对象
    const fd = new FormData()
    fd.append('multipartFile', event.target.files[0])
    getCertificateUpload(fd).then((res) => {
      if (res.code === 200) {
        ElMessage.success('上传成功')
      }
      else {
        ElMessage.error(res.message)
      }
    })
  }
//   }
//   else {
//     ElMessage.error('请上传pdf格式')
//   }
}
// 批量导入
const batchImport = () => {
  fileRef.value.click()
}
// 传给子组件的刷新事件
const refreshDta = () => {
  getList()
  dialogVisible.value = false
}
onMounted(() => {
  getDeptList()
  getList()
})
</script>

<template>
  <div>
    <add-dialog v-show="dialogVisible" ref="addRef" @reset-data="refreshDta" />
    <!-- 布局 -->
    <app-container v-show="!dialogVisible">
      <!-- 筛选条件 -->
      <search-area :need-clear="true" @search="search" @clear="reset">
        <search-item>
          <el-input v-model="searchQuery.staffNo" placeholder="人员编号" clearable class="w-50 m-2" />
        </search-item>
        <search-item>
          <el-input v-model="searchQuery.name" placeholder="姓名" clearable class="w-50 m-2" />
        </search-item>
        <search-item>
          <el-select v-model="searchQuery.deptId" class="m-2" placeholder="工作部门">
            <el-option
              v-for="item in deptList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </search-item>
        <search-item>
          <el-input v-model="searchQuery.verifierCertificateNo" placeholder="证书号" clearable class="w-50 m-2" />
        </search-item>
        <search-item>
          <el-select v-model="searchQuery.certificateStatus" class="m-2" placeholder="证书状况">
            <el-option
              v-for="item in certificateStatusList"
              :key="item.id"
              :label="item.name"
              :value="item.value"
            />
          </el-select>
        </search-item>
      </search-area>
      <table-container>
        <!-- 表头区域 -->
        <template #btns-right>
          <input v-show="(searchQuery.limit === 0)" ref="fileRef" type="file" multiple @change="onFileChange">
          <el-button v-if="!props.isRemind && proxy.hasPerm(`/measure/person/${authority}/import`)" type="primary" @click="batchImport">
            批量导入
          </el-button>
          <el-button v-if="!props.isRemind && proxy.hasPerm(`/measure/person/${authority}/mould`)" type="primary" @click="templateDownload">
            模板下载
          </el-button>
          <el-button v-if="!props.isRemind && proxy.hasPerm(`/measure/person/${authority}/add`)" type="primary" @click="add">
            新建
          </el-button>
          <el-button v-if="proxy.hasPerm(`/measure/person/${authority}/export`)" type="primary" @click="exportExcelBtn">
            导出
          </el-button>
          <el-button v-if="proxy.hasPerm(`/measure/person/${authority}/print`)" v-print="printObj" type="primary" @click="print">
            打印
          </el-button>
        </template>
        <!-- 表格区域 -->
        <normal-table
          id="print"
          :data="list" :total="total" :columns="columns as any"
          :is-showmulti-select="true"
          :query="{ limit: searchQuery.limit, offset: searchQuery.offset }"
          :list-loading="loadingTable"
          @change="changePage"
        >
          <template #preColumns>
            <el-table-column label="序号" width="55" align="center">
              <template #default="scope">
                {{ (searchQuery.offset - 1) * searchQuery.limit + scope.$index + 1 }}
              </template>
            </el-table-column>
          </template>
          <template #columns>
            <el-table-column fixed="right" label="操作" align="center" width="150">
              <template #default="{ row }">
                <el-button v-if="props.isRemind && proxy.hasPerm(`/measure/person/${authority}/remind`)" size="small" type="primary" link @click="remind(row)">
                  提醒
                </el-button>
                <el-button v-if="!props.isRemind && proxy.hasPerm(`/measure/person/${authority}/update`)" size="small" type="primary" link @click="update(row)">
                  编辑
                </el-button>
                <el-button v-if="proxy.hasPerm(`/measure/person/${authority}/detail`)" size="small" type="primary" link @click="detail(row)">
                  详情
                </el-button>
                <el-button v-if="props.isRemind && proxy.hasPerm(`/measure/person/${authority}/delete`)" size="small" type="primary" link @click="remove(row)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </template>
        </normal-table>
      </table-container>
    </app-container>
  </div>
</template>

<style lang="scss" scoped>
.normal-input {
  width: 130px !important;
}

.normal-date {
  width: 130px !important;
}

.normal-select {
  width: 130px !important;
}

:deep(.el-table__header) {
  background-color: #bbb;
}
</style>
