<template>
  <el-dialog
    :title="title"
    :close-on-click-modal="false"
    v-model="visible"
    append-to-body
    width="70%">
    <el-form :model="dataForm" :rules="dataRule" ref="dataFormRef" @keyup.enter="() => dataFormSubmit('1')"
             label-width="100px">
      <el-row>
        <el-col :span="8">
          <el-form-item label="招生计划" prop="groupId">
            <el-select v-model="dataForm.groupId" filterable :disabled="!!dataForm.id"
                       placeholder="请选择招生计划">
              <el-option
                v-for="item in planList"
                :key="item.id"
                :label="item.groupName"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="姓名" prop="name">
            <el-input type="text" v-model="dataForm.name" :disabled="type != 1"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="联系人" prop="contactName">
            <el-select 
            v-model="dataForm.contactName" 
            filterable 
            clearable 
            placeholder="" 
            :disabled="!(hasAuth('recruit_recruitprestudent_dj_sure') || dataForm.auditStatus != '20')">
              <el-option
                v-for="item in contactNameList"
                :key="item.teacherNo"
                :label="item.realName+'-'+item.deptCode"
                :value="item.teacherNo">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

   
      <el-row>
        <el-col :span="6">
          <el-form-item label="成绩单" prop="scorePhoto">
            <el-upload
              :action="uploadUrl"
              class="avatar-uploader"
              name="file"
              :headers="headers"
              :data="uploadData"
              :show-file-list="false"
              :before-upload="beforeUpload"
              :http-request="httpRequest"
              :on-success="uploadSuccess">
              <div v-if="dataForm.scorePhoto" class="avatar-wrapper">
                <img :src="baseUrl + dataForm.scorePhoto" class="avatar"/>
              </div>
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="毕业证" prop="graPic">
            <el-upload
              :action="uploadUrl"
              class="avatar-uploader"
              name="file"
              :headers="headers"
              :data="uploadData"
              :show-file-list="false"
              :before-upload="beforeUpload"
              :http-request="httpRequest"
              :on-success="upload2Success">
              <div v-if="dataForm.graPic" class="avatar-wrapper">
                <img :src="baseUrl + dataForm.graPic" class="avatar"/>
              </div>
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="在常营业执照" prop="yyPic">
            <el-upload
              :action="uploadUrl"
              class="avatar-uploader"
              name="file"
              :headers="headers"
              :data="uploadData"
              :show-file-list="false"
              :before-upload="beforeUpload"
              :http-request="httpRequest"
              :on-success="upload3Success">
              <div v-if="dataForm.yyPic" class="avatar-wrapper">
                <img :src="baseUrl + dataForm.yyPic" class="avatar"/>
              </div>
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="在常社保证明" prop="sbPic">
            <el-upload
              :action="uploadUrl"
              class="avatar-uploader"
              name="file"
              :headers="headers"
              :data="uploadData"
              :show-file-list="false"
              :before-upload="beforeUpload"
              :http-request="httpRequest"
              :on-success="upload5Success">
              <div v-if="dataForm.sbPic" class="avatar-wrapper">
                <img :src="baseUrl + dataForm.sbPic" class="avatar"/>
              </div>
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        
        <el-col >
          <el-form-item label="在常租赁合同/房产证明" prop="housePic">
            <el-upload
              :action="uploadUrl"
              list-type="picture-card"
              name="file"
              :headers="headers"
              :limit="5"
              :data="uploadData"
              :file-list="houseList"
              :before-upload="beforeUpload"
              :on-preview="handlePictureCardPreview"
              :on-remove="remove4Handler"
              :http-request="httpRequest"
              :on-success="upload4Success">
              <el-icon class="avatar-uploader-icon"><Plus /></el-icon>
              <template #tip>
                <div>最多上传5张</div>
              </template>
            </el-upload>
          </el-form-item>
        </el-col>
      
        <el-col>
          <el-form-item label="户口本" prop="householdPic">
            <el-upload
              :action="uploadUrl"
              list-type="picture-card"
              name="file"
              :headers="headers"
              :limit="5"
              :data="uploadData"
              :file-list="hkPicList"
              :before-upload="beforeUpload"
              :on-preview="handlePictureCardPreview"
              :on-remove="remove6Handler"
              :http-request="httpRequest"
              :on-success="upload6Success">
              <el-icon class="avatar-uploader-icon"><Plus /></el-icon>
              <template #tip>
                <div>最多上传5张</div>
              </template>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="材料审核意见" prop="zlshRemark">
            <el-input v-model="dataForm.zlshRemark" placeholder="请输入审核意见" type="textarea" :rows="2" ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="dataFormSubmit('1',false)" v-if="hasAuth('recruit_recruitstudentsignup_edit') && canSubmit">保存</el-button>
        <el-button type="success" icon="CircleCheck" @click="dataFormSubmit('2',false)" v-if="hasAuth('signup_material_exam') && canSubmit">通过</el-button>
        <el-button type="success" icon="CircleCheck" @click="dataFormSubmit('2',true)" v-if="hasAuth('signup_material_pass_force') && canSubmit">强制通过</el-button>
        <el-button type="danger" icon="CircleClose" @click="dataFormSubmit('3',false)" v-if="hasAuth('signup_material_exam') && canSubmit">驳回</el-button>
      </div>
    </template>

    <el-dialog title="图片预览" v-model="dialogUploadVisible" append-to-body>
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, nextTick, computed, onMounted } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { useAuth } from '/@/hooks/auth'
import { useMessage } from '/@/hooks/message'
import { Session } from '/@/utils/storage'
import axios from 'axios'
import { getObj, materialExam } from '/@/api/recruit/recruitstudentsignup'
import { getList } from '/@/api/recruit/recruitstudentplangroup'
import { queryAllTeacher } from '/@/api/professional/professionaluser/teacherbase'
import { AUDIT_STATUS_LIST, getStatusConfig } from '/@/config/global'

