<template>
  <el-dialog
    :title="title"
    :close-on-click-modal="false"
    v-model="visible"
    append-to-body
    width="90%"
  >
    <el-form :model="dataForm" :rules="dataRule" ref="dataFormRef"  label-width="120px">
      <el-tabs v-model="activeTab">
        <el-tab-pane label="基本信息" name="basic">
          <!-- 基本信息 -->
          <div class="form-section">
            <div class="section-title">基本信息</div>
        
        <el-row :gutter="20" >
          <el-col :span="6">
            <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="6">
          <el-form-item label="姓名" prop="name" >
            <el-input type="text" v-model="dataForm.name" :disabled="!isEdit"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="曾用名" prop="oldName">
            <el-input type="text" v-model="dataForm.oldName" :disabled="!isEdit"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="民族" prop="nationality">
            <el-select v-model="dataForm.nationality" filterable placeholder="请选择民族" :disabled="!isEdit">
              <el-option
                v-for="item in nationalityList"
                :key="item.nationCode"
                :label="item.nationName"
                :value="item.nationName">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="证件类型" prop="idCardType">
            <el-radio-group v-model="dataForm.idCardType" :disabled="!isEdit" @change="handleIdCardTypeChange">
              <el-radio v-for="item in idCardTypeList" :key="item.value" :label="item.value">{{ item.label }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="身份证号" prop="idNumber">
            <el-input 
              v-model="dataForm.idNumber" 
              placeholder="身份证号"
              maxlength="20"
              v-input-filter="'idcard'"
              :disabled="!isEdit">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="性别" prop="gender" :required="isGenderRequired">
            <el-radio-group v-model="dataForm.gender" :disabled="!isEdit || dataForm.idCardType=='0'">
              <el-radio v-for="item in sexy" :key="item.value" :label="item.value">{{ item.label }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        
        <el-col :span="6">
          <el-form-item label="是否团员" prop="isLeagueMember">
            <el-select v-model="dataForm.isLeagueMember" filterable clearable placeholder="请选择是否团员" :disabled="!isEdit">
              <el-option
                v-for="item in yes_no_type"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="是否住宿" prop="isAccommodation">
            <el-select v-model="dataForm.isAccommodation" filterable clearable placeholder="请选择是否住宿" :disabled="!isEdit">
              <el-option
                v-for="item in yes_no_type"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="18">
          <el-form-item label="毕业学校" prop="schoolOfGraduation">
            <el-input type="text" v-model="dataForm.schoolOfGraduation" :disabled="!isEdit"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20" >
        <el-col :span="6">
          <el-form-item label="准考证号" prop="examRegistrationNumbers">
            <el-input 
              v-model="dataForm.examRegistrationNumbers" 
              placeholder="准考证号"
              maxlength="20"
              :disabled="!isEdit"
              v-input-filter="'alphanumeric'">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="文化程度" prop="degreeOfEducation">
            <el-select v-model="dataForm.degreeOfEducation" filterable placeholder="请选择文化程度" :disabled="!isEdit" @change="changeEducation">
              <el-option
                v-for="item in eduList"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        
        <el-col :span="6">
          <el-form-item label="成绩" prop="score">
            <el-input-number 
              controls-position="right"
              v-model="dataForm.score" 
              placeholder="成绩"
              :min="0"
              :max="1000"
              :disabled="!isEdit" 
              @change="calculateCorrectedScore">
            </el-input-number>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="户口性质" prop="residenceType">
            <el-select v-model="dataForm.residenceType" filterable clearable placeholder="请选择户口性质" :disabled="!isEdit">
              <el-option
                v-for="item in residenceTypeList"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
     
      <!-- 证件信息 -->
     
      <el-row v-if="dataForm.degreeOfEducation=='1'" :gutter="20" >
        <el-col :span="6">
          <el-form-item label="学校归属地" prop="schoolArea">
            <el-select v-model="dataForm.schoolArea" filterable placeholder="请选择学校归属地" :disabled="!isEdit" @change="changeFrom">
              <el-option
                v-for="item in schoolFromList"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col v-if="(dataForm.degreeOfEducation) && (dataForm.schoolArea=='2')" :span="6">
          <el-form-item label="学校所在省市" prop="jsOtherCity">
            <el-select v-model="dataForm.jsOtherCity" filterable placeholder="请选择学校所在省市"
                       :disabled="!isEdit" @change="changeSchoolCode">
              <el-option
                v-for="item in schoolCodeList"
                :key="item.regionId"
                :label="item.regionName"
                :value="item.regionId">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col v-if="(dataForm.degreeOfEducation) && (dataForm.schoolArea=='3')" :span="6">
          <el-form-item label="外省" prop="otherProvince">
            <el-select v-model="dataForm.otherProvince" filterable placeholder="请选择学校所在省市"
                       :disabled="!isEdit" @change="changeSchoolCode">
              <el-option
                v-for="item in areaHomeProvinceList"
                :key="item.code"
                :label="item.name"
                :value="item.code">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="当地总分" prop="fullScore">
            <el-input-number 
              controls-position="right"
              v-model="dataForm.fullScore" 
              :min="0"
              :max="1000"
              :disabled="isShow" 
              @change="changePlaceScore">
            </el-input-number>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="成绩折算分" prop="correctedScore">
            <el-input-number 
              controls-position="right"
              v-model="dataForm.correctedScore" 
              :min="0"
              :max="1000"
              disabled>
            </el-input-number>
          </el-form-item>
        </el-col>
       
       
      </el-row>
   
      <!-- 户口所在地 -->
      <el-row :gutter="20" >
        <el-col :span="12">
          <el-form-item label="户口所在地" prop="residenceProvince">
            <div class="address-group">
              <el-select v-model="dataForm.residenceProvince" filterable clearable placeholder="省" class="address-select" :disabled="!isEdit" @change="changeR(1)">
                <el-option
                  v-for="item in areaProvinceList"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code">
                </el-option>
              </el-select>
              <span class="address-separator">-</span>
              <el-select v-model="dataForm.residenceCity" filterable clearable placeholder="市" class="address-select" :disabled="!isEdit" @change="changeR(2)">
                <el-option
                  v-for="item in areaCityList"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code">
                </el-option>
              </el-select>
              <span class="address-separator">-</span>
              <el-select v-model="dataForm.residenceArea" filterable clearable placeholder="区/县" class="address-select" :disabled="!isEdit">
                <el-option
                  v-for="item in areaAreaList"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code">
                </el-option>
              </el-select>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="户口详细地址" prop="residenceDetail">
            <el-input type="text" v-model="dataForm.residenceDetail" placeholder="请输入详细地址" :disabled="!isEdit"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 家庭地址 -->
      <el-row :gutter="20" >
        <el-col :span="12">
          <el-form-item label="家庭地址" prop="homeAddressProvince">
            <div class="address-group">
              <el-select v-model="dataForm.homeAddressProvince" filterable clearable placeholder="省" class="address-select" :disabled="!isEdit" @change="changeH(1)">
                <el-option
                  v-for="item in areaHomeProvinceList"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code">
                </el-option>
              </el-select>
              <span class="address-separator">-</span>
              <el-select v-model="dataForm.homeAddressCity" filterable clearable placeholder="市" class="address-select" :disabled="!isEdit" @change="changeH(2)">
                <el-option
                  v-for="item in areaHomeCityList"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code">
                </el-option>
              </el-select>
              <span class="address-separator">-</span>
              <el-select v-model="dataForm.homeAddressArea" filterable clearable placeholder="区/县" class="address-select" :disabled="!isEdit">
                <el-option
                  v-for="item in areaHomeAreaList"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code">
                </el-option>
              </el-select>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="家庭详细地址" prop="homeAddressDetail">
            <el-input type="text" v-model="dataForm.homeAddressDetail" placeholder="请输入详细地址" :disabled="!isEdit"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20" >
        <el-col :span="6">
          <el-form-item label="家长姓名" prop="parentName">
            <el-input type="text" v-model="dataForm.parentName" :disabled="!isEdit"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="家长手机" prop="parentTelOne">
            <el-input 
              v-model="dataForm.parentTelOne" 
              type="tel"
              placeholder="家长手机"
              maxlength="11"
              :disabled="!isEdit"
              v-input-filter="'number'">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="家长固话" prop="parentTelTwo">
            <el-input 
              v-model="dataForm.parentTelTwo" 
              placeholder="家长固话"
              maxlength="20"
              :disabled="!isEdit"
              v-input-filter="'tel'">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="本人联系电话" prop="selfTel">
            <el-input 
              v-model="dataForm.selfTel" 
              type="tel"
              placeholder="本人联系电话"
              maxlength="11"
              :disabled="!isEdit"
              v-input-filter="'number'">
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      </div>

      <!-- 专业信息 -->
      <div class="form-section">
        <div class="section-title">专业信息</div>
        <el-row v-if="dataForm.id" :gutter="20" >
          <el-col :span="8">
            <el-form-item label="拟报专业1" prop="wishMajorOne">
            <el-select v-model="dataForm.wishMajorOne" filterable clearable placeholder="请选择专业">
              <el-option
                v-for="item in planMajorList"
                :key="item.majorCode"
                :label="item.majorName"
                :value="item.majorCode">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="拟报专业2" prop="wishMajorTwo">
            <el-select v-model="dataForm.wishMajorTwo" filterable clearable placeholder="请选择专业">
              <el-option
                v-for="item in planMajorList"
                :key="item.majorCode"
                :label="item.majorName"
                :value="item.majorCode">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="拟报专业3" prop="wishMajorThree">
            <el-select v-model="dataForm.wishMajorThree" filterable clearable placeholder="请选择专业">
              <el-option
                v-for="item in planMajorList"
                :key="item.majorCode"
                :label="item.majorName"
                :value="item.majorCode">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
        <el-row :gutter="20" >
          <el-col :span="24">
            <el-form-item label="录取专业" prop="confirmedMajor">
            <el-select v-model="dataForm.confirmedMajor" filterable clearable placeholder="" :disabled="!isEdit" @change="changeConfirmedMajor(dataForm.confirmedMajor)">
              <el-option
                v-for="item in planMajorList"
                :key="item.majorCode"
                :label="item.majorName+' || '+item.xyNum"
                :value="item.majorCode">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
        <el-row v-if="isEdit" :gutter="20" >
        <el-col :span="8" v-if="twoMajorList.length>0">
          <el-form-item label="两年制专业" prop="twoMajor" >
            <el-select v-model="dataForm.twoMajor" filterable clearable placeholder="" @change="changeConfirmedMajor(dataForm.twoMajor)">
              <el-option
                v-for="item in twoMajorList"
                :key="item.majorCode"
                :label="item.majorName+' || '+item.xyNum"
                :value="item.majorCode">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8" v-if="threeMajorList.length>0">
          <el-form-item label="三年制专业" prop="threeMajor" v-if="threeMajorList.length>0">
            <el-select v-model="dataForm.threeMajor" filterable clearable placeholder="" @change="changeConfirmedMajor(dataForm.threeMajor)">
              <el-option
                v-for="item in threeMajorList"
                :key="item.majorCode"
                :label="item.majorName+' || '+item.xyNum"
                :value="item.majorCode">
              </el-option>
            </el-select>
          </el-form-item>         
        </el-col>
        <el-col :span="8" v-if="fourMajorList.length>0">
          <el-form-item label="四年制专业" prop="fourMajor" >
            <el-select v-model="dataForm.fourMajor" filterable clearable placeholder="" @change="changeConfirmedMajor(dataForm.fourMajor)">
            <el-option
              v-for="item in fourMajorList"
              :key="item.majorCode"
              :label="item.majorName+' || '+item.xyNum"
              :value="item.majorCode">
            </el-option>
          </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8" v-if="fiveMajorList.length>0">
          <el-form-item label="五年制专业" prop="fiveMajor" >
            <el-select v-model="dataForm.fiveMajor" filterable clearable placeholder="" @change="changeConfirmedMajor(dataForm.fiveMajor)">
              <el-option
                v-for="item in fiveMajorList"
                :key="item.majorCode"
                :label="item.majorName+' || '+item.xyNum"
                :value="item.majorCode">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8" v-if="sixMajorList.length>0">
          <el-form-item label="六年制专业" prop="sixMajor">
            <el-select v-model="dataForm.sixMajor" filterable clearable placeholder="" @change="changeConfirmedMajor(dataForm.sixMajor)">
              <el-option
                v-for="item in sixMajorList"
                :key="item.majorCode"
                :label="item.majorName+' || '+item.xyNum"
                :value="item.majorCode">
              </el-option>
            </el-select>
          </el-form-item>         
        </el-col>
        <el-col :span="8" v-if="sevenMajorList.length>0">
          <el-form-item label="七年制专业" prop="sevenMajor">
            <el-select v-model="dataForm.sevenMajor" filterable clearable placeholder="" @change="changeConfirmedMajor(dataForm.sevenMajor)">
              <el-option
                v-for="item in sevenMajorList"
                :key="item.majorCode"
                :label="item.majorName+' || '+item.xyNum"
                :value="item.majorCode">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
        <!-- 费用信息 -->
        <el-row :gutter="20" >
          <el-col :span="8">
            <el-form-item label="学费" prop="feeTuition">
              <el-input-number v-model="dataForm.feeTuition" controls-position="right" :min="0" :max="999999" :step-strictly="true" disabled></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="代办费" prop="feeAgency">
              <el-input-number v-model="dataForm.feeAgency" controls-position="right" :min="0" :max="999999" :step-strictly="true" disabled></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="总费用" prop="allMoney">
              <span class="total-fee">{{Number(dataForm.feeTuition)+Number(dataForm.feeAgency)}}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 其他信息 -->
        <el-row :gutter="20" >
          <el-col :span="8">
            <el-form-item label="联系人" prop="contactName">
              <el-select v-model="dataForm.contactName" filterable clearable placeholder="请选择联系人" :disabled="!isEdit">
                <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-col :span="8">
            <el-form-item label="辨色力" prop="colorDiscrimination">
              <el-select v-model="dataForm.colorDiscrimination" filterable clearable placeholder="请选择辨色力" :disabled="!isEdit">
                <el-option
                  v-for="item in color_discrimination"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20" >
          <el-col :span="12">
            <el-form-item label="既往病史" prop="pastMedicalHistory">
              <el-input type="textarea" v-model="dataForm.pastMedicalHistory" placeholder="请输入既往病史" :rows="2" :disabled="!isEdit"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注" prop="remarks">
              <el-input type="textarea" v-model="dataForm.remarks" placeholder="备注" :rows="2" :disabled="!isEdit"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
          </div>
        </el-tab-pane>
        <el-tab-pane label="附件材料" name="attachment">
          <!-- 附件材料 -->
          <el-row :gutter="20" >
            <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 :gutter="20" >
            <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-tab-pane>
      </el-tabs>
    </el-form>
    <template #footer v-if="isEdit">
      <div class="dialog-footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="dataFormSubmit('0')" v-if="hasAuth('recruit_recruitstudentsignup_add') && canSubmit&&!dataForm.id">保存并送审</el-button>
        <el-button type="primary" @click="dataFormSubmit('0')" v-if="hasAuth('recruit_recruitstudentsignup_edit') && canSubmit&&dataForm.id">保存</el-button>
        <el-button type="success" icon="CircleCheck" @click="dataFormSubmit('20',false)" v-if="hasAuth('signup_info_exam') && canSubmit&&dataForm.id">确认录取</el-button>
        <el-button type="warning" icon="CircleCheck" @click="dataFormSubmit('20',true)" v-if="hasAuth('signup_pass_force') && canSubmit&&dataForm.id">强制录取</el-button>
        <el-button type="danger" icon="CircleClose" @click="dataFormSubmit('-20',false)" v-if="hasAuth('signup_info_exam') && canSubmit&&dataForm.id">驳回</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, watch, computed, onMounted } from 'vue'
import { ElNotification } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { useAuth } from '/@/hooks/auth'
import { useMessage, useMessageBox } from '/@/hooks/message'
import { Session } from '/@/utils/storage'
import axios from 'axios'
import { getObj, putObj, addObj ,makeCorrectScore} from '/@/api/recruit/recruitstudentsignup'
import { getList } from "/@/api/recruit/recruitstudentplangroup"
import { listByEdu } from "/@/api/recruit/recruitstudentplan"
import { getDictsByTypes } from "/@/api/admin/dict"
import { useDict } from '/@/hooks/dict'
import { areaList, areaSonList } from "/@/api/recruit/recruitstudentschool"
import { list as scoreList } from "/@/api/recruit/recruitstudentplancorrectscoreconfig"
import { queryAllTeacher } from "/@/api/professional/professionaluser/teacherbase"
import { getNationalList } from "/@/api/basic/basicnation"
import { verifyAdmissionNumber, verifyPhone } from '/@/utils/toolsValidate'
import { AUDIT_STATUS_LIST, getStatusConfig } from '/@/config/global'

const { hasAuth } = useAuth()
const message = useMessage()
const messageBox = useMessageBox()
// Emits
const emit = defineEmits<{
  (e: 'refreshDataList'): void
}>()

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

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

// 响应式数据
const visible = ref(false)
const canSubmit = ref(false)
const title = ref("")
const activeTab = ref('basic')

// 上传相关
const uploadData = reactive({})
const houseList = ref<any[]>([])
const hkPicList = ref<any[]>([])
const fileReader = ref<FileReader | null>(null)
const dialogImageUrl = ref("")
const dialogUploadVisible = ref(false)

// 请求头
const headers = computed(() => {
  return {
    "Authorization": 'Bearer ' + Session.getToken()
  }
})
// 字典数据 是否 性别 辨色力
const { yes_no_type, sexy, color_discrimination } = useDict('yes_no_type', 'sexy', 'color_discrimination')

const eduList = ref<any[]>([])
const type = ref<number | null>(null)
const isShow = ref(false)
const isEdit = ref(false)
// 性别是否必填（证件类型不是身份证时必填）
const isGenderRequired = computed(() => dataForm.idCardType !== '0')
// 录取状态
const auditStatusList = AUDIT_STATUS_LIST
// 户口性质
const residenceTypeList = ref<any[]>([])
const schoolCodeList = ref<any[]>([])
const contactNameList = ref<any[]>([])
const planList = ref<any[]>([])
const planMajorList = ref<any[]>([])
const areaProvinceList = ref<any[]>([])
const areaCityList = ref<any[]>([])
const areaAreaList = ref<any[]>([])
const areaHomeProvinceList = ref<any[]>([])
const areaHomeCityList = ref<any[]>([])
const areaHomeAreaList = ref<any[]>([])
const sevenMajorList = ref<any[]>([])
const sixMajorList = ref<any[]>([])
const fiveMajorList = ref<any[]>([])
const fourMajorList = ref<any[]>([])
const threeMajorList = ref<any[]>([])
const twoMajorList = ref<any[]>([])
const agencyFeeList = ref<any[]>([])
const tuitionFeeList = ref<any[]>([])
const schoolFromList = ref<any[]>([])
const nationalityList = ref<any[]>([])
const idCardTypeList = ref<any[]>([])
const dataForm = reactive({
        id: "",
        groupId: "",
        name: "",
        oldName: "",
        gender: "",
        nationality: "",
        degreeOfEducation: "",
        isLeagueMember: "",
        schoolOfGraduation: "",
        isAccommodation: "",
        examRegistrationNumbers: "",
        isMinimumLivingSecurity: "",
        score: "",
        postcode: "",
        residenceType: "",
        correctedScore: 0,
        fullScore: "",
        schoolArea: "",
        idNumber: "",
        residenceProvince: "",
        residenceCity: "",
        residenceArea: "",
        residenceDetail: "",
        homeAddressProvince: "",
        homeAddressCity: "",
        homeAddressArea: "",
        homeAddressDetail: "",
        parentName: "",
        parentTelOne: "",
        parentTelTwo: "",
        selfTel: "",
        wishMajorOne: "",
        wishMajorTwo: "",
        wishMajorThree: "",
        confirmedMajor: "",
        sevenMajor:"",
        sixMajor:"",
        fiveMajor:"",
        fourMajor: "",
        threeMajor: "",
        twoMajor: "",
        feeTuition: 0,
        feeAgency: 0,
        feeContribute: 0,
        scorePhoto: "",
        graPic: "",
        yyPic: "",
        housePic: "",
        sbPic: "",
        contactName: "",
        oldSerialNumber: "",
        colorDiscrimination: "",
        nutrition: "",
        height: "",
        weight: "",
        pastMedicalHistory: "",
        eyesightLeft: "",
        eyesightRight: "",
        correctEyesightLeft: "",
        correctEyesightRight: "",
        remarks: "",
        auditRemarks: "",
        serialNumber: "",
        auditStatus:"",
        jsOtherCity:"",
        householdPic:"",
        otherProvince:"",
        idCardType:"0",
        scorePhotoList: [] as string[],
        graPicList: [] as string[],
        yyPicList: [] as string[],
        housePicList: [] as string[],
        sbPicList: [] as string[],
        householdPicList: [] as string[]
})

const dataRule = reactive({
        groupId: [
          {required: true, message: '招生计划不能为空', trigger: 'change'}
        ],
        name: [
          {required: true, message: '姓名不能为空', trigger: 'change'}
        ],
        gender: [
          {
            validator: (rule: any, value: any, callback: any) => {
              // 如果证件类型是身份证，性别可以不填（后台会根据身份证号自动获取）
              if (dataForm.idCardType === '0') {
                callback()
              } else if (!value) {
                callback(new Error('性别不能为空'))
              } else {
                callback()
              }
            },
            trigger: 'change'
          }
        ],
        nationality: [
          {required: true, message: '民族不能为空', trigger: 'change'}
        ],
        degreeOfEducation: [
          {required: true, message: '文化程度不能为空', trigger: 'change'}
        ],
        isLeagueMember: [
          {required: true, message: '是否团员不能为空', trigger: 'change'}
        ],
        schoolOfGraduation: [
          {required: true, message: '毕业学校不能为空', trigger: 'change'}
        ],
        isAccommodation: [
          {required: true, message: '是否住宿不能为空', trigger: 'change'}
        ],
        residenceType: [
          {required: true, message: '户口性质不能为空', trigger: 'change'}
        ],
        idCardType: [
          {required: true, message: '证件类型不能为空', trigger: 'change'}
        ],
        idNumber: [
          {required: true, message: '身份证不能为空', trigger: 'change'}
        ],
        examRegistrationNumbers: [
          {required: true, message: '准考证号不能为空', trigger: 'change'},
          {
            validator: (rule: any, value: any, callback: any) => {
              if (value && !verifyAdmissionNumber(value)) {
                callback(new Error('请输入正确的准考证号'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ],
        score: [] as any[],
        fullScore: [] as any[],
        jsOtherCity: [] as any[],
        otherProvince: [] as any[],
        residenceProvince: [
          {required: true, message: '户口所在地不能为空', trigger: 'change'}
        ],
        residenceCity: [
          {required: true, message: '户口所在地不能为空', trigger: 'change'}
        ],
        residenceArea: [
          {required: true, message: '户口所在地不能为空', trigger: 'change'}
        ],
        residenceDetail: [
          {required: true, message: '户口所在地不能为空', trigger: 'change'}
        ],
        homeAddressProvince: [
          {required: true, message: '家庭地址不能为空', trigger: 'change'}
        ],
        homeAddressCity: [
          {required: true, message: '家庭地址不能为空', trigger: 'change'}
        ],
        homeAddressArea: [
          {required: true, message: '家庭地址不能为空', trigger: 'change'}
        ],
        homeAddressDetail: [
          {required: true, message: '家庭地址不能为空', trigger: 'change'}
        ],
        parentName: [
          {required: true, message: '家长姓名不能为空', trigger: 'change'}
        ],
        parentTelOne: [
          {required: true, message: '家长手机不能为空', trigger: 'change'},
          {
            validator: (rule: any, value: any, callback: any) => {
              if (value && !verifyPhone(value)) {
                callback(new Error('请输入正确的手机号码'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ],        
        contactName: [
          {required: true, message: '联系人不能为空', trigger: 'change'}
        ],
        colorDiscrimination: [
          {required: true, message: '辨色力不能为空', trigger: 'change'}
        ],
        correctedScore:[
          {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 init = (id: string | null, typeParam: number, groupId?: string) => {
  dataForm.id = id || ""
  type.value = typeParam
  isEdit.value = typeParam == 1 ? true : false
  visible.value = true
  canSubmit.value = true
  initData()
  isShow.value = true
  nextTick(() => {
    dataFormRef.value?.resetFields()
    // 新增时，如果传入了 groupId，设置到表单中
    if (!id && groupId) {
      dataForm.groupId = groupId
    }
    // 初始化地区数据
    areaProvinceList.value = []
    areaCityList.value = []
    areaAreaList.value = []
    // 家庭地址数据
    areaHomeProvinceList.value = []
    areaHomeCityList.value = []
    areaHomeAreaList.value = []
    
    // 批量获取数据字典（新增和编辑都需要）  文化程度  学费 代办费  户口性质  学校归属地
    getDictsByTypes(['id_type','finance_student_source', 'recruit_agency_fee', 'tuition_fee','house_hold_properties','recruit_school_form']).then((res: any) => {
      idCardTypeList.value = res.data.id_type || []
      eduList.value = res.data.finance_student_source || []
      agencyFeeList.value = res.data.recruit_agency_fee || []
      tuitionFeeList.value = res.data.tuition_fee || []
      residenceTypeList.value = res.data.house_hold_properties || []
      schoolFromList.value = res.data.recruit_school_form || []
      // 加载地区数据（新增和编辑都需要）
      areaList({ type: 0 }).then((data: any) => {
        const areas = data.data
        // 加载省级数据
        areas.forEach((e: any) => {
          if (e.parentId == '1') {
            areaProvinceList.value.push(e)
            areaHomeProvinceList.value.push(e)
          }
        })
      })
      
      if (dataForm.id) {
        // 编辑模式：获取表单数据
        getObj(dataForm.id).then((response: any) => {
              Object.assign(dataForm, response.data)
              // 清空多图上传的列表
              houseList.value = []
              hkPicList.value = []
              
              // 初始化多图上传列表
              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 arr = dataForm.householdPic.split(",").filter((item: string) => item && item.trim())
                arr.forEach((e: string) => {
                  // 保存原始路径，显示时添加 baseUrl 前缀
                  hkPicList.value.push({ url: baseUrl + e, name: '', originalUrl: e })
                })
              }



              title.value = dataForm.serialNumber
              // 获取文化程度对应的专业
              // 根据学历获取代办费（从字典获取）
              agencyFeeList.value.forEach((e: any) => {
                if (dataForm.degreeOfEducation == e.label) {
                  dataForm.feeAgency = e.value
                }
              })
              // 加载专业列表并分组
              loadMajorListAndGroup()
              // 获取招生计划下的学校所在城市（本省外市）
              scoreList({ groupId: dataForm.groupId }).then((data: any) => {
                schoolCodeList.value = data.data
              })
              
              // 根据已有数据加载市区数据
              if (dataForm.residenceProvince) {
                areaSonList({ code: dataForm.residenceProvince }).then((data: any) => {
                  areaCityList.value = data.data
                  if (dataForm.residenceCity) {
                    areaSonList({ code: dataForm.residenceCity }).then((data: any) => {
                      areaAreaList.value = data.data
                    })
                  }
                })
              }
              
              if (dataForm.homeAddressProvince) {
                areaSonList({ code: dataForm.homeAddressProvince }).then((data: any) => {
                  areaHomeCityList.value = data.data
                  if (dataForm.homeAddressCity) {
                    areaSonList({ code: dataForm.homeAddressCity }).then((data: any) => {
                      areaHomeAreaList.value = data.data
                    })
                  }
                })
              }
              // 根据文化程度添加前缀：初中(C)、高中(G)、技职校(J)
              const educationPrefixMap: Record<string, string> = {
                '1': 'C',  // 初中
                '2': 'G',  // 高中
                '3': 'J'   // 技职校
              }
              const prefix = educationPrefixMap[String(dataForm.degreeOfEducation)]
              if (prefix) {
                title.value = prefix + title.value
              }

              // 从字典数据获取录取状态标签
              const auditStatusConfig = getStatusConfig(auditStatusList, dataForm.auditStatus)
              if (auditStatusConfig && auditStatusConfig.label) {
                title.value = auditStatusConfig.label + " " + title.value
              }
        })
      } else {
        // 新增模式：设置默认标题
        title.value = "新增报名信息"
      }
    })
  })
}

// 证件类型变化处理
const handleIdCardTypeChange = () => {
  // 如果选择身份证，清空性别字段（后台会根据身份证号自动获取）
  if (dataForm.idCardType === '0') {
    dataForm.gender = ''
  }
}

// 加载专业列表并分组
const loadMajorListAndGroup = () => {
  // 清空专业列表
  planMajorList.value = []
  twoMajorList.value = []
  threeMajorList.value = []
  fiveMajorList.value = []
  sixMajorList.value = []
  sevenMajorList.value = []
  fourMajorList.value = []
  
  // 根据学历获取专业
  listByEdu({ groupId: dataForm.groupId, degreeOfEducation: dataForm.degreeOfEducation }).then((e: any) => {
    planMajorList.value = e.data
    // 如果是初中生，则根据折算分匹配录取专业
    getGzAuditChange()
    // 根据年制分组
    planMajorList.value.forEach((item: any) => {
      if (item.learnYear == '2') {
        twoMajorList.value.push(item)
      } else if (item.learnYear == '3') {
        threeMajorList.value.push(item)
      } else if (item.learnYear == '4') {
        fourMajorList.value.push(item)
      } else if (item.learnYear == '5') {
        fiveMajorList.value.push(item)
      } else if (item.learnYear == '6') {
        sixMajorList.value.push(item)
      } else if (item.learnYear == '7') {
        sevenMajorList.value.push(item)
      }
    })
    
    // 如果已有录取专业，根据文化程度和专业更新学费
    if (dataForm.confirmedMajor) {
      updateTuitionByMajorAndEducation()
    }
  })
}

const changeEducation = () => {
  // 清空拟报专业 录取专业 学费和代办费
  dataForm.wishMajorOne = ""
  dataForm.wishMajorTwo = ""
  dataForm.wishMajorThree = ""
  dataForm.confirmedMajor = ""
  dataForm.twoMajor = ""
  dataForm.threeMajor = ""
  dataForm.fourMajor = ""
  dataForm.fiveMajor = ""
  dataForm.sixMajor = ""
  dataForm.sevenMajor = ""

  dataForm.feeTuition = 0
  dataForm.feeAgency = 0

  // 重新根据学历获取代办费（从字典获取）
  agencyFeeList.value.forEach((e: any) => {
    if (dataForm.degreeOfEducation == e.label) {
      dataForm.feeAgency = e.value
    }
  })

  // 加载专业列表并分组
  loadMajorListAndGroup()
}

const initData = () => {
  // 联系人(教职工)
  queryAllTeacher().then((res: any) => {
    contactNameList.value = res.data
  })
  // 获取招生计划列表
  getList().then((data: any) => {
    planList.value = data.data
  })
  // 获取民族列表
  getNationalList().then((res: any) => {
    nationalityList.value = res.data
  })
}

const changeFrom = () => {
  dataForm.fullScore = ""
  dataForm.correctedScore = 0
  if (dataForm.schoolArea == "2") {
    isShow.value = true
  } else {
    isShow.value = false
  }
}

const changeSchoolCode = () => {
  dataForm.fullScore = ""
  schoolCodeList.value.forEach((e: any) => {
    if (e.regionId == dataForm.jsOtherCity) {
      dataForm.fullScore = e.fullScore
    }
  })
  if (dataForm.fullScore == "" && dataForm.schoolArea != "3") {
    ElNotification.error({
      title: '错误',
      message: '当前省市未匹配到分数线,请检查'
    })
    return
  }

  dataForm.correctedScore = 0
  calculateCorrectedScore()
}

const changePlaceScore = () => {
  calculateCorrectedScore()
}

const getGzAuditChange = () => {
  // 如果是初中生 需要根据折算分匹配录取专业
  if (dataForm.degreeOfEducation == "1") {
    if (isEdit.value && (dataForm.confirmedMajor == undefined || dataForm.confirmedMajor == "")) {
      // 根据折算分匹配录取专业
      planMajorList.value.forEach((e: any) => {
        if (e.majorCode == dataForm.wishMajorOne && (parseFloat(e.xyNum) > 0)) {
          dataForm.confirmedMajor = dataForm.wishMajorOne
        }
      })
      if (dataForm.confirmedMajor) {
        planMajorList.value.forEach((e: any) => {
          if (e.majorCode == dataForm.wishMajorTwo && (parseFloat(e.xyNum) > 0)) {
            dataForm.confirmedMajor = dataForm.wishMajorOne
          }
        })
      }

      if (dataForm.confirmedMajor) {
        planMajorList.value.forEach((e: any) => {
          if (e.majorCode == dataForm.wishMajorThree && (parseFloat(e.xyNum) > 0)) {
            dataForm.confirmedMajor = dataForm.wishMajorOne
          }
        })
      }
    }
  }
  
}

// 计算成绩折算分
const calculateCorrectedScore = () => {
  // 验证必要字段是否存在
  const hasFullScore = dataForm.fullScore != undefined && dataForm.fullScore != ""
  const hasSchoolArea = dataForm.schoolArea != undefined && dataForm.schoolArea != ""
  
  // 验证外省或学校所在省市至少有一个存在
  const hasLocation = (dataForm.schoolArea === '2' && dataForm.jsOtherCity) || 
                     (dataForm.schoolArea === '3' && dataForm.otherProvince)
  
  // 只有成绩、当地总分、学校归属地、外省/学校所在省市都存在时才能计算
  if (!hasFullScore || !hasSchoolArea || !hasLocation) {
    return
  }
  
  dataForm.confirmedMajor = ""
  
  // 调用后端接口计算折算分
  makeCorrectScore({
    groupId: dataForm.groupId,
    schoolArea: dataForm.schoolArea,
    jsOtherCity: dataForm.jsOtherCity,
    otherProvince: dataForm.otherProvince,
    fullScore: dataForm.fullScore,
    score: dataForm.score,
    degreeOfEducation: dataForm.degreeOfEducation
  }).then(res => {
    if (res.code !== 0) {
      return
    }
    
    dataForm.correctedScore = res.data
    
    // 根据折算分匹配录取专业（按志愿顺序：专业1 -> 专业2 -> 专业3）
    const matchMajorByScore = (majorCode: string) => {
      return planMajorList.value.find((major: any) => 
        dataForm.correctedScore >= major.scoreLine && 
        major.majorCode == majorCode && 
        parseFloat(major.xyNum) > 0
      )
    }
    
    // 按志愿顺序匹配专业
    const matchedMajor = matchMajorByScore(dataForm.wishMajorOne) || 
                        matchMajorByScore(dataForm.wishMajorTwo) || 
                        matchMajorByScore(dataForm.wishMajorThree)
    
    if (matchedMajor) {
      dataForm.confirmedMajor = matchedMajor.majorCode
      changeConfirmedMajor(dataForm.confirmedMajor)
    }
  })
}

const changeR = (changeType: number) => {
  let code = ""
  // 清空区数据
  areaAreaList.value = []
  dataForm.residenceArea = ""
  if (changeType == 1) {
    // 选择省份时，清空市和区数据
    code = dataForm.residenceProvince
    areaCityList.value = []
    dataForm.residenceCity = ""
  } else {
    // 选择市时
    code = dataForm.residenceCity
  }
  // 获取市或区数据
  areaSonList({ code: code }).then((data: any) => {
    if (changeType == 1) {
      areaCityList.value = data.data
    } else {
      areaAreaList.value = data.data
    }
  })
}

const changeH = (changeType: number) => {
  let code = ""
  areaHomeAreaList.value = []
  dataForm.homeAddressArea = ""
  if (changeType == 1) {
    code = dataForm.homeAddressProvince
    areaHomeCityList.value = []
    dataForm.homeAddressCity = ""
  } else {
    code = dataForm.homeAddressCity
  }
  areaSonList({ code: code }).then((data: any) => {
    if (changeType == 1) {
      areaHomeCityList.value = data.data
    } else {
      areaHomeAreaList.value = data.data
    }
  })
}

// 改变录取专业
const changeConfirmedMajor = (id: string) => {
  if (id) {
    dataForm.confirmedMajor = id
    // 根据文化程度和录取专业更新学费
    updateTuitionByMajorAndEducation()
  }
}

// 根据文化程度和录取专业更新学费
const updateTuitionByMajorAndEducation = () => {
  if (!dataForm.confirmedMajor || !dataForm.degreeOfEducation) {
    return
  }
  
  // 查找选中的专业
  const selectedMajor = planMajorList.value.find((major: any) => major.majorCode === dataForm.confirmedMajor)
  if (!selectedMajor) {
    return
  }
  
  // 根据文化程度选择对应的学费字段
  // '1' = 初中 -> czFee
  // '2' = 高中 -> gzFee
  // '3' = 技职校 -> jzxFee
  if (dataForm.degreeOfEducation === '1' && selectedMajor.czFee !== undefined && selectedMajor.czFee !== null) {
    dataForm.feeTuition = selectedMajor.czFee
  } else if (dataForm.degreeOfEducation === '2' && selectedMajor.gzFee !== undefined && selectedMajor.gzFee !== null) {
    dataForm.feeTuition = selectedMajor.gzFee
  } else if (dataForm.degreeOfEducation === '3' && selectedMajor.jzxFee !== undefined && selectedMajor.jzxFee !== null) {
    dataForm.feeTuition = selectedMajor.jzxFee
  }
}

// 表单提交
const dataFormSubmit = (state: string,force:any) => {
  dataForm.auditStatus = state
  let submitTitle = "确认通过该学生的报名申请么?"
  // 新增模式
  if (!dataForm.id) {
    submitTitle = "确认保存并提交该学生的报名信息么？"
  } else {
    // 编辑模式
    if (state == "-20") {
      submitTitle = "确认驳回该学生的报名申请么？"
    }
  }

  // 清空相关验证规则
  dataRule.score = []
  dataRule.fullScore = []
  dataRule.jsOtherCity = []
  dataRule.otherProvince = []
  if (dataForm.degreeOfEducation == '1') {
    dataRule.score = [
      {required: true, message: '初中生报名请填写成绩', trigger: 'change'}
    ]
    if(dataForm.schoolArea){
      if(dataForm.schoolArea == '3'){
        // 外省外市
        dataRule.fullScore = [
          {required: true, message: '外地初中生报名请填写当地总分', trigger: 'change'}
        ]
        dataRule.otherProvince = [
          {required: true, message: '初中生请选择学校归属地和所在省市', trigger: 'change'}
        ]
      }
      if(dataForm.schoolArea == '2'){
        // 本省外市
        dataRule.jsOtherCity = [
          {required: true, message: '初中生请选择学校归属地和所在省市', trigger: 'change'}
        ]
      }
    }
  }

  // 先进行表单验证，验证成功后再弹出确认框
  dataFormRef.value?.validate((valid: boolean) => {
    if (!valid) {
      return
    }
    
    // 表单验证通过，弹出确认框
    messageBox.confirm(submitTitle).then(() => {
      canSubmit.value = false
      if (dataForm.id) {
        // 编辑模式
        dataForm.force=force
        putObj(dataForm).then(() => {
          message.success('操作成功')
          visible.value = false
          emit('refreshDataList')
        }).finally(() => {
          canSubmit.value = true
        })
      } else {
        // 新增模式
        addObj(dataForm).then(() => {
          message.success('新增成功')
          visible.value = false
          emit('refreshDataList')
        }).finally(() => {
          canSubmit.value = true
        })
      }
    }).catch(() => {
      // 用户取消
    })
  })
}

// 监听招生计划变化（新增模式下需要加载分数线数据）
watch(() => dataForm.groupId, (newVal) => {
  if (newVal && !dataForm.id) {
    // 新增模式下，加载招生计划对应的分数线数据
    scoreList({ groupId: newVal }).then((data: any) => {
      schoolCodeList.value = data.data
    })
  }
})

// 暴露方法给父组件
defineExpose({
  init
})
</script>
<style lang="scss" scoped>
  .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;
    }
  }

// 总费用样式
.total-fee {
  color: #f56c6c;
  font-weight: 600;
  font-size: 16px;
}

// 表单布局优化
.el-form {
  // 覆盖全局样式：每行的最后一个表单项也需要间距
  .el-row .el-form-item:last-child {
    margin-bottom: 18px !important;
  }
  
  // 只有整个表单的最后一个表单项才不需要底部间距
  .el-row:last-of-type .el-form-item:last-child {
    margin-bottom: 0 !important;
  }
}


// 表单模块样式
.form-section {
  margin-bottom: 24px;
  padding: 20px;
  background: #fafbfc;
  border-radius: 8px;
  border: 1px solid #ebeef5;
  
  &:last-child {
    margin-bottom: 0;
  }
  
  .section-title {
    font-size: 15px;
    font-weight: 600;
    color: #303133;
    margin-bottom: 16px;
    padding-bottom: 12px;
    border-bottom: 2px solid #e4e7ed;
  }
}

// 地址组样式 - 省市区紧凑排列，用分隔符连接
.address-group {
  display: flex;
  align-items: center;
  gap: 8px;
  width: 100%;
  
  :deep(.address-select) {
    flex: 1 1 0;
    min-width: 0px;
    width: 0; // 让 flex: 1 生效
  }
  
  .address-separator {
    color: #909399;
    font-size: 14px;
    font-weight: 500;
    flex-shrink: 0;
    padding: 0 4px;
  }
}



</style>

