<template>
	<view class="knzz-gl-apply">
		<!-- 选项卡容器 -->
		<view class="tabs-container">
			<view class="tabs-header">
				<view class="tab-item" :class="{ active: activeTab === 0 }" @click="switchTab(0)">
					<uni-icons type="contact" size="12" :color="activeTab === 0 ? '#409EFF' : '#666'"></uni-icons>
					<text class="tab-text">基本信息</text>
				</view>
				<view class="tab-item" :class="{ active: activeTab === 1 }" @click="switchTab(1)">
					<uni-icons type="home" size="12" :color="activeTab === 1 ? '#409EFF' : '#666'"></uni-icons>
					<text class="tab-text">家庭经济情况</text>
				</view>
				<view class="tab-item" :class="{ active: activeTab === 2 }" @click="switchTab(2)">
					<uni-icons type="compose" size="12" :color="activeTab === 2 ? '#409EFF' : '#666'"></uni-icons>
					<text class="tab-text">学习情况</text>
				</view>
				<view class="tab-item" :class="{ active: activeTab === 3 }" @click="switchTab(3)">
					<uni-icons type="chat" size="12" :color="activeTab === 3 ? '#409EFF' : '#666'"></uni-icons>
					<text class="tab-text">申请理由</text>
				</view>
				<view class="tab-item" :class="{ active: activeTab === 4 }" @click="switchTab(4)">
					<uni-icons type="document" size="12" :color="activeTab === 4 ? '#409EFF' : '#666'"></uni-icons>
					<text class="tab-text">审核意见</text>
				</view>
			</view>
		</view>

		<!-- 表单内容区域 -->
		<scroll-view scroll-y class="form-scroll" :style="{ height: formScrollHeight }">
			<view class="form-wrapper">
				<!-- 1. 基本信息标签页 -->
				<view v-show="activeTab === 0" class="tab-panel">
					<view class="form-card">
							<view class="card-title">学生基本信息</view>
							
							<view class="form-item">
								<label class="form-label"><span class="red-tip">*</span>学号</label>
								<input v-model="formData.stuNo" placeholder="请输入学号" class="form-input" :disabled="type === 'detail'"></input>
							</view>
							<view class="form-item">
								<label class="form-label"><span class="red-tip">*</span>姓名</label>
								<input v-model="formData.stuName" placeholder="请输入姓名" class="form-input" :disabled="type === 'detail'"></input>
							</view>
							<view class="form-item">
								<label class="form-label"><span class="red-tip">*</span>性别</label>
								<picker mode="selector" :range="genderOptions" :range-key="'text'" v-model="formData.gender" @change="handleGenderChange" :disabled="type === 'detail'">
									<view class="picker-input">
										{{ formData.gender ? formData.gender : '请选择性别' }}
									</view>
								</picker>
							</view>
							<view class="form-item">
								<label class="form-label"><span class="red-tip">*</span>民族</label>
								<input v-model="formData.mz" placeholder="请输入民族" class="form-input" :disabled="type === 'detail'"></input>
							</view>
							<view class="form-item">
								<label class="form-label"><span class="red-tip">*</span>政治面貌</label>
								<input v-model="formData.zzmm" placeholder="请输入政治面貌" class="form-input" :disabled="type === 'detail'"></input>
							</view>
							<view class="form-item">
								<label class="form-label"><span class="red-tip">*</span>班级</label>
								<input v-model="formData.className" placeholder="请输入班级" class="form-input" :disabled="type === 'detail'"></input>
							</view>
							<view class="form-item">
								<label class="form-label"><span class="red-tip">*</span>学院</label>
								<input v-model="formData.deptName" placeholder="请输入学院" class="form-input" :disabled="type === 'detail'"></input>
							</view>
							<view class="form-item">
								<label class="form-label"><span class="red-tip">*</span>专业</label>
								<input v-model="formData.majorName" placeholder="请输入专业" class="form-input" :disabled="type === 'detail'"></input>
							</view>
							<view class="form-item">
								<label class="form-label"><span class="red-tip">*</span>联系电话</label>
								<input v-model="formData.stuPhone" placeholder="请输入联系电话" class="form-input" type="number" :disabled="type === 'detail'"></input>
							</view>
							<view class="form-item">
								<label class="form-label"><span class="red-tip">*</span>身份证号</label>
								<input v-model="formData.idCard" placeholder="请输入身份证号" class="form-input" :disabled="type === 'detail'"></input>
							</view>
							<view class="form-item">
							<label class="form-label"><span class="red-tip">*</span>入学时间</label>
							<input v-model="formData.inTime" placeholder="请输入入学时间" class="form-input" :disabled="type === 'detail'" ></input>
						</view>
						<!-- <view class="form-item">
							<label class="form-label"><span class="red-tip">*</span>证件照</label>
							<view class="example-body">
								<uni-file-picker 
									@select="handlePhotoUpload" 
									@delete="deletePhoto" 
									:auto-upload="false"
									limit="1"
									:disabled="type === 'detail'"
									mode="grid"
								></uni-file-picker>
							</view>
							<view class="upload-tip" v-if="type !== 'detail'">支持上传jpg/png格式照片，单个文件不超过5MB</view>
						</view> -->
						<view class="form-item">
							<label class="form-label">曾获资助/奖励</label>
							<textarea v-model="formData.helpHis" placeholder="请输入曾获资助或奖励情况" class="form-textarea" rows="3" :disabled="type === 'detail'" ></textarea>
						</view>
						</view>
				</view>

				<!-- 2. 家庭经济情况标签页 -->
				<view v-show="activeTab === 1" class="tab-panel">
					<view class="form-card">
						<view class="card-title">家庭经济情况</view>
						<view class="form-item">
							<label class="form-label"><span class="red-tip">*</span>家庭人口数</label>
							<input v-model="formData.familyNum" placeholder="请填写家庭人口数" class="form-input" type="number" :disabled="type === 'detail'"></input>
						</view>
						<view class="form-item">
							<label class="form-label"><span class="red-tip">*</span>家庭月总收入</label>
							<input v-model="formData.monthMoney" placeholder="请填写家庭月总收入" class="form-input" type="number" :disabled="type === 'detail'"></input>
						</view>
						<view class="form-item">
							<label class="form-label"><span class="red-tip">*</span>人均月收入</label>
							<input v-model="formData.perMoney" placeholder="请填写人均月收入" class="form-input" type="number" :disabled="type === 'detail'"></input>
						</view>
						<view class="form-item">
					<label class="form-label"><span class="red-tip">*</span>收入来源</label>
					<input v-model="formData.moneySrc" placeholder="请填写收入来源" class="form-input" :disabled="type === 'detail'"></input>
				</view>
				<view class="form-item">
					<label class="form-label"><span class="red-tip">*</span>困难类型</label>
					<view class="checkbox-container">
						<view class="checkbox-item" v-for="(option, index) in hardTypeOptions" :key="index" @click="type !== 'detail' && setHardType(option.value)">
							<view class="custom-checkbox" :class="{ 'checkbox-checked': formData.hardType === option.value }">{{ formData.hardType === option.value ? '✓' : '' }}</view>
							<text class="checkbox-text">{{ option.text }}</text>
						</view>
					</view>
				</view>
				<view class="form-item">
					<label class="form-label"><span class="red-tip">*</span>家庭住址</label>
					<input v-model="formData.homeAddr" placeholder="请填写家庭住址" class="form-input" :disabled="type === 'detail'"></input>
				</view>
				<view class="form-item">
					<label class="form-label"><span class="red-tip">*</span>邮政编码</label>
					<input v-model="formData.postCode" placeholder="请填写邮政编码" class="form-input" type="number" :disabled="type === 'detail'"></input>
				</view>
					</view>
				</view>

				<!-- 3. 学习情况标签页 -->
				<view v-show="activeTab === 2" class="tab-panel">
					<view class="form-card">
						<view class="card-title">学习情况</view>
						<view class="form-item">
							<label class="form-label"><span class="red-tip">*</span>专业排名</label>
							<input v-model="formData.majorRank" placeholder="请填写专业排名" class="form-input" type="number" :disabled="type === 'detail'"></input>
						</view>
						<view class="form-item">
							<label class="form-label"><span class="red-tip">*</span>专业人数</label>
							<input v-model="formData.majorNum" placeholder="请填写专业人数" class="form-input" type="number" :disabled="type === 'detail'"></input>
						</view>
						<view class="form-item">
							<label class="form-label"><span class="red-tip">*</span>实行综合考评排名</label>
							<view class="checkbox-container">
								<view class="checkbox-item" @click="type !== 'detail' && setIsCph('是')">
								<view class="custom-checkbox" :class="{ 'checkbox-checked': formData.isCph === '是' }">{{ formData.isCph === '是' ? '✓' : '' }}</view>
								<text class="checkbox-text">是</text>
							</view>
							<view class="checkbox-item" @click="type !== 'detail' && setIsCph('否')">
								<view class="custom-checkbox" :class="{ 'checkbox-checked': formData.isCph === '否' }">{{ formData.isCph === '否' ? '✓' : '' }}</view>
								<text class="checkbox-text">否</text>
							</view>
							</view>
						</view>
						<view class="form-item">
							<label class="form-label"><span class="red-tip">*</span>班级排名</label>
							<input v-model="formData.classRank" placeholder="请填写班级排名" class="form-input" type="number" :disabled="type === 'detail'"></input>
						</view>
						<view class="form-item">
							<label class="form-label"><span class="red-tip">*</span>班级人数</label>
							<input v-model="formData.classNum" placeholder="请填写班级人数" class="form-input" type="number" :disabled="type === 'detail'"></input>
						</view>
						<view class="form-item">
							<label class="form-label"><span class="red-tip">*</span>必修课门数</label>
							<input v-model="formData.bxk" placeholder="请填写必修课门数" class="form-input" type="number" :disabled="type === 'detail'"></input>
						</view>
						<view class="form-item">
							<label class="form-label"><span class="red-tip">*</span>及格门数</label>
							<input v-model="formData.jg" placeholder="请填写及格门数" class="form-input" type="number" :disabled="type === 'detail'"></input>
						</view>
					</view>
				</view>

				<!-- 4. 申请理由标签页 -->
				<view v-show="activeTab === 3" class="tab-panel">
					<view class="form-card">
						<view class="card-title">申请理由与承诺</view>
						<view class="form-item">
							<label class="form-label"><span class="red-tip">*</span>申请理由</label>
							<textarea placeholder="请输入申请理由" v-model="formData.applyReason" class="form-textarea" rows="4" :disabled="type === 'detail'"></textarea>
						</view>
						<view class="form-item">
							<label class="form-label"><span class="red-tip">*</span>证明材料</label>
							<view class="upload-btn" @click="handleUpload" :class="{ 'upload-disabled': type === 'detail' }">
								<text class="upload-icon">+</text>
								<text>{{ type === 'detail' ? '已上传佐证材料' : '上传文件' }}</text>
							</view>
							<view class="file-list" v-if="affixFiles.length">
								<view class="file-item" v-for="(file, index) in affixFiles" :key="index">
									<text class="file-name" @click="previewImage(file.serverUrl)">{{ file.attachmentName || file.trueName }}</text>
									<uni-icons type="trash-filled" size="30" @click="deleteFile(index)" v-if="type !== 'detail'" class="delete-btn"></uni-icons>
								</view>
							</view>
							<view class="upload-tip" v-if="type !== 'detail'">1、个人上学年成绩单；2、辅导员签字的综测排名截图</view>
									<view class="upload-tip" v-if="type !== 'detail'">请上传 大小不超过 10MB 格式为 doc/docx/xls/ppt/txt/pdf/xlsx 的文件</view>
						</view>
						<view class="form-item">
							<label class="form-label"><span class="red-tip">*</span>申请人签名</label>
							<view class="sign-img" v-if="signImg">
								<image :src="signImg" mode="aspectFit" style="width: 200px; height: 50px; cursor: pointer;" @click="previewImage(signImg)"></image>
								<text @tap="signToggle" class="re-sign-text">重新签名</text>
							</view>
							<view v-else class="sign" @tap="signToggle" :class="{ 'sign-disabled': type === 'detail' }">
								点击签名
							</view>
						</view>
					</view>
				</view>

				<!-- 5. 审核意见标签页 -->
				<view v-show="activeTab === 4" class="tab-panel">
					<view class="form-card">
						<view class="card-title">审核意见</view>
						
						<!-- 辅导员审核意见 -->
						<view class="approval-section">
							<view class="section-title">辅导员审核意见</view>
							<view class="approval-content">
								<text v-if="formData.fdyCmt" class="approval-text">{{ formData.fdyCmt }}</text>
								<text v-else class="no-content">暂无审核意见</text>
							</view>
							<view class="approval-info">
								<text v-if="formData.fdyName">审核人：{{ formData.fdyName }}</text>
								<text v-if="formData.fdyDate">审核时间：{{ formData.fdyDate }}</text>
							</view>
						</view>
						
						<!-- 院系审核意见 -->
						<view class="approval-section">
							<view class="section-title">院系审核意见</view>
							<view class="approval-content">
								<text v-if="formData.xwCmt" class="approval-text">{{ formData.xwCmt }}</text>
								<text v-else class="no-content">暂无审核意见</text>
							</view>
							<view class="approval-info">
								<text v-if="formData.xwName">审核人：{{ formData.xwName }}</text>
								<text v-if="formData.xwDate">审核时间：{{ formData.xwDate }}</text>
							</view>
						</view>
						
						<!-- 学工审核意见 -->
						<view class="approval-section">
							<view class="section-title">学工审核意见</view>
							<view class="approval-content">
								<text v-if="formData.xgCmt" class="approval-text">{{ formData.xgCmt }}</text>
								<text v-else class="no-content">暂无审核意见</text>
							</view>
							<view class="approval-info">
								<text v-if="formData.xgName">审核人：{{ formData.xgName }}</text>
								<text v-if="formData.xgDate">审核时间：{{ formData.xgDate }}</text>
							</view>
						</view>
						

					</view>
				</view>
			</view>
		</scroll-view>

		<!-- 提交按钮 -->
		<view class="submit-btn-container" v-if="type !== 'detail'">
			<view class="submit-btn" @click="submitForm">
				<text>提交申请</text>
			</view>
		</view>
		<!-- 签名组件 -->
		<jp-signature-popup ref="jpSignature" :required="true" popup @change="uploadSign" />
	</view>
