<!-- 考核填报弹窗 -->
<script lang="ts" setup name="FillingDialog">
import type { FormInstance, FormRules } from 'element-plus'
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import { uploadApi } from '@/api/common'
import { filling } from '@/api/home/filling/filling'
// ----------------------- 以下是字段定义 emits props ---------------------
const emits = defineEmits(['closeRefresh'])
const dialogVisible = ref(false)
// 显示标题
const textMap: { [key: string]: string } = {
  update: '编辑',
  create: '新增',
}
const rowData = ref({})
const defaultFormData = {
  assDesc: '', // 考核说明
  fileId: '',
  fileName: '',
  score: '',
}
// 表单数据对象
const formData = reactive({ ...defaultFormData })

// ---------------表单提交--------------------------------
// 表单对象
const dataFormRef = ref<FormInstance>()
// 校验规则
const rules: FormRules = reactive({
  assDesc: [{ required: true, message: '考核说明不可为空', trigger: ['blur', 'change'] }],
  score: [{ required: true, message: '考核得分不可为空', trigger: ['blur', 'change'] }],
})

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) { return }
  await formEl.validate((valid, fields) => {
    if (valid) {
      const data = {
        assDesc: formData.assDesc,
        fileId: formData.fileId,
        fileName: formData.fileName,
        score: formData.score,
        id: rowData.value.id,
      }
      filling(data).then((res) => {
        ElMessage.success('填报成功')
        dialogVisible.value = false
        resetForm()
        emits('closeRefresh')
      })
    }
  })
}
// 重置表单
function resetForm() {
  const form = formData
  const keys = Object.keys(formData)
  keys.forEach((key) => {
    form[key] = defaultFormData[key]
  })
  Object.assign(formData, form)
  nextTick(() => {
    dataFormRef.value?.clearValidate()
  })
}
// ----------初始化、关闭对话框相关-----------------
function initDialog(row: any) {
  dialogVisible.value = true
  rowData.value = row
  resetForm()
}

// 关闭弹窗
function dialogClose() {
  resetForm()
  dialogVisible.value = false
}
// ----------------------- 以下是暴露的方法内容 ----------------------------
defineExpose({ initDialog })
const fileRef = ref() // 文件上传input
const onFileChange = (event: any) => {
  if (event.target.files?.length !== 0) {
    // 创建formdata对象
    const fd = new FormData()
    const loading = ElLoading.service({
      lock: true,
      background: 'rgba(255, 255, 255, 0.8)',
    })
    fd.append('file', event.target.files[0])
    uploadApi(fd).then((res) => {
      if (res.code === 200) {
        formData.fileId = formData.fileId ? `${formData.fileId},${res.data.fileId}` : res.data.fileId
        formData.fileName = formData.fileName ? `${formData.fileName},${res.data.fileName}` : res.data.fileName
        // 重置当前验证
        // dataFormRef.value?.clearValidate('minioFileName')
        ElMessage.success('文件上传成功')
        fileRef.value.value = ''
        loading.close()
      }
      else {
        // ElMessage.error(res.message)
        loading.close()
      }
    })
  }
}
// 上传
const upload = () => {
  fileRef.value.click()
}
// 删除上传的文件
const deleteFile = (fileName: string) => {
  const data = formData.fileName.split(',')
  const ids = formData.fileId.split(',')
  const filterData = data.filter(item => item !== fileName)
  const filterid = ids.filter((item, index) => index !== data.findIndex(citem => citem === fileName))
  formData.fileId = filterid.length ? filterid.join(',') : ''
  formData.fileName = filterData.length ? filterData.join(',') : ''
}
</script>

<template>
  <el-dialog
    v-model="dialogVisible"
    title="填报"
    width="50%"
    :before-close="dialogClose"
    append-to-body
    :open-delay="0"
    :close-on-click-modal="false"
  >
    <el-form
      ref="dataFormRef" :model="formData" :rules="rules" label-position="left" label-width="110px" class="form-container"
      size="default" @submit.prevent
    >
      <el-row :gutter="24">
        <el-col :span="24" class="grid-cell">
          <el-form-item label="考核得分" prop="score" class="required">
            <el-input v-model.trim="formData.score" type="text" placeholder="0-12之间" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="24" class="grid-cell">
          <el-form-item label="考核说明" prop="assDesc" class="required">
            <el-input v-model.trim="formData.assDesc" type="textarea" placeholder="考核说明" :rows="4" maxlength="100" show-word-limit />
          </el-form-item>
        </el-col>
        <el-col :span="24" class="grid-cell">
          <el-form-item label="附件上传">
            <show-photo :minio-file-name="formData.fileName" :minio-file-id="formData.fileId" @delete="deleteFile" />
            <input ref="fileRef" style="display: none;" type="file" accept="application/msword,application/pdf" @change="onFileChange">
            <el-button v-if="!$route.path.includes('detail')" type="primary" @click="upload">
              上传
            </el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submitForm(dataFormRef)">
          保存
        </el-button>
        <el-button @click="dialogClose">
          取消
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style lang="scss" scoped>
.form-container {
  width: 100%;

  .full-width-input {
    width: 100%;
  }
}
</style>