const auditStatusList = AUDIT_STATUS_LIST
const { hasAuth } = useAuth()
// 消息提示 hooks
const message = useMessage()

const baseUrl = import.meta.env.VITE_API_URL
const uploadUrl = baseUrl + '/recruit/file/uploadAttachment'

// 请求头
const headers = computed(() => {
  return {
    "Authorization": 'Bearer ' + Session.getToken()
  }
})

// Emits
const emit = defineEmits<{
  (e: 'refreshDataList'): void
}>()

// 表单引用
const dataFormRef = ref()

// 响应式数据
const uploadData = reactive({})
const visible = ref(false)
const canSubmit = ref(false)
const title = ref("")
const contactNameflag = ref(false)
const type = ref<number | null>(null)
const contactNameList = ref<any[]>([])
const planList = ref<any[]>([])

const houseList = ref<any[]>([])
const hkPicList = ref<any[]>([])

const fileReader = ref<FileReader | null>(null)
const dialogImageUrl = ref("")
const dialogUploadVisible = ref(false)

const dataForm = reactive({
  id: "",
  zlshRemark: "",
  groupId: "",
  name: "",
  contactName: "",
  scorePhoto: "",
  graPic: "",
  yyPic: "",
  housePic: "",
  sbPic: "",
  householdPic: "",
  zlsh: "",
  // 以下字段从后端获取，用于显示和判断
  serialNumber: "",
  degreeOfEducation: "",
  auditStatus: ""
})

const dataRule = {
  groupId: [
    { required: true, message: '招生计划不能为空', trigger: 'change' }
  ],
  name: [
    { required: true, message: '姓名不能为空', trigger: 'change' }
  ],
  idNumber: [
    { required: true, message: '身份证不能为空', trigger: 'change' }
  ],
  correctedScore: [
    { required: true, message: '成绩折算分不能为空', trigger: 'change' }
  ],
  confirmedMajor: [
    { required: true, message: '原录取专业不能为空', trigger: 'change' }
  ],
  newConfirmedMajor: [
    { required: true, message: '新录取专业不能为空', trigger: 'change' }
  ]
}

// 初始化 FileReader
onMounted(() => {
  if (!window.FileReader) {
    message.error('您的浏览器不支持 FileReader API!')
  } else {
    fileReader.value = new FileReader()
  }
})

// 上传前验证
const beforeUpload = (file: File) => {
  const isLt5M = file.size < 10 * 1024 * 1024
  if (!isLt5M) {
    message.error('文件大小不能超过10M')
    return false
  }
  return true
}

// 图片预览
const handlePictureCardPreview = (file: any) => {
  dialogImageUrl.value = file.url
  dialogUploadVisible.value = true
}


// 通用移除文件处理（多文件）
const handleRemoveMultiple = (fileList: any[], dataFormField: string) => {
  return (file: any) => {
    const arr: any[] = []
    const strArr: string[] = []
    const dataFormObj = dataForm as any
    fileList.forEach((e: any) => {
      if (e.url != file.url) {
        arr.push(e)
        // 保存时使用原始路径
        strArr.push(e.originalUrl || (e.url.startsWith(baseUrl) ? e.url.substring(baseUrl.length) : e.url))
      }
    })
    fileList.splice(0, fileList.length, ...arr)
    dataFormObj[dataFormField] = strArr.join(",")
  }
}

// 移除文件处理（多图上传）
const remove4Handler = handleRemoveMultiple(houseList.value, 'housePic')
const remove6Handler = handleRemoveMultiple(hkPicList.value, 'householdPic')

// 自定义上传请求
const httpRequest = (options: any) => {
  const file = options.file
  if (file && fileReader.value) {
    fileReader.value.readAsDataURL(file)
    fileReader.value.onload = () => {
      const base64Str = fileReader.value?.result as string
      const config = {
        url: uploadUrl,
        method: 'post',
        headers: headers.value,
        data: {
          base64Str: base64Str.split(',')[1]
        },
        timeout: 10000,
        onUploadProgress: function (progressEvent: any) {
          progressEvent.percent = progressEvent.loaded / progressEvent.total * 100
          options.onProgress(progressEvent, file)
        },
      }
      axios(config)
        .then((res: any) => {
          options.onSuccess(res, file)
        })
        .catch((err: any) => {
          options.onError(err)
        })
    }
  }
}