</template>

<script>
	import { add, doEdit, getDetail, doReApply, doApply } from '@/api/finance/knzzGl';
	import { getOwnSign } from '@/api/workStudy/post';
	import { getOwnKnrd, getOwnExtraInfo, getOwnInfo as getOwnStuInfo } from '@/api/finance/special';
	import uploadFile from "@/plugins/upload.js"
	export default {
		data() {
			return {
				activeTab: 0,
				formScrollHeight: '600px',
				type: 'add',
				id: '',
				loading: false,
				listData: null,
				isReApply: false,
				genderOptions: [
				{ value: '男', text: '男' },
				{ value: '女', text: '女' }
			],
			hardTypeOptions: [
				{ value: '特别困难', text: '特别困难' },
				{ value: '比较困难', text: '比较困难' },
				{ value: '一般困难', text: '一般困难' }
			],
			formData: {
					stuNo: '',
					stuName: '',
					gender: '',
					mz: '',
					zzmm: '',
					className: '',
					stuPhone: '',
					idCard: '',
					inTime: '',
					helpHis: '',
					familyNum: '',
					monthMoney: '',
					perMoney: '',
					moneySrc: '',
					hardType: '',
					homeAddr: '',
					postCode: '',
					majorRank: '',
					majorNum: '',
					isCph: '否',
					classRank: '',
					classNum: '',
					bxk: '',
					jg: '',
					applyReason: '',
						hardFile: '',
						applySign: '',
						pic: '',
						majorName: '',
						deptName: '',
					fdyCmt: '',
					fdySign: '',
					fdyDate: '',
					fdyName: '',
					xwCmt: '',
					xwSign: '',
					xwDate: '',
					xwName: '',
					xgCmt: '',
						xgSign: '',
						xgDate: '',
						xgName: ''
				},
				affixFiles: [],
				signImg: '',
				baseUrl: uni.getStorageSync('baseUrl')
			};
		},
		onLoad(option) {
			// 接收从主页面传递过来的申请ID和类型
			if (option && option.id) {
				this.id = option.id;
				if (option.type === 'detail') {
					this.type = 'detail';
				}
				// 接收是否是重新提交的参数
				if (option.isReApply === 'true') {
					this.isReApply = true;
				}
				// 从本地存储获取从列表页面传递的数据
				const storedItem = uni.getStorageSync('glApplyItem');
				if (storedItem) {
					this.listData = storedItem;
					// 清除本地存储，避免数据残留
					uni.removeStorageSync('glApplyItem');
				}
			}
			this.calculateFormHeight();
			this.initData();
		},
		onShow() {
			this.calculateFormHeight();
		},
		methods: {
			// 计算表单滚动区域高度
			calculateFormHeight() {
				const systemInfo = uni.getSystemInfoSync();
				const navHeight = 44; // 导航栏高度
				const tabsHeight = 50; // 选项卡高度
				const submitBtnHeight = 60; // 提交按钮高度
				const padding = 20; // 页面内边距
				this.formScrollHeight = (systemInfo.windowHeight - navHeight - tabsHeight - submitBtnHeight - padding) + 'px';
			},
			// 初始化数据
			async initData() {
				this.loading = true;
				try {
					// 并行请求所有基础信息
					const [signRes, knrdRes, stuInfoRes, extraInfoRes] = await Promise.all([
						getOwnSign(),
						getOwnKnrd(),
						getOwnStuInfo(),
						getOwnExtraInfo()
					]);
					
					// 处理签名信息
					if (signRes && signRes.data) {
						this.formData.applySign = signRes.data;
						this.signImg = this.baseUrl + signRes.data;
					}
					
					// 处理困难认定信息
					if (knrdRes && knrdRes.data) {
						const knrdData = knrdRes.data;
						console.log('困难认定信息:', knrdData);
						// 处理家庭人口总数、家庭月总收入、人均月收入
						if (knrdData.rkzs) {
							this.formData.familyNum = knrdData.rkzs;
						}
						if (knrdData.jtnsr) {
							// 计算家庭月总收入：年收入除以12，保留两位小数
							const jtysr = parseFloat((knrdData.jtnsr / 12).toFixed(2));
							this.formData.monthMoney = jtysr;
							// 计算人均月收入：家庭月总收入除以家庭人口总数，保留两位小数
							if (knrdData.rkzs) {
								const rjysr = parseFloat((jtysr / Number(knrdData.rkzs)).toFixed(2));
								this.formData.perMoney = rjysr;
							}
						}
						// 处理困难类型
						if (knrdData.xsqmyj) {
							console.log('xsqmyj:', knrdData.xsqmyj);
							switch (knrdData.xsqmyj) {
								case '1':
									this.formData.hardType = '特别困难';
									break;
								case '2':
									this.formData.hardType = '比较困难';
									break;
								case '3':
									this.formData.hardType = '一般困难';
									break;
							}
						}
					}
					
					// 处理学生基本信息
					if (stuInfoRes && stuInfoRes.data) {
						const stuInfo = stuInfoRes.data;
						console.log('学生基本信息:', stuInfo);
						this.formData.stuNo = stuInfo.stuNo || this.formData.stuNo;
						this.formData.stuName = stuInfo.name || this.formData.stuName;
						this.formData.gender = stuInfo.gender || this.formData.gender;
						// 从cphStuExtraInfo获取民族和政治面貌
						if (stuInfo.cphStuExtraInfo) {
							console.log('cphStuExtraInfo:', stuInfo.cphStuExtraInfo);
							this.formData.mz = stuInfo.cphStuExtraInfo.mz || this.formData.mz;
							this.formData.zzmm = stuInfo.cphStuExtraInfo.zzmm || this.formData.zzmm;
						} else {
							console.log('cphStuExtraInfo不存在');
						}
						// 处理班级信息
						if (stuInfo.srsClass && stuInfo.srsClass.className) {
							this.formData.className = stuInfo.srsClass.className;
						}
						this.formData.stuPhone = stuInfo.phone || this.formData.stuPhone;
						this.formData.idCard = stuInfo.idCard || this.formData.idCard;
						// 处理专业信息
						if (stuInfo.srsMajors && stuInfo.srsMajors.majorName) {
							this.formData.majorName = stuInfo.srsMajors.majorName;
						}
						// 处理学院信息
						if (stuInfo.dept && stuInfo.dept.deptName) {
							this.formData.deptName = stuInfo.dept.deptName;
						}
					}
					
					// 处理额外信息
						if (extraInfoRes && extraInfoRes.data) {
							const extraInfo = extraInfoRes.data;
							console.log('额外信息:', extraInfo);
							this.formData.familyNum = extraInfo.familyNum || this.formData.familyNum;
							this.formData.monthMoney = extraInfo.monthMoney || this.formData.monthMoney;
							this.formData.perMoney = extraInfo.perMoney || this.formData.perMoney;
							this.formData.moneySrc = extraInfo.moneySrc || this.formData.moneySrc;
							// 处理困难类型
							if (extraInfo.hardType) {
								this.formData.hardType = extraInfo.hardType;
							} else if (extraInfo.xsqmyj) {
								// 处理xsqmyj字段，映射到困难类型
								switch (extraInfo.xsqmyj) {
									case '1':
										this.formData.hardType = '特别困难';
										break;
									case '2':
										this.formData.hardType = '比较困难';
										break;
									case '3':
										this.formData.hardType = '一般困难';
										break;
									}
							}
							// 尝试从额外信息中获取民族和政治面貌
							if (extraInfo.mz) {
								this.formData.mz = extraInfo.mz;
							}
							if (extraInfo.zzmm) {
								this.formData.zzmm = extraInfo.zzmm;
							}
							// 处理家庭住址和邮政编码
							if (extraInfo.xjtdz) {
								this.formData.homeAddr = extraInfo.xjtdz;
							} else if (extraInfo.hkszd) {
								this.formData.homeAddr = extraInfo.hkszd;
							} else if (extraInfo.hksz1 && extraInfo.hksz2 && extraInfo.hksz3) {
								this.formData.homeAddr = extraInfo.hksz1 + extraInfo.hksz2 + extraInfo.hksz3;
							}
							if (extraInfo.jtyzbm) {
								this.formData.postCode = extraInfo.jtyzbm;
							} else if (extraInfo.yzbm) {
								this.formData.postCode = extraInfo.yzbm;
							}
							// 处理证件照
							if (extraInfo.whitePhoto) {
								this.formData.pic = extraInfo.whitePhoto;
								console.log('设置证件照:', this.formData.pic);
							}
						}
					
					// 如果有申请ID，获取申请详情
					if (this.id) {
						// 如果有从列表页面传递的数据，直接使用该数据进行回显
						if (this.listData) {
							this.formData = { ...this.formData, ...this.listData };
							// 处理签名图片
							if (this.listData.applySign) {
								this.signImg = this.baseUrl + this.listData.applySign;
							}
							// 处理困难佐证材料
							if (this.listData.hardFile) {
								// 处理多个文件路径的情况
								const filePaths = this.listData.hardFile.split(',');
								this.affixFiles = filePaths.map(filePath => {
									// 从文件路径中提取文件名
									const fileName = filePath.split('/').pop();
									// 构造文件信息对象
									return {
										attachmentName: fileName,
										attachmentUrl: filePath,
										serverUrl: filePath,
										fileId: '',
										fileSize: 0,
										fileSuffix: fileName.split('.').pop().toLowerCase(),
										savePath: filePath
									};
								});
							}
						} else {
							// 从接口获取数据
							this.getDetail();
						}
					}
				} catch (error) {
					console.error('初始化数据失败:', error);
				} finally {
					this.loading = false;
				}
			},
			
			// 切换选项卡
			switchTab(index) {
				this.activeTab = index;
			},
			
			// 处理性别选择
			handleGenderChange(e) {
				const index = e.detail.value;
				this.formData.gender = this.genderOptions[index].value;
			},
			// 设置困难类型
			setHardType(value) {
				this.formData.hardType = value;
				console.log('设置困难类型:', value);
			},
			
			// 设置是否综合考评
			setIsCph(value) {
				this.formData.isCph = value;
			},
			
			// 获取详细信息
			getDetail() {
				getDetail(this.id).then(response => {
					const res = response || {};
					const data = res.data || {};
					// 处理困难类型
					let hardType = data.hardType;
					if (!hardType && data.xsqmyj) {
						switch (data.xsqmyj) {
							case '1':
								hardType = '特别困难';
								break;
							case '2':
								hardType = '比较困难';
								break;
							case '3':
								hardType = '一般困难';
								break;
						}
					}
					// 构建formData对象
					this.formData = {
						...data,
						hardType: hardType
					};
					// 处理签名图片
					if (this.formData.applySign) {
						this.signImg = this.baseUrl + this.formData.applySign;
					} else {
						this.signImg = '';
					}
					// 处理困难佐证材料
					if (this.formData.hardFile) {
						// 处理多个文件路径的情况
						const filePaths = this.formData.hardFile.split(',');
						this.affixFiles = filePaths.map(filePath => {
							// 从文件路径中提取文件名
							const fileName = filePath.split('/').pop();
							// 构造文件信息对象
							return {
								attachmentName: fileName,
								attachmentUrl: filePath,
								serverUrl: filePath,
								fileId: '',
								fileSize: 0,
								fileSuffix: fileName.split('.').pop().toLowerCase(),
								savePath: filePath
							};
						});
					}
				}).catch(error => {
					console.error('获取详情失败:', error);
					uni.showToast({
						title: '获取详情失败',
						icon: 'none'
					});
				});
			},

			// 提交表单
			submitForm() {
				// 表单验证
				if (!this.formData.inTime) {
					uni.showToast({ title: '请填写入学时间', icon: 'none' });
					return;
				}
				if (!this.formData.helpHis) {
					uni.showToast({ title: '请填写曾获奖励,没有写无', icon: 'none' });
					return;
				}
				if (!this.formData.familyNum) {
					uni.showToast({ title: '请填写家庭人口数', icon: 'none' });
					return;
				}
				if (!this.formData.monthMoney) {
					uni.showToast({ title: '请填写家庭月总收入', icon: 'none' });
					return;
				}
				if (!this.formData.perMoney) {
					uni.showToast({ title: '请填写人均月收入', icon: 'none' });
					return;
				}
				if (!this.formData.moneySrc) {
				uni.showToast({ title: '请填写收入来源', icon: 'none' });
				return;
			}
			if (!this.formData.hardType) {
				uni.showToast({ title: '请选择困难类型', icon: 'none' });
				return;
			}
			if (!this.formData.homeAddr) {
				uni.showToast({ title: '请填写家庭住址', icon: 'none' });
				return;
			}
			if (!this.formData.postCode) {
				uni.showToast({ title: '请填写邮政编码', icon: 'none' });
				return;
			}
				if (!this.formData.majorRank) {
					uni.showToast({ title: '请填写专业排名', icon: 'none' });
					return;
				}
				if (!this.formData.majorNum) {
					uni.showToast({ title: '请填写专业人数', icon: 'none' });
					return;
				}
				if (!this.formData.bxk) {
					uni.showToast({ title: '请填写必修课门数', icon: 'none' });
					return;
				}
				if (!this.formData.jg) {
					uni.showToast({ title: '请填写及格门数', icon: 'none' });
					return;
				}
				if (!this.formData.applyReason) {
					uni.showToast({ title: '请填写申请理由', icon: 'none' });
					return;
				}
				if (!this.formData.hardFile) {
					uni.showToast({ title: '请上传证明材料', icon: 'none' });
					return;
				}
				if (!this.formData.applySign) {
					uni.showToast({ title: '请上传申请人签名', icon: 'none' });
					return;
				}

				const submitData = { ...this.formData };
				if (this.id) {
					if (this.isReApply) {
						// 重新提交
						doReApply(submitData).then(response => {
							const res = response || {};
							if (res.code === 200 || res.code === 0) {
								uni.showToast({
									title: '重新提交成功',
									icon: 'success'
								});
								uni.navigateBack();
							} else {
								uni.showToast({
									title: res.msg || '重新提交失败',
									icon: 'none'
								});
							}
						}).catch(error => {
							console.error('重新提交失败:', error);
							uni.showToast({
								title: '重新提交失败',
								icon: 'none'
							});
						});
					} else {
						// 修改
						doEdit(submitData).then(response => {
							const res = response || {};
							if (res.code === 200 || res.code === 0) {
								uni.showToast({
									title: '修改成功',
									icon: 'success'
								});
								uni.navigateBack();
							} else {
								uni.showToast({
									title: res.msg || '修改失败',
									icon: 'none'
								});
							}
						}).catch(error => {
							console.error('修改失败:', error);
							uni.showToast({
								title: '修改失败',
								icon: 'none'
							});
						});
					}
				} else {
					// 提交申请
					doApply(submitData).then(response => {
						const res = response || {};
						if (res.code === 200 || res.code === 0) {
							uni.showToast({
								title: '提交成功',
								icon: 'success'
							});
							uni.navigateBack();
						} else {
							uni.showToast({
								title: res.msg || '提交失败',
								icon: 'none'
							});
						}
					}).catch(error => {
						console.error('提交失败:', error);
						uni.showToast({
							title: '提交失败',
							icon: 'none'
						});
					});
				}
			},

			// 处理文件上传
				handleUpload() {
					// 如果是详情模式，不执行上传操作
					if (this.type === 'detail') {
						return;
					}

					// 定义affixId生成工具函数
					const generateUUID = () => {
						return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
							const r = Math.random() * 16 | 0;
							const v = c === 'x' ? r : (r & 0x3 | 0x8);
							return v.toString(16);
						});
					};

					uni.chooseFile({
				count: 5,
				extension: ['doc', 'docx', 'xls', 'ppt', 'txt', 'pdf', 'xlsx'],
						success: async (chooseRes) => {
							// 初始化affixId（如果为空则生成唯一ID）
							if (!this.formData.affixId) {
								this.formData.affixId = generateUUID();
							}

							// 遍历选择的文件，逐个上传
							for (const file of chooseRes.tempFiles) {
								try {
									// 构造上传参数
									const formDataObj = {
										affixId: this.formData.affixId,
										fileName: file.name,
										fileSize: file.size
									};

									// 上传文件
									console.log('准备上传文件:', file.path);
									console.log('上传参数:', formDataObj);
									const uploadRes = await uploadFile('/affix/upload', file.path, formDataObj);
									console.log('上传结果:', uploadRes);
									const result = typeof uploadRes === 'string' ? JSON.parse(uploadRes) : uploadRes;
									console.log('解析结果:', result);

									// 上传结果校验
									if (result && result.code === 200) {
										// 构造文件信息对象
										const fileInfo = {
											attachmentName: file.name,
											trueName: file.name,
											attachmentUrl: result.savePath,
											serverUrl: result.savePath || '',
											fileId: result.id || '',
											fileSize: file.size,
											fileSuffix: file.name.split('.').pop().toLowerCase(),
											savePath: result.savePath
										};

										// 去重逻辑
										const isDuplicate = this.affixFiles.some(item =>
											item.attachmentName === file.name && item.fileSize === file.size
										);

										if (!isDuplicate) {
										this.affixFiles.push(fileInfo);
										// 更新hardFile字段为所有文件路径的逗号分隔字符串
										this.formData.hardFile = this.affixFiles.map(item => item.savePath).join(',');
									}

										uni.showToast({
											title: `文件 ${file.name} 上传成功`,
											icon: 'success',
											duration: 1500
										});
									} else {
										// 上传失败处理
										uni.showToast({
											title: `文件 ${file.name} 上传失败：${result.message || '未知错误'}`,
											icon: 'none',
											duration: 2000
										});
									}
								} catch (error) {
									// 异常捕获
									console.error(`文件 ${file.name} 上传异常：`, error);
									uni.showToast({
										title: `文件 ${file.name} 上传异常，请重试`,
										icon: 'none',
										duration: 2000
									});
								}
							}
						},
						// 取消选择文件的处理
						fail: (err) => {
							console.error('选择文件失败：', err);
							uni.showToast({
								title: '选择文件失败，请重试',
								icon: 'none'
							});
						}
					});
				},

			// 删除文件
			deleteFile(index) {
				this.affixFiles.splice(index, 1);
				// 更新hardFile字段为剩余文件路径的逗号分隔字符串
				this.formData.hardFile = this.affixFiles.map(item => item.savePath).join(',');
			},

			// 预览图片
				previewImage(url) {
					// 检查文件类型是否为图片
					const fileSuffix = url.split('.').pop().toLowerCase();
					const imageSuffixes = ['jpg', 'jpeg', 'png', 'gif', 'bmp'];
					if (imageSuffixes.includes(fileSuffix)) {
						uni.previewImage({
							urls: [url]
						});
					} else {
						// 非图片文件，使用其他方式处理
						uni.showToast({
							title: '该文件类型不支持预览',
							icon: 'none'
						});
					}
				},

			// 签名相关
			signToggle() {
				this.$refs.jpSignature.toPop();
			},

			// 上传签名
			uploadSign(data) {
				if (data) {
					// 上传签名图片到后端
					uploadFile('/common/upload', data).then((res) => {
						const result = typeof res === 'string' ? JSON.parse(res) : res;
						if (result && result.code === 200) {
							this.formData.applySign = result.fileName || result.savePath;
							this.signImg = result.url || (this.baseUrl + (result.fileName || result.savePath));
						} else {
							uni.showToast({
								title: '签名上传失败，请重试',
								icon: 'none'
							});
						}
					}).catch((error) => {
						console.error('签名上传异常：', error);
						uni.showToast({
							title: '签名上传异常，请重试',
							icon: 'none'
						});
					});
				}
			},
			
			// 处理证件照上传
			handlePhotoUpload(e) {
				const file = e.tempFile;
				
				// 检查文件大小
				if (file.size > 5 * 1024 * 1024) {
					uni.showToast({
						title: '文件大小不能超过5MB',
						icon: 'none'
					});
					return;
				}
				
				// 检查文件类型
				const fileExt = file.name.split('.').pop().toLowerCase();
				if (!['jpg', 'jpeg', 'png'].includes(fileExt)) {
					uni.showToast({
						title: '只支持jpg/jpeg/png格式的图片',
						icon: 'none'
					});
					return;
				}
				
				uni.showLoading({ title: '上传中...' });
				
				uploadFile('/common/upload', file.path).then((res) => {
					uni.hideLoading();
					const result = typeof res === 'string' ? JSON.parse(res) : res;
					if (result && result.code === 200) {
						this.formData.pic = result.fileName || result.savePath;
						uni.showToast({
							title: '证件照上传成功',
							icon: 'success'
						});
					} else {
						uni.showToast({
							title: '证件照上传失败，请重试',
							icon: 'none'
						});
					}
				}).catch((error) => {
					uni.hideLoading();
					console.error('证件照上传异常：', error);
					uni.showToast({
						title: '证件照上传异常，请重试',
						icon: 'none'
					});
				});
			},
			
			// 删除证件照
			deletePhoto() {
				this.formData.pic = '';
				uni.showToast({
					title: '证件照已删除',
					icon: 'success'
				});
			}
		}
	};
