<template>
  <div class="app-container">
    <h1 style="font-size: 30px;text-align: center;">个人信息填写</h1>
    <div class="stylecard">
      <el-card class="box-card1">
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
          <el-form-item label="学号" prop="stId" :rules="rules.reason1">
            <el-input v-model="form.stId" placeholder="请输入学号" />
            <!-- <el-input v-model="form.stId" placeholder="请输入学号" @blur="changeGet" /> -->
          </el-form-item>
          <!-- <el-form-item label="学生编号" prop="studentId" >
            <el-input v-model="form.studentId" placeholder="" disabled />
          </el-form-item> -->
          <el-form-item label="姓名" prop="stName" :rules="rules.reason2">
            <el-input v-model="form.stName" placeholder="请输入姓名" />
          </el-form-item>
          <!-- <el-form-item label="辅导员名字" prop="fdName" :rules="rules.reason3">
            <el-input v-model="form.fdName" placeholder="请输入辅导员名字" />
          </el-form-item> -->
          <el-form-item label="性别" prop="sex" :rules="rules.reason4">
            <el-select v-model="form.sex" placeholder="请选择性别">
              <el-option v-for="dict in dict.type.sys_user_sex" :key="dict.value" :label="dict.label"
                :value="dict.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="民族" prop="nations" :rules="rules.reason5">
            <!-- <el-input v-model="form.nations" placeholder="请输入民族" /> -->
            <el-select v-model="form.nations" placeholder="请选择民族">
              <el-option v-for="dict in dict.type.rt_nation" :key="dict.value" :label="dict.label"
                :value="dict.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="班级" prop="stClass" :rules="rules.reason6">
            <el-input v-model="form.stClass" placeholder="请输入班级" />
          </el-form-item>
          <el-form-item label="专业" prop="majors" :rules="rules.reason7">
            <el-input v-model="form.majors" placeholder="请输入专业" />
          </el-form-item>
          <el-form-item label="年级" prop="grade" :rules="rules.reason8">
            <el-input v-model="form.grade" placeholder="请输入年级" />
          </el-form-item>
          <el-form-item label="学院" prop="college" :rules="rules.reason9">
            <!-- <el-input v-model="form.college" placeholder="请输入学院" /> -->
            <el-select v-model="form.college" placeholder="请选择学院" :rules="rules.reason10">
              <el-option v-for="dict in dict.type.rt_filling_college" :key="dict.value" :label="dict.label"
                :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="原因" prop="reasons" :rules="rules.reason10">
            <el-input v-model="form.reasons" placeholder="请输入原因" type="textarea" />
          </el-form-item>
          <el-form-item label="时间" prop="times" :rules="rules.reason11">
            <!-- <el-input v-model="form.times" placeholder="请输入时间" /> -->
            <el-date-picker v-model="form.times" clearable type="date" value-format="yyyy-MM-dd"
              placeholder="请选择填报时间" />
          </el-form-item>

          <!-- 入伍时间 -->
          <el-form-item label="入伍时间" prop="rwTime" :rules="rules.reason11">
            <el-date-picker v-model="form.rwTime" clearable type="date" value-format="yyyy-MM-dd"
              placeholder="请选择填报时间" />
          </el-form-item>

          <!-- 退伍时间 -->
          <el-form-item label="退伍时间" prop="dataa" :rules="rules.reason11">
            <!-- <el-input v-model="form.dataa" placeholder="请输入" /> -->
            <el-date-picker v-model="form.dataa" clearable type="date" value-format="yyyy-MM-dd"
              placeholder="请选择填报时间" />
          </el-form-item>

          <!-- 手机号 -->
          <el-form-item label="手机号" prop="datab" :rules="rules.reason13">
            <el-input v-model="form.datab" placeholder="请输入手机号" />
          </el-form-item>

          <el-form-item label="专业转换" prop="conversion" :rules="rules.reason12">
            <el-select v-model="form.conversion" placeholder="请选择专业转换">
              <el-option v-for="dict in dict.type.sys_yes_no" :key="dict.value" :label="dict.label"
                :value="dict.value"></el-option>
            </el-select>

          </el-form-item>
        </el-form>
        <!-- <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div> -->
      </el-card>

      <!-- 材料上传 -->
       <el-card class="box-card1" v-if="form.conversion === 'N'">
        <el-form ref="form2" :model="form" :rules="rules2" label-width="80px">
          <el-form-item label="退役证明" prop="proof">
            <image-upload v-model="form.proof" />
          </el-form-item>
          <el-form-item label="身份证" prop="idcard">
            <image-upload v-model="form.idcard" />
          </el-form-item>
          <el-form-item label="材料" prop="material">
            <image-upload v-model="form.material" />
          </el-form-item>
        </el-form>
      </el-card>

      <!-- 转专业材料上传 -->
      <el-card class="box-card1" v-if="form.conversion === 'Y'">
        <el-form ref="form2" :model="form" :rules="rules2" label-width="80px">
          <el-form-item label="原年级" prop="oldgrade" :rules="rules2.reason3">
            <el-input v-model="form.oldgrade" placeholder="请输入原年级" disabled />
          </el-form-item>
          <el-form-item label="原专业" prop="oldmajor" :rules="rules2.reason4">
            <el-input v-model="form.oldmajor" placeholder="请输入原专业" disabled />
          </el-form-item>
          <el-form-item label="新年级" prop="newgrade" :rules="rules2.reason5">
            <el-select v-model="form.newgrade" filterable clearable placeholder="请选择年级" style="width: 100%"
              :key="`grade-${form.newgrade}`"> <!-- 新增key强制刷新 -->
              <el-option v-for="item in grade_list" :key="item.gradeId" :label="item.gradeName" :value="item.gradeId" />
            </el-select>
          </el-form-item>
          <!-- <el-form-item label="新班级" prop="newmajor" :rules="rules2.reason6">
            <el-cascader v-model="classVlue1" placeholder="请选择班级" :show-all-levels="false" :options="ClassNameList"
              clearable filterable style="width: 100%" @change="handleChange1">
              <template slot-scope="{ node, data }">
                <span>{{ data.label }}</span>
                <span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
              </template>
          </el-cascader>
          </el-form-item> -->
          <el-form-item label="新专业" prop="newmajor" :rules="rules2.reason6">
            <!-- 1. 必须绑定 form.classVlue1；2. 加 key 强制刷新；3. 明确 props 匹配字段 -->
            <el-cascader v-model="form.classVlue1" placeholder="请选择班级" :show-all-levels="false" :options="ClassNameList"
              clearable filterable style="width: 100%" @change="handleChange1"
              :key="`cascader-${form.classVlue1 ? form.classVlue1.join('-') : 'empty'}`"
              :props="{ value: 'value', label: 'label', children: 'children' }">
              <template slot-scope="{ node, data }">
                <span>{{ data.label }}</span>
                <span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
              </template>
            </el-cascader>
          </el-form-item>
          <el-form-item label="退役证明" prop="proof">
            <image-upload v-model="form.proof" />
          </el-form-item>
          <el-form-item label="身份证" prop="idcard">
            <image-upload v-model="form.idcard" />
          </el-form-item>
          <el-form-item label="材料" prop="material">
            <image-upload v-model="form.material" />
          </el-form-item>
        </el-form>
      </el-card>

    </div>

    <div slot="footer" class="stylecard">
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>


  </div>