// 通用上传成功回调（单文件 - avatar模式）
const handleUploadSuccess = (dataFormField: string) => {
  return (res: any) => {
    const fileUrl = res.data.fileUrl
    const dataFormObj = dataForm as any
    dataFormObj[dataFormField] = fileUrl
  }
}

// 通用上传成功回调（多文件）
const handleUploadSuccessMultiple = (fileList: any[], dataFormField: string) => {
  return (res: any) => {
    const fileUrl = res.data.fileUrl // 后端返回的原始路径
    const dataFormObj = dataForm as any
    // 添加到文件列表，显示时添加 baseUrl 前缀，同时保存原始路径用于提交
    fileList.push({ url: baseUrl + fileUrl, name: '', originalUrl: fileUrl })
    // 保存时使用原始路径
    const arr: string[] = []
    fileList.forEach((e: any) => {
      // 优先使用保存的原始路径，如果没有则从 url 中提取
      arr.push(e.originalUrl || (e.url.startsWith(baseUrl) ? e.url.substring(baseUrl.length) : e.url))
    })
    dataFormObj[dataFormField] = arr.join(",")
  }
}

// 上传成功回调
const uploadSuccess = handleUploadSuccess('scorePhoto')
const upload2Success = handleUploadSuccess('graPic')
const upload3Success = handleUploadSuccess('yyPic')
const upload4Success = handleUploadSuccessMultiple(houseList.value, 'housePic')
const upload5Success = handleUploadSuccess('sbPic')
const upload6Success = handleUploadSuccessMultiple(hkPicList.value, 'householdPic')

// 初始化数据
const initData = () => {
  getList().then((data: any) => {
    planList.value = data.data
  })
  // 联系人(教职工)
  queryAllTeacher().then((res: any) => {
    contactNameList.value = res.data
  })
}

// 表单提交
const dataFormSubmit = (submitType: string,force:any) => {
  if ((dataForm.zlshRemark == '' || !dataForm.zlshRemark) && submitType == '3') {
    message.error('请填写驳回理由')
    return
  }
  dataForm.zlsh = submitType
  canSubmit.value = false
  dataForm.force=force
  materialExam(dataForm).then(() => {
    message.success('操作成功')
    visible.value = false
    emit('refreshDataList')
  }).catch(() => {
    canSubmit.value = true
  })
}

// 初始化方法
const init = (id: string | null) => {
  dataForm.id = id || ""
  visible.value = true
  canSubmit.value = true
  initData()
  nextTick(() => {
    dataFormRef.value?.resetFields()
    if (dataForm.id) {
      getObj(dataForm.id).then((response: any) => {
        // 清空多图上传的列表
        houseList.value = []
        hkPicList.value = []
        Object.assign(dataForm, response.data)
        title.value = dataForm.serialNumber
        // avatar 模式直接使用 dataForm 中的字段，不需要 fileList
        // 多图上传需要初始化列表
        if (dataForm.housePic && dataForm.housePic != '') {
          const arr = dataForm.housePic.split(",").filter((item: string) => item && item.trim())
          arr.forEach((e: string) => {
            // 保存原始路径，显示时添加 baseUrl 前缀
            houseList.value.push({ url: baseUrl + e, name: '', originalUrl: e })
          })
        }
        if (dataForm.householdPic && dataForm.householdPic != '') {
          const arr2 = dataForm.householdPic.split(",").filter((item: string) => item && item.trim())
          arr2.forEach((e: string) => {
            // 保存原始路径，显示时添加 baseUrl 前缀
            hkPicList.value.push({ url: baseUrl + e, name: '', originalUrl: e })
          })
        }

        const educationPrefixMap: Record<string, string> = {
          '1': 'C',  // 初中
          '2': 'G',  // 高中
          '3': 'J'   // 技职校
        }
        const prefix = educationPrefixMap[String(dataForm.degreeOfEducation)]
        if (prefix) {
          title.value = prefix + title.value
        }
        contactNameflag.value = false
        const auditStatusConfig = getStatusConfig(auditStatusList, dataForm.auditStatus)
        if (auditStatusConfig) {
          title.value = auditStatusConfig.label + " " + title.value
          if (auditStatusConfig.value == '20') {
            contactNameflag.value = true
          }
        }
      })
    }
  })
}

// 暴露方法给父组件
defineExpose({
  init
})
</script>

<style lang="scss" scoped>
  .el-form{
    .el-form-item:last-of-type{
      margin-bottom:18px!important;
    }
  }

  
  .avatar-uploader {
    :deep(.el-upload) {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
      width: 148px;
      height: 148px;  
      &:hover {
        border-color: var(--el-color-primary);
      }
    }
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 148px;
    height: 148px;
    line-height: 148px;
    text-align: center;
  }

  .avatar-wrapper {
    width: 148px;
    height: 148px;
    .avatar {
      width: 148px;
      height: 148px;
      display: block;
      object-fit: cover;
      cursor: pointer;
    }
  }
</style>