</script>

<style scoped>
	.knzz-gl-apply {
		background-color: #F3F4F6;
		min-height: 100vh;
	}

	.tabs-container {
		background-color: white;
		position: sticky;
		top: 0;
		z-index: 10;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
	}

	.tabs-header {
		display: flex;
		justify-content: space-around;
		align-items: center;
		height: 50px;
	}

	.tab-item {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 0 10rpx;
		position: relative;
	}

	.tab-item.active {
		color: #409EFF;
	}

	.tab-item.active::after {
					content: '';
					position: absolute;
					bottom: -12rpx;
					left: 20%;
					width: 60%;
					height: 3rpx;
					background-color: #409EFF;
					border-radius: 3rpx;
				}

	.tab-text {
		margin-top: 4rpx;
		font-size: 24rpx;
	}

	.form-scroll {
		width: 100%;
	}

	.form-wrapper {
		padding: 20rpx;
	}

	.tab-panel {
		width: 100%;
	}

	.form-card {
		background-color: white;
		border-radius: 10rpx;
		padding: 20rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
		margin-bottom: 20rpx;
	}

	.card-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 20rpx;
		display: block;
	}

	.form-item {
		margin-bottom: 20rpx;
	}

	.form-label {
		display: block;
		font-size: 28rpx;
		color: #606266;
		margin-bottom: 10rpx;
	}

	.red-tip {
		color: #f56c6c;
		font-size: 28rpx;
		margin-right: 5rpx;
	}

	.form-input {
		width: 100%;
		height: 80rpx;
		border: 1rpx solid #dcdfe6;
		border-radius: 10rpx;
		padding: 0 20rpx;
		font-size: 28rpx;
		color: #303133;
		background-color: #fafafa;
	}

	.form-textarea {
		width: 100%;
		min-height: 160rpx;
		border: 1rpx solid #dcdfe6;
		border-radius: 10rpx;
		padding: 20rpx;
		font-size: 28rpx;
		color: #303133;
		background-color: #fafafa;
		resize: none;
	}

	.picker-input {
		width: 100%;
		height: 80rpx;
		border: 1rpx solid #dcdfe6;
		border-radius: 10rpx;
		padding: 0 20rpx;
		font-size: 28rpx;
		color: #303133;
		background-color: #fafafa;
		display: flex;
		align-items: center;
	}

	.checkbox-container {
		display: flex;
		gap: 40rpx;
	}

	.checkbox-item {
		display: flex;
		align-items: center;
		gap: 10rpx;
	}

	.custom-checkbox {
		width: 32rpx;
		height: 32rpx;
		border: 2rpx solid #dcdfe6;
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 24rpx;
		color: white;
	}

	.checkbox-checked {
		background-color: #409EFF;
		border-color: #409EFF;
	}

	.checkbox-text {
		font-size: 28rpx;
		color: #303133;
	}

	.upload-btn {
		width: 100%;
		height: 120rpx;
		border: 2rpx dashed #dcdfe6;
		border-radius: 10rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		background-color: #fafafa;
		cursor: pointer;
	}

	.upload-icon {
		font-size: 48rpx;
		color: #409EFF;
		margin-bottom: 10rpx;
	}

	.upload-disabled {
		opacity: 0.6;
		cursor: not-allowed;
	}

	.file-list {
		margin-top: 20rpx;
	}

	.file-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 10rpx 0;
		border-bottom: 1rpx solid #f0f0f0;
	}

	.file-name {
		font-size: 26rpx;
		color: #409EFF;
		flex: 1;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}

	.delete-btn {
		color: #f56c6c;
	}

	.upload-tip {
			font-size: 24rpx;
			color: #909399;
			margin-top: 10rpx;
		}
		
		.example-body {
			margin-top: 10rpx;
		}

	.sign {
		width: 200px;
		height: 50px;
		border: 1rpx solid #dcdfe6;
		border-radius: 10rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		background-color: #fafafa;
		cursor: pointer;
		font-size: 24rpx;
		color: #606266;
	}

	.sign-disabled {
		opacity: 0.6;
		cursor: not-allowed;
	}

	.sign-img {
		display: flex;
		flex-direction: column;
		align-items: flex-start;
	}

	.re-sign-text {
		margin-top: 10rpx;
		font-size: 24rpx;
		color: #409EFF;
		cursor: pointer;
	}

	.approval-section {
				margin-bottom: 30rpx;

				.section-title {
					font-size: 26rpx;
					font-weight: bold;
					color: #333;
					margin-bottom: 15rpx;
				}

				.approval-content {
					padding: 20rpx;
					background-color: #F9F9F9;
					border-radius: 10rpx;
					margin-bottom: 10rpx;
					transition: all 0.3s ease;

					&:hover {
						background-color: #F0F0F0;
					}

					.approval-text {
						font-size: 24rpx;
						color: #666;
						line-height: 1.5;
						white-space: pre-wrap;
					}

					.no-content {
						font-size: 24rpx;
						color: #999;
					}
				}

				.approval-info {
					display: flex;
					justify-content: space-between;
					font-size: 22rpx;
					color: #999;
					padding: 0 20rpx;
				}
			}

	/* 提交按钮容器 */
	.submit-btn-container {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		display: flex;
		padding: 10px;
		background-color: #fff;
		border-top: 1px solid #e4e7ed;
		z-index: 100;
	}

	/* 提交按钮 */
	.submit-btn {
		width: 100%;
		height: 40px;
		border-radius: 20px;
		font-size: 14px;
		border: none;
		background-color: #409EFF;
		color: #fff;
		display: flex;
		align-items: center;
		justify-content: center;
		gap: 5px;
	}
	.submit-primary {
		background-color: #67c23a;
	}
</style>