</template>

<script>
import { getOwnInfo, listBasic, getBasic, delBasic, addBasic, updateBasic } from "@/api/routine/basic";
import { listMate, getMate, delMate, addMate, updateMate } from "@/api/routine/mate";
import { getStudentInfoByStuId } from '@/api/routine/stuIdReissue'
import { getUserProfile } from '@/api/system/user' // 获取

import { listGrade } from '@/api/stuCQS/basedata/grade'

// 获取学生信息
import { addStudent, delStudent, doDept, getClassName, getStatus, getStudent, initOnePwd, initPwd, listStudent, updateStudent } from '@/api/stuCQS/basedata/student'
import { log } from "vxe-table";

export default {
  name: "Basic",
  dicts: ['sys_yes_no', 'sys_user_sex', 'rt_filling_college', 'sys_commit_status', 'sys_teacher_kpi_filling_year', 'rt_nation', 'rt_classes'],
  data() {
    return {
      // 年级列表
      grade_list: [],
      // 班级搜索选择
      classVlue1: [],
      // 班级名称列表
      ClassNameList: [],

      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 退伍复学申请表格数据
      basicList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        studentId: null,
        fxId: null,
        fxTime: null,
        stId: null,
        stName: null,
        fdName: null,
        sex: null,
        nations: null,
        fdQm: null,
        xwQm: null,
        erQm: null,
        xjQm: null,
        jwQm: null,
        stClass: null,
        majors: null,
        grade: null,
        college: null,
        reasons: null,
        fdIdea: null,
        twoIdea: null,
        xwIdea: null,
        xjIdea: null,
        jwIdea: null,
        zsIdea: null,
        zsStatus: null,
        times: null,
        fdStatus: null,
        xwStatus: null,
        twoStatus: null,
        xjglStatus: null,
        jwStatus: null,
        rwTime: null,
        zsTime: null,
        fdTime: null,
        xwTime: null,
        twoTime: null,
        xjTime: null,
        jwTime: null,
        datab: null,
        dataa: null,
        conversion: null,
        processId: null,
        deployId: null
      },

      // 表单参数
      form: {
        // 新增：自动填充所需的核心属性（与接口返回字段对应）
        studentId: '',
        stId: '',
        stName: '',
        sex: '',
        stClass: '',
        majors: '',
        grade: '',
        college: '',
        datab: '',
        // 保留你原有重置方法中定义的所有字段（防止重置失效）
        id: null,
        fxId: null,
        fxTime: null,
        fdName: null,
        nations: null,
        fdQm: null,
        xwQm: null,
        erQm: null,
        xjQm: null,
        jwQm: null,
        reasons: null,
        fdIdea: null,
        twoIdea: null,
        xwIdea: null,
        xjIdea: null,
        jwIdea: null,
        zsIdea: null,
        zsStatus: null,
        times: null,
        fdStatus: null,
        xwStatus: null,
        twoStatus: null,
        xjglStatus: null,
        jwStatus: null,
        rwTime: null,
        zsTime: null,
        fdTime: null,
        xwTime: null,
        twoTime: null,
        xjTime: null,
        jwTime: null,
        dataa: null,
        conversion: null,
        processId: null,
        deployId: null,
        testData: null,
        testTest: null,

        // mate
        oldgrade: '',
        oldmajor: '',
        newgrade: '',
        newmajor: '',
        proof: '',
        idcard: '',
        material: '',
        data1: '',
        data2: ''
      },
      // 表单校验
      rules: {
        reason1: [
          { required: true, message: '学号不能为空', trigger: 'blur' },
        ],
        reason2: [
          { required: true, message: '姓名不能为空', trigger: 'blur' },
        ],
        reason3: [
          { required: true, message: '辅导员不能为空', trigger: 'blur' },
        ],
        reason4: [
          { required: true, message: '请选择性别', trigger: 'blur' },
        ],
        reason5: [
          { required: true, message: '请选择民族', trigger: 'blur' },
        ],
        reason6: [
          { required: true, message: '请输入班级', trigger: 'blur' },
        ],
        reason7: [
          { required: true, message: '请输入专业', trigger: 'blur' },
        ],
        reason8: [
          { required: true, message: '请输入年级', trigger: 'blur' },
        ],
        reason9: [
          { required: true, message: '请选择学院', trigger: 'blur' },
        ],
        reason10: [
          { required: true, message: '请填写原因', trigger: 'blur' },
        ],
        reason11: [
          { required: true, message: '请选择时间', trigger: 'blur' },
        ],
        reason12: [
          { required: true, message: '请选择是否专业转换', trigger: 'blur' },
        ],
        reason13: [
          { required: true, message: '请输入联系电话', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号码', trigger: 'blur' }
        ],
      },

      // mate
      rules2: {
        reason3: [
          { required: true, message: '输入原年级', trigger: 'blur' },
        ],
        reason4: [
          { required: true, message: '输入原专业', trigger: 'blur' },
        ],
        reason5: [
          { required: true, message: '输入新年级', trigger: 'blur' },
        ],
        reason6: [
          { required: true, message: '输入新专业', trigger: 'blur' },
        ],
      },


    };
  },

  created() {
    // this.getList();
    this.getUser()
    // 新增：加载年级和班级列表
    this.listGrade()
    this.getClassNameList()
    // 移除：showData 交由 getUser 内部在数据填充后执行，避免异步冲突
    // this.showData()
  },
  methods: {

    // mate
    /** 搜索班级选择 */
    handleChange1(value) {
      console.log("级联选择值：", value);
      if (value && value.length === 3) { // 必须是三级数组
        this.form.classVlue1 = value; // 核心：同步到 form
        this.form.data1 = value[0]; // 学院ID
        this.form.data2 = value[1]; // 年级ID
        this.form.newmajor = value[2]; // 班级ID
      } else {
        this.form.classVlue1 = [];
        this.form.data1 = "";
        this.form.data2 = "";
        this.form.newmajor = "";
      }
    },

    /** 获取当前登录信息 */
    getUser() {
      this.loading = true
      getUserProfile().then(response => {
        // this.roleGroup = response.roleGroup
        // console.log("response.data",response.data)
        // this.form.studentId = response.data.userId
        getOwnInfo().then(res => {
          if (res.data) {
            // console.log("信息接口", res.data.stuId)
            // this.form.studentId = res.data.stuId
            this.form.stId = res.data.stuNo
            this.form.stName = res.data.stuName
            this.form.sex = res.data.gender
            this.form.majors = res.data.majorName
            this.form.stClass = res.data.className
            this.form.grade = res.data.gradeName
            this.form.datab = res.data.stuPhone
            this.form.college = res.data.deptName

            // 新增：自动填充原年级和原专业
            this.form.oldgrade = this.form.grade
            this.form.oldmajor = this.form.majors
            
              listStudent({ pageNum: 1, pageSize: 10, name: this.form.stName }).then(response => {
                this.form.studentId = response.rows[0].stuId
                console.log("获取到的学号",response.rows[0].stuId)
              })

            // 新增1：强制触发Vue视图更新（解决响应式延迟）
            this.$forceUpdate()
            // 新增2：数据填充完成后，再执行 showData（兼容编辑场景）
            this.showData()
          }
        }).finally(() => {
          // 新增3：请求完成后重置loading
          this.loading = false
        })
        this.getList();
      })
    },


    // 修改数据（终极强制回显版本）
    showData() {
      if (this.$route.query.id != undefined) {
        console.log("===== 编辑回显开始 =====", this.$route.query.id);
        getBasic(this.$route.query.id).then(async (basicRes) => {
          // 1. 合并主表数据（用 $set 保证响应式）
          this.$set(this, "form", { ...this.form, ...basicRes.data });

          // 2. 获取 mate 表（转专业数据）
          const mateData = await this.getMateData(basicRes.data.stId);
          console.log("mate 表数据：", mateData);

          if (mateData) {
            // 3. 统一所有 ID 为字符串（级联必须严格匹配类型）
            const newgradeStr = mateData.newgrade ? String(mateData.newgrade) : "";
            const data1Str = mateData.data1 ? String(mateData.data1) : ""; // 学院ID
            const data2Str = mateData.data2 ? String(mateData.data2) : ""; // 年级ID
            const newmajorStr = mateData.newmajor ? String(mateData.newmajor) : ""; // 班级ID

            // 4. 等待年级、班级列表完全加载（必须等）
            await this.waitForListsLoaded();
            console.log("年级列表：", this.grade_list);
            console.log("班级级联列表：", this.ClassNameList);

            // --- 新年级回显（已正常，保留）---
            const gradeItem = this.grade_list.find(item => String(item.gradeId) === newgradeStr);
            if (gradeItem) {
              this.$set(this.form, "newgrade", gradeItem.gradeId);
              console.log("新年级匹配成功：", gradeItem.gradeName);
            } else {
              console.warn("新年级未匹配：", newgradeStr);
            }

            // --- 新班级（级联）回显（核心修复）---
            if (data1Str && data2Str && newmajorStr) {
              // 构造三级回显数组（必须是 [学院ID, 年级ID, 班级ID]）
              const cascadeValue = [data1Str, data2Str, newmajorStr];
              console.log("级联回显值：", cascadeValue);

              // 验证：检查级联列表中是否存在该路径（关键排查）
              const hasPath = this.checkCascaderPath(this.ClassNameList, cascadeValue);
              if (hasPath) {
                // 用 $set 赋值，保证响应式
                this.$set(this.form, "classVlue1", cascadeValue);
                console.log("级联回显成功！");
              } else {
                console.error("级联路径不存在：", cascadeValue, "→ 检查班级列表结构与 value 类型");
              }
            }

            // 5. 回显其他字段
            this.$set(this.form, "oldgrade", mateData.oldgrade || basicRes.data.grade);
            this.$set(this.form, "oldmajor", mateData.oldmajor || basicRes.data.majors);
            this.$set(this.form, "proof", mateData.proof || "");
            this.$set(this.form, "idcard", mateData.idcard || "");
            this.$set(this.form, "material", mateData.material || "");

            // 6. 强制刷新视图
            this.$forceUpdate();
            console.log("===== 编辑回显完成 =====");
          }
        });
      }
    },

    // 新增：辅助方法 → 检查级联路径是否存在（排查用）
    checkCascaderPath(options, path) {
      let tempOptions = options;
      for (let i = 0; i < path.length; i++) {
        const target = tempOptions.find(item => String(item.value) === String(path[i]));
        if (!target) return false;
        if (i < path.length - 1 && !target.children) return false;
        tempOptions = target.children;
      }
      return true;
    },


    // 辅助：等待年级/班级列表加载完成
    waitForListsLoaded() {
      return new Promise((resolve) => {
        const check = () => {
          if (this.grade_list.length > 0 && this.ClassNameList.length > 0) {
            resolve();
          } else {
            setTimeout(check, 50); // 每50ms检查一次，直到加载完成
          }
        };
        check();
      });
    },

    // 获取mate表数据（卡片2专属）
    getMateData(stId) {
      return new Promise((resolve) => {
        listMate({ stId: stId }).then(res => {
          if (res.rows && res.rows.length > 0) {
            resolve(res.rows[0]); // 取第一条匹配的数据
          } else {
            resolve({}); // 无数据返回空对象
          }
        }).catch(() => {
          resolve({}); // 异常返回空对象
        });
      });
    },

    /** 获取班级名称列表 */
    getClassNameList() {
      getClassName().then(res => {
        // 1. 确保返回数据是三级结构（学院→年级→班级）
        this.ClassNameList = res.data || [];
        console.log("班级级联列表（最终）：", this.ClassNameList);

        // 2. 强制所有 value 为字符串（避免类型不匹配）
        const formatCascader = (list) => {
          return list.map(item => {
            item.value = String(item.value);
            if (item.children && item.children.length) {
              item.children = formatCascader(item.children);
            }
            return item;
          });
        };
        this.ClassNameList = formatCascader(this.ClassNameList);
        console.log("格式化后（value 全为字符串）：", this.ClassNameList);
      }).catch(err => {
        console.error("获取班级列表失败：", err);
        this.ClassNameList = [];
      });
    },
    /** 获取年级列表 */
    async listGrade() {
      try {
        let res = await listGrade()
        if (res.code == 200) {
          this.grade_list = [...res.rows]
        }
      } catch (error) {
        console.error('获取年级列表失败:', error)
      }
    },

    // 填写学号时自动获取其他信息 + 同步赋值studentId
    changeGet() {
      // 1. 先确定stId（优先取form.stId，无则取路由参数）
      this.form.stuId = this.form.stId ? this.form.stId : this.$route.query.stId;

      // 2. 并行请求：同时获取学生信息和登录用户信息（提升效率）
      Promise.all([
        // 请求1：根据stuId获取学生信息
        getStudentInfoByStuId(this.form.stuId),
        // 请求2：获取登录用户信息（用于赋值studentId）
        getUserProfile()
      ]).then(([studentRes, userRes]) => {
        // 处理学生信息请求的结果
        if (studentRes.data == null) {
          this.$message.error('学号不存在');
          return;
        }
        // 赋值学生信息到form
        this.form = studentRes.data;
        this.form.stId = studentRes.data.stuNo;
        this.form.stName = studentRes.data.studentName;
        this.form.college = studentRes.data.departmentName;
        this.majors = studentRes.data.className;
        this.form.sex = studentRes.data.gender;
        this.form.grade = studentRes.data.gradeName;

        listStudent({ pageNum: 1, pageSize: 10, name: this.form.stName }).then(response => {
          this.form.studentId = response.rows[0].stuId
        })

      }).catch(err => {
        // 捕获请求异常
        console.error("请求失败：", err);
        this.$message.error('数据获取失败，请重试');
      });
    },

    /** 查询退伍复学申请列表 */
    getList() {
      this.loading = true;
      listBasic(this.queryParams).then(response => {
        this.basicList = response.rows;
        this.total = response.total;
        this.loading = false;
        console.log(this.basicList)
      });
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },

    // 表单重置
    reset() {
      this.form = {
        id: null,
        fxId: null,
        fxTime: null,
        stId: null,
        stName: null,
        fdName: null,
        sex: null,
        nations: null,
        fdQm: null,
        xwQm: null,
        erQm: null,
        xjQm: null,
        jwQm: null,
        stClass: null,
        majors: null,
        grade: null,
        college: null,
        reasons: null,
        fdIdea: null,
        twoIdea: null,
        xwIdea: null,
        xjIdea: null,
        jwIdea: null,
        zsIdea: null,
        zsStatus: null,
        times: null,
        fdStatus: null,
        xwStatus: null,
        twoStatus: null,
        xjglStatus: null,
        jwStatus: null,
        rwTime: null,
        zsTime: null,
        fdTime: null,
        xwTime: null,
        twoTime: null,
        xjTime: null,
        jwTime: null,
        datab: null,
        dataa: null,
        conversion: null,
        processId: null,
        deployId: null,
        studentId: null,
        testData: null,
        testTest: null
      };
      this.resetForm("form");
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加退伍复学申请";
    },

    /** 修改按钮操作（修复版） */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      // 1. 先并行加载年级、班级列表
      Promise.all([this.listGrade(), this.getClassNameList()])
        .then(() => {
          // 2. 再获取主表数据
          return getBasic(id);
        })
        .then(response => {
          this.$set(this, "form", response.data);
          this.open = true;
          this.title = "修改退伍复学申请";
          // 3. DOM 渲染完成后，再执行回显
          this.$nextTick(() => {
            this.showData();
          });
        })
        .catch(err => {
          console.error("编辑加载失败：", err);
        });
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(async (valid) => { // 改为async
        if (valid) {
          try { // 新增异常捕获
            if (this.form.id != null) {
              // 重置状态
              this.form.zsStatus = 0
              this.form.fdStatus = 0
              this.form.xwStatus = 0
              this.form.twoStatus = 0
              this.form.Status = 0
              this.form.jwStatus = 0
              this.form.testData = 0

              this.form.fdIdea = ""
              this.form.xwIdea = ""
              this.form.twoIdea = ""
              this.form.xjIdea = ""
              this.form.jwIdea = ""

              // 等待updateBasic执行完成
              const basicRes = await updateBasic(this.form);
              if (basicRes.code !== 200) {
                this.$modal.msgError("修改主表数据失败");
                return;
              }

              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();

              // 关键：查询mate表主键，用于更新（而不是新增）
              const mateList = await listMate({ stId: this.form.stId });
              const mateId = mateList.rows && mateList.rows.length > 0 ? mateList.rows[0].id : null;

              this.dataform = {
                id: mateId, // 新增mate表主键，确保updateMate能定位记录
                stId: this.form.stId,
                stName: this.form.stName,
                times: null,
                college: this.form.college,
                oldgrade: this.form.oldgrade,
                oldmajor: this.form.oldmajor,
                newgrade: this.form.newgrade,
                newmajor: this.form.newmajor,
                proof: this.form.proof,
                idcard: this.form.idcard,
                material: this.form.material,
                data1: this.form.data1,
                data2: this.form.data2,
                finaldata1: this.form.data1,
                finaldata2: this.form.data2,
                finalmajor: this.form.newmajor,
                finallabel:this.form.newgrade,

              };

              // 有mateId则更新，无则新增（修复原始终addMate的问题）
              if (mateId) {
                await updateMate(this.dataform); // 改为await
              } else {
                await addMate(this.dataform); // 改为await
              }

              this.open = false;
              this.getList();
              // 页面跳转（所有异步完成后再跳转）
              this.$router.push({
                path: '/routine/dis/appli',
              })

            } else {
              // 新增操作
              const basicRes = await addBasic(this.form); // 改为await
              if (basicRes.code === 200) {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
                console.log(this.form.stId)
                this.dataform = {
                  id: null,
                  stId: this.form.stId,
                  stName: this.form.stName,
                  times: null,
                  college: this.form.college,
                  oldgrade: this.form.oldgrade,
                  oldmajor: this.form.oldmajor,
                  newgrade: this.form.newgrade,
                  newmajor: this.form.newmajor,
                  proof: this.form.proof,
                  idcard: this.form.idcard,
                  material: this.form.material,
                  data1: this.form.data1,
                  data2: this.form.data2,
                  finaldata1: this.form.data1,
                  finaldata2: this.form.data2,
                  finalmajor: this.form.newmajor,
                  finallabel:this.form.newgrade,
                };
                await addMate(this.dataform); // 改为await

                this.open = false;
                this.getList();

                // 页面跳转（所有异步完成后再跳转）
                this.$router.push({
                  path: '/routine/dis/appli',
                })
              } else {
                this.$modal.msgError("新增主表数据失败");
              }
            }
          } catch (error) {
            // 异常处理
            console.error("提交失败：", error);
            this.$modal.msgError("操作失败，请重试");
          }
        }
      });
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除退伍复学申请编号为"' + ids + '"的数据项？').then(function () {
        return delBasic(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },

    /** 导出按钮操作 */
    handleExport() {
      this.download('routine/basic/export', {
        ...this.queryParams
      }, `basic_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

<style>
.box-card1 {
  width: 600px;
  max-width: 100%;
  /* 新增：适配小屏幕，避免溢出 */
  text-align: center;
  margin: 0 auto;
  /* 替代原margin-left，实现水平居中更优雅 */
  padding: 20px;
  /* 新增：内边距，提升内容呼吸感 */
  background-color: #fff;
  /* 新增：卡片背景色 */
  border-radius: 8px;
  /* 新增：圆角，增强视觉友好度 */
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  /* 新增：阴影，突出卡片层次 */
  box-sizing: border-box;
  /* 新增：保证width包含padding和border */
  white-space: nowrap
}

.stylecard {
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>