<template>
  <div class="app-container">
    <el-card class="box-card">
      <el-steps :active="active" :finish-status="finishStatus">
        <el-step title="学生申请" description="提交申请,填写补办的原因以及相片"></el-step>
        <el-step title="辅导员审核" :description="changeActive(form.inspectionProgress)"></el-step>
        <el-step title="学工处理"
          :description="`${form.isPay === 0 ? '未缴费:' : '已缴费,备注:'}` + `${$route.query.jwcCmt ? $route.query.jwcCmt : '等待缴费,记录缴费金额'}`"></el-step>
        <el-step title="完成制作" :description="getCompletionDescription()"></el-step>
      </el-steps>
    </el-card>
    <el-card class="box-card" style="margin-top: 20px;">
      <div class="titleNav">基本信息</div>
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <div class="formItem">
          <div>
            <el-form-item label="学号" prop="stuNo">
              <el-input v-model="form.stuNo" placeholder="请输入学号" @blur="changeGet" :disabled="$route.query.inspectionProgress == -1 ? isDisabledStuNo : isDisabled" />
            </el-form-item>
            <el-form-item label="出生日期" prop="birthday">
              <!-- <el-input v-model="form.createTime" placeholder="请输入出生日期" /> -->
              <el-date-picker v-model="form.birthday" align="right" type="date" placeholder="选择日期"
                value-format="yyyy-MM-dd" style="width: 100%;">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="家庭所在地" prop="hksz2">
              <el-cascader :options="areaOptions" v-model="form.homeLocation" clearable filterable @change="hkszChange" style="width: 100%"></el-cascader>
            </el-form-item>
            <el-form-item label="家庭详细地址" prop="birthplace">
              <el-input v-model="form.birthplace" placeholder="请输入家庭详细地址" />
            </el-form-item>
            <el-form-item label="民族" prop="mz">
              <el-select clearable v-model="form.mz" placeholder="请选择民族" style="width: 100%">
                <el-option v-for="dict in dict.type.rt_nation" :key="dict.value" :label="dict.label"
                  :value="dict.value" />
              </el-select>
            </el-form-item>
          </div>
          <div>
            <el-form-item label="学生名称" prop="studentName">
              <el-input v-model="form.studentName" placeholder="请输入学生名称" :disabled="$route.query.inspectionProgress == -1 ? isDisabledStuNo : isDisabled" />
            </el-form-item>
            <el-form-item label="性别" prop="gender">
              <el-input v-model="form.gender" placeholder="请输入性别" :disabled="$route.query.inspectionProgress == -1 ? isDisabledStuNo : isDisabled" />
            </el-form-item>
            <el-form-item label="籍贯" prop="nativePlace">
              <el-cascader :options="areaOptions" v-model="form.nativePlace" clearable filterable
                @change="addressChange" style="width: 100%"></el-cascader>
                <!-- <el-cascader :options="areaOptions" v-model="form.nativePlace" clearable filterable v-else
                @change="addressChange" style="width: 100%"></el-cascader> -->
            </el-form-item>
            <el-form-item label="联系电话" prop="phoneNumber">
              <el-input v-model="form.phoneNumber" placeholder="请输入联系电话" />
            </el-form-item>
            <el-form-item label="乘火车区间" prop="railwayStation">
              <el-input v-model="form.railwayStation" placeholder="请输入乘火车区间(南宁到XX站)" />
            </el-form-item>
          </div>
          <!-- <div>
            <el-form-item label="照片" prop="photo">
              <image-upload v-model="form.photo" />
            </el-form-item>
          </div> -->
        </div>
      </el-form>
    </el-card>

    <el-card class="box-card" style="margin-top: 20px;">
      <div class="titleNav">办理状态</div>
      <div style="margin-bottom: 20px;">
        <el-tag v-if="form.inspectionProgress >= 3" type="success">已完成制作</el-tag>
        <el-tag v-else-if="form.inspectionProgress >= 2" type="warning">学工处理中</el-tag>
        <el-tag v-else-if="form.inspectionProgress >= 1" type="primary">辅导员审核中</el-tag>
        <el-tag v-else-if="form.inspectionProgress === 0" type="info">待审核</el-tag>
        <el-tag v-else type="danger">申请被驳回</el-tag>
      </div>
      <div class="titleNav">办理信息</div>
      <el-form ref="form" :model="form" :rules="rules" label-width="90px">
        <div class="formItem">
          <div>
            <el-form-item label="年级" prop="gradeName">
              <el-input v-model="form.gradeName" placeholder="请输入年级" :disabled="$route.query.inspectionProgress == -1 ? isDisabledStuNo : isDisabled" />
            </el-form-item>
            <el-form-item label="班级" prop="className">
              <el-input v-model="form.className" placeholder="请输入班级" :disabled="$route.query.inspectionProgress == -1 ? isDisabledStuNo : isDisabled" />
            </el-form-item>
            <el-form-item label="宿舍楼" prop="dormitoryBuilding">
              <el-input v-model="form.dormitoryBuilding" placeholder="请输入宿舍楼" />
            </el-form-item>
            <el-form-item label="宿舍号" prop="dormitoryNumber">
              <el-input v-model="form.dormitoryNumber" placeholder="请输入宿舍号" />
            </el-form-item>
          </div>
          <div>
            <el-form-item label="学院" prop="departmentName">
              <el-input v-model="form.departmentName" placeholder="请输入学院" :disabled="$route.query.inspectionProgress == -1 ? isDisabledStuNo : isDisabled" />
            </el-form-item>
            <el-form-item label="入学时间" prop="enrollmentTime">
              <el-date-picker v-model="form.enrollmentTime" align="right" type="date" placeholder="选择日期"
                value-format="yyyy-MM-dd" style="width: 100%;">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="申请时间" prop="applyTime">
              <el-date-picker v-model="form.applyTime" align="right" type="date" placeholder="选择日期"
                value-format="yyyy-MM-dd HH:mm:ss" style="width: 100%;">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="补办原因" prop="reason">
              <el-input v-model="form.reason" placeholder="请输入补办原因" />
            </el-form-item>
          </div>
          <div>
            <el-form-item label="照片" prop="photo">
              <image-upload v-model="form.photo" />
            </el-form-item>
          </div>
        </div>
      </el-form>
    </el-card>
    <div slot="footer" class="dialog-footer" style="text-align: right; margin-top: 20px;">
      <!-- 新申请时显示提交申请按钮 -->
      <el-button v-if="!form.id" type="primary" @click="submitForm(1)">提交申请</el-button>
      
      <!-- 已有申请但未完成制作时显示修改提交申请按钮 -->
      <el-button v-if="form.id && form.inspectionProgress < 3" type="primary"
        @click="submitForm(1)">修改提交申请</el-button>
      
      <!-- 已完成制作时显示继续提交申请按钮 -->
      <el-button v-if="form.id && form.inspectionProgress >= 3" type="primary"
        @click="submitNewApplication">继续提交申请</el-button>
      
      <!-- 未完成制作时显示取消申请按钮 -->
      <el-button v-if="form.id && form.inspectionProgress < 3" 
        type="danger" @click="cancelApplication">取消申请</el-button>
      
      <!-- 已完成制作时显示取消申请按钮（不可点击） -->
      <el-button v-if="form.id && form.inspectionProgress >= 3" 
        type="info" disabled @click="showCompletedMessage">当前审核已完成，不可取消</el-button>
      
      <el-button type="primary" @click="printing">打印学生证申请表</el-button>
      <el-button @click="$router.push('/routine/sicr/stuIdReissueLIst')">返 回</el-button>
    </div>
  </div>
</template>

<script>
import { getStuIdReissue, addStuIdReissue, updateStuIdReissue, getStudentInfoByStuId, getStuIdReissueStatus, delStuIdReissue } from "@/api/routine/stuIdReissue";
import { listClass } from "@/api/stuCQS/basedata/class";
import {
  pcaTextArr, // 省市区联动数据,纯汉字
} from 'element-china-area-data'
export default {
  name: "StuIdReissue",
  dicts: ['rt_nation'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      // 学生证补办表格数据
      stuIdReissueList: [],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        reason: [
          { required: true, message: "补办原因不能为空", trigger: "blur" }
        ],
        inspectionProgress: [
          { required: true, message: "审核状态不能为空", trigger: "blur" }
        ],
        stuNo: [
          { required: true, message: "学号不能为空", trigger: "blur" }
        ],
        stuId: [
          { required: true, message: "学号不能为空", trigger: "blur" }
        ],
        studentName: [
          { required: true, message: "学生名称不能为空", trigger: "blur" }
        ],
        phoneNumber: [
          { required: true, message: "联系电话不能为空", trigger: "blur" }
        ],
        enrollmentTime: [
          { required: true, message: "入学时间不能为空", trigger: "blur" }
        ],
        railwayStation: [
          { required: true, message: "乘火车区间不能为空", trigger: "blur" }
        ],
        birthplace: [
          { required: true, message: "家庭详细地址不能为空", trigger: "blur" }
        ]
      },
      // 申请进展
      active: 1,
      showRole: 0,
      // 查询到的审核信息
      stuMultiLevelReview: {},
      // 审核处理人
      transactor: '',
      // 省市区
      areaOptions: pcaTextArr,
      // 控件禁用
      isDisabled: false,
      // 审核进度状态
      finishStatus: 'success',
      isDisabledStuNo: false
    };
  },
  watch: {
    "$route.query.id": {
      immediate: true,
      handler() {
        this.form = {}
        this.active = 1
        this.finishStatus = 'success'
        if (this.$route.query.id !== undefined) {
          this.handleUpdate()
          if (this.$route.query.inspectionProgress >= 0) {
            this.isDisabled = true
            this.finishStatus = 'success'
          } else if (this.$route.query.inspectionProgress == -1) {
            this.isDisabledStuNo = true
            this.finishStatus = 'error'
          } else {
            this.finishStatus = 'error'
          }
        } else {
          this.reset()
          this.isDisabled = false
          this.isDisabledStuNo = false
          this.finishStatus = 'success'
          this.active = 1
        }
      }
    }
  },
  created() {
    // this.getList();
    let temp = this.$store.getters.roles;
    temp.map(x => {
      if (x == "admin") {
        this.showRole = 1;
      }

      if (x == "test") { //学工
        this.showRole = 1;
      }

      if (x == "stumanger") { //学务
        this.showRole = 2;
      }

      if (x == "testteacher") { //辅导员
        this.showRole = 3;
      }

      if (x == "teststu") { //学生
        this.showRole = 4;
      }
    });
  },
  methods: {
    // 填写学号时自动获取其他信息
    changeGet() {
      this.form.stuId = this.form.stuNo ? this.form.stuNo : this.$route.query.stuNo
      getStudentInfoByStuId(this.form.stuId).then(response => {
        if (response.data == null) {
          this.$message.error('学号不存在')

          return
        }
        this.form = response.data
        listClass({ // 根据班级名称查询班级信息
          className: this.form.className
        }).then(response => {
          // this.classList = response.rows;
          if (response.rows && response.rows.length > 0 && response.rows[0].teacher) {
            this.form.counsellorName = response.rows[0].teacher.name
            this.form.counsellorId = response.rows[0].teacher.teacherId
          } else {
            console.warn('未找到班级信息或辅导员信息');
          }
        }).catch(error => {
          console.error('查询班级信息失败:', error);
        });
      });
    },
    // 进度变化时改变文字提示
    changeActive(active) {
      const progress = Number(this.form.inspectionProgress);
      if (progress === -1) {
        return '申请被驳回,备注:申请不通过,' + this.$route.query.fdyCmt;
      } else if (progress === 0) {
        return '辅导员审核学生补办请求通不通过';
      } else if (progress === 1) {
        return '申请通过,备注:' + this.$route.query.fdyCmt;
      } else if (progress === 2) {
        return '学工处理中,备注:' + (this.$route.query.jwcCmt || '等待缴费,记录缴费金额');
      } else if (progress >= 3) {
        return '已完成制作,备注:学生证制作完成';
      } else {
        return '辅导员审核学生补办请求通不通过';
      }
    },
    // 根据inspectionProgress确定当前步骤
    calculateActive() {
      const progress = Number(this.form.inspectionProgress);
      console.log('调试信息 - calculateActive中的progress:', progress, '类型:', typeof progress);
      if (progress >= 3) {
        console.log('调试信息 - 返回步骤4 (完成制作)');
        return 4; // 完成制作时返回4，对应步骤条的最后一个步骤
      } else if (progress >= 2) {
        console.log('调试信息 - 返回步骤3 (学工处理)');
        return 3; // 学工处理
      } else if (progress >= 1) {
        console.log('调试信息 - 返回步骤2 (辅导员审核)');
        return 2; // 辅导员审核
      } else {
        console.log('调试信息 - 返回步骤1 (学生申请)');
        return 1; // 学生申请
      }
    },
    // 获取完成制作步骤的动态描述
    getCompletionDescription() {
      const progress = Number(this.form.inspectionProgress);
      if (progress >= 3) {
        return '学生证制作已完成，请及时领取';
      } else if (progress >= 2) {
        return '等待学工完成学生证制作';
      } else {
        return '学工完成学生证制作';
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        stuName: null,
        photo: null,
        reason: null,
        stuId: null,
        stuNo: null,
        createTime: null,
        jg: null,
        hksz2: null
      };
      this.active = 1
      this.resetForm("form");
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 修改按钮操作 */
    handleUpdate() {
      this.reset();
      const id = this.$route.query && this.$route.query.id
      getStuIdReissue(id).then(response => {
        this.form = response.data;
        this.form.studentName = this.form.stuName
        // this.form.stuName = this.form.studentName
        console.log('调试信息 - inspectionProgress:', response.data.inspectionProgress, '类型:', typeof response.data.inspectionProgress);
        console.log('调试信息 - calculateActive():', this.calculateActive());
        
        if (response.data.inspectionProgress === -1) {
          this.active = 1; // 驳回时显示学生申请步骤
          this.finishStatus = 'error'
        } else {
          this.active = this.calculateActive();
          // 根据审核进度设置完成状态
          if (Number(response.data.inspectionProgress) >= 3) {
            this.finishStatus = 'success'
          } else if (Number(response.data.inspectionProgress) >= 0) {
            this.finishStatus = 'success'
          } else {
            this.finishStatus = 'error'
          }
        }
        console.log('调试信息 - active:', this.active, '类型:', typeof this.active);
        console.log('调试信息 - finishStatus:', this.finishStatus);
        console.log('调试信息 - 步骤条配置检查 - active值应为3时:', this.active === 3, 'finishStatus:', this.finishStatus);
        
        // 地区转换
        this.form.nativePlace = this.form.jg !== null ? this.parseSelectedPath(this.form.jg) : '暂无填写'
        // 地区转换
        this.form.homeLocation = this.form.hksz2 !== null ? this.parseSelectedPath(this.form.hksz2) : '暂无填写'
      });
    },
    /** 提交按钮 */
    submitForm(active) {
      this.$modal.loading('正在努力加载中,请稍等...')
      // 学生提交申请状态
      this.form.inspectionProgress = 0
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateStuIdReissue(this.form).then(response => {
              this.$modal.closeLoading()
              console.log('修改响应:', response);
              if (response.code === 200) {
                this.$modal.msgSuccess("修改成功");
                this.active = active
                this.finishStatus = 'success'
                this.isDisabled = true
                // 修改成功后修改路由参数
                this.$router.push({ path: this.$route.path, query: { id: this.form.id, stuNo: this.form.stuNo, inspectionProgress: this.form.inspectionProgress } });
              }
              // 移除else分支，让全局拦截器处理所有非200的情况
            }).catch(error => {
              this.$modal.closeLoading()
              console.log('修改捕获到错误 - error:', error);
              // 如果error是字符串'error'，说明是全局拦截器返回的Promise.reject('error')
              // 这种情况下，全局拦截器已经显示了错误信息，这里不再重复显示
              if (error === 'error') {
                console.log('修改业务错误已由全局拦截器处理');
                return;
              }
              // 忽略由于路由跳转/刷新导致的请求取消错误，避免误报网络错误
              const isCanceled = error && (
                error.code === 'ERR_CANCELED' ||
                error.message === 'canceled' ||
                error.message === 'Cancel' ||
                error.__CANCEL__ === true ||
                (typeof error.message === 'string' && /cancel/i.test(error.message))
              );
              if (isCanceled) {
                console.log('请求被取消，已忽略该错误提示');
                return;
              }
              // 只处理真正的网络错误
              if (!error.response) {
                this.$modal.msgError("网络连接失败，请检查网络");
              }
            });
          } else {
            addStuIdReissue(this.form).then(response => {
              this.$modal.closeLoading()
              console.log('提交响应:', response);
              if (response.code === 200) {
                this.$modal.msgSuccess("提交申请成功");
                this.active = active
                this.finishStatus = 'success'
                this.isDisabled = true
                // 新增成功后跳转到详情页面
                console.log('提交成功，更新表单状态');
                this.form.inspectionProgress = 0;
                // 设置表单ID（如果后端返回了ID）
                if (response.data && response.data.id) {
                  this.form.id = response.data.id;
                }
                // 更新路由参数，不刷新页面
                setTimeout(() => {
                  this.$message.info('申请提交成功');
                  // 使用replace更新路由，避免强制刷新
                  if (this.form.id) {
                    this.$router.replace({ 
                      path: this.$route.path, 
                      query: { 
                        id: this.form.id, 
                        stuNo: this.form.stuNo, 
                        inspectionProgress: this.form.inspectionProgress 
                      } 
                    });
                  }
                }, 1000);
              }
            }).catch(error => {
              this.$modal.closeLoading()
              console.log('提交捕获到错误 - error:', error);
              // 如果error是字符串'error'，说明是全局拦截器返回的Promise.reject('error')
              // 这种情况下，全局拦截器已经显示了错误信息，这里不再重复显示
              if (error === 'error') {
                console.log('提交业务错误已由全局拦截器处理');
                return;
              }
              // 忽略由于路由跳转/刷新导致的请求取消错误
              const isCanceled = error && (
                error.code === 'ERR_CANCELED' ||
                error.message === 'canceled' ||
                error.message === 'Cancel' ||
                error.__CANCEL__ === true ||
                (typeof error.message === 'string' && /cancel/i.test(error.message))
              );
              if (!error.response) {
                this.$modal.msgError("网络连接失败，请检查网络");
              }
            });
          }
        } else {
          this.$modal.closeLoading()
          this.$modal.msgError("请完善必填信息");
        }
      });
    },
    // el-cascader选择处理
    addressChange(arr) {
      this.form.jg = arr[0] + '/' + arr[1] + '/' + arr[2]
    },
    // el-cascader选择处理
    hkszChange(arr) {
      this.form.hksz2 = arr[0] + '/' + arr[1] + '/' + arr[2]
    },
    // 地区回显到el-cascader
    parseSelectedPath(pathString) {
      const pathArray = pathString.split('/');
      // 假设 options 已经被正确设置,并且可以通过遍历找到对应的值
      let currentLevel = this.areaOptions;
      const selectedOptions = [];
      for (let i = 0; i < pathArray.length; i++) {
        const found = currentLevel.find(item => item.label === pathArray[i]);
        if (found) {
          selectedOptions.push(found.value);
          currentLevel = found.children || [];
        } else {
          // 处理未找到的情况,例如返回空数组或显示错误
          break;
        }
      }
      return selectedOptions;
    },
    // 跳转打印页面
    printing() {
      this.$router.push({
        path: '/routine/sicr/studentIdPrinting',
        query: {
          listId: this.form.id || null,
        },
      })
    },
    // 继续提交申请（已完成制作后可重新申请）
    submitNewApplication() {
      this.$confirm('您已完成制作，是否要重新提交新的申请？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 重置表单为新申请状态
        this.reset();
        this.isDisabled = false;
         this.isDisabledStuNo = false;
         this.finishStatus = 'success';
         this.active = 1;
        // 清除路由参数，进入新申请模式
        this.$router.push({ path: this.$route.path });
        this.$message.success('已重置为新申请状态，请填写申请信息');
      }).catch(() => {
        this.$message.info('已取消操作');
      });
    },
    // 取消申请
    cancelApplication() {
      this.$confirm('确认要取消此申请吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 调用删除接口
        this.$modal.loading('正在取消申请...');
        delStuIdReissue(this.form.id).then(response => {
          this.$modal.closeLoading();
          this.$modal.msgSuccess('申请已取消');
          // 返回列表页面
          this.$router.push('/routine/sicr/stuIdReissueLIst');
        }).catch(() => {
          this.$modal.closeLoading();
        });
      }).catch(() => {
        this.$message.info('已取消操作');
      });
    },
    // 显示已完成消息
    showCompletedMessage() {
      this.$message.info('当前审核已完成，不可取消');
    }
  }
};
</script>

<style scoped>
.titleNav {
  font-size: 20px;
  font-weight: bold;
  margin: 10px 0 20px 0;
}

.titleNav::before {
  content: "";
  margin-right: 10px;
  border: 3px solid rgb(64, 158, 255);
}

.formItem {
  display: flex;
}

.formItem>div {
  flex: 1;
}
</style>
