<template>
  <view class="personal-info-page">
    <!-- 顶部导航栏 -->
    <custom-navbar :title="navTitle" :showBack="true"></custom-navbar>
    
    <!-- 变更提示 -->
    <view class="change-tip" v-if="editable">
      <text>请变更您需要变更的信息</text>
    </view>
    
    <!-- 页面内容容器 -->
    <view class="content-area" :style="{ paddingBottom: buttonAreaHeight + 'px' }">
      <!-- 个人资料部分 -->
      <view class="section">
        <view class="section-title">
          <view class="title-bar"></view>
          <text class="title-text">个人资料</text>
        </view>
        
        <!-- 头像上传 -->
        <view class="form-item box-cont">
          <view class="label-wrapper">
            <text class="label required">工装头像</text>
            <image class="label-icon" src="https://mrrplus.oss-cn-beijing.aliyuncs.com/photo/system/25bd7f38-1a3e-4282-84ea-190d7f820108" mode="aspectFit" @click="showTipPopup('head_photo')"></image>
          </view>
          <view class="upload-box" @click="chooseImage('head_photo')">
            <view class="upload-camera head_photo-upload">
              <image v-if="displayData.head_photo" :src="displayData.head_photo" mode="aspectFill" class="preview-image"></image>
              <image v-else src="/static/images/upload-img.png" mode="aspectFit" class="camera-icon"></image>
            </view>
          </view>
          <view class="upload-tip">注:头像即为服务人实形象照，是用户下单选择服务人员时的重要参考，请上传正面半身免冠照。尺寸需大于750*750像素，背景为浅色</view>
        </view>

        <!-- 身份证照片部分 -->
        <view class="section">
          <view class="box-cont">
            <view class="form-item">
              <text class="label required">身份证照片</text>
              <view class="upload-tip-sfz">请保证照片上的文字清晰、无遮挡、证件边角可见</view>
              
              <view class="idcard-upload-vertical-container">
                <!-- 身份证正面 -->
                <view class="idcard-upload-vertical-item">
                  <view class="upload-box" @click="chooseImage('idcard_positive')">
                    <view class="upload-camera idcard-front">
                      <image v-if="displayData.idcard_positive" :src="displayData.idcard_positive" mode="aspectFill" class="preview-image"></image>
                      <image v-else src="https://mrrplus.oss-cn-beijing.aliyuncs.com/photo/system/043b0c97-79c1-4f95-810f-c33e3d5269a3" mode="aspectFit" class="camera-icon"></image>
                    </view>
                  </view>
                  <text class="upload-label required">请上传身份证正面（人像面）</text>
                </view>
                
                <!-- 身份证反面 -->
                <view class="idcard-upload-vertical-item">
                  <view class="upload-box" @click="chooseImage('idcard_negative')">
                    <view class="upload-camera idcard-back">
                      <image v-if="displayData.idcard_negative" :src="displayData.idcard_negative" mode="aspectFill" class="preview-image"></image>
                      <image v-else src="https://mrrplus.oss-cn-beijing.aliyuncs.com/photo/system/203cfdf4-2501-44e6-8565-ad251c6bf0fa" mode="aspectFit" class="camera-icon"></image>
                    </view>
                  </view>
                  <text class="upload-label required">请上传身份证反面（国徽面）</text>
                </view>
              </view>
            </view>
          </view>
        </view>

        <!-- 真实姓名 -->
        <view class="form-item-one box-cont">
          <text class="label required">真实姓名</text>
          <input type="text" v-model="displayData.name" placeholder="请输入真实姓名" 
                 :disabled="!editable" placeholder-class="placeholder" class="input" />
        </view>

        <!-- 联系方式 -->
        <view class="form-item-one box-cont">
          <text class="label required">联系方式</text>
          <input type="number" v-model="displayData.account" placeholder="请输入联系方式" 
                 :disabled="!editable" placeholder-class="placeholder" class="input" />
        </view>

        <!-- 备用联系方式 -->
        <view class="form-item-one box-cont">
          <text class="label required">备用联系方式</text>
          <input type="number" v-model="displayData.second_phone" placeholder="请输入备用联系方式" 
                 :disabled="!editable" placeholder-class="placeholder" class="input" />
        </view>

        <!-- 身份证号 -->
        <view class="form-item-one box-cont">
          <text class="label required">身份证号</text>
          <input type="idcard" v-model="displayData.idcard_num" placeholder="请输入证件号码" 
                 :disabled="!editable" placeholder-class="placeholder" class="input" />
        </view>

        <!-- 身份证有效期 -->
        <view class="form-item box-cont">
          <text class="label required">身份证有效期至：</text>
          <view class="radio-group">
            <view class="radio-item" @click="editable && setIdCardValidType(1)">
              <view class="radio" :class="{ checked: displayData.idcard_expiry_type === 1 }">
                <image v-if="displayData.idcard_expiry_type === 1" src="https://mrrplus.oss-cn-beijing.aliyuncs.com/photo/system/cb185ec8-9d30-4e53-b5dc-14b546013a60" class="radio-icon-image" mode="aspectFit"></image>
              </view>
              <text class="radio-label">长久有效</text>
            </view>
            <view class="radio-item" @click="editable && setIdCardValidType(2)">
              <view class="radio" :class="{ checked: displayData.idcard_expiry_type === 2 }">
                <image v-if="displayData.idcard_expiry_type === 2" src="https://mrrplus.oss-cn-beijing.aliyuncs.com/photo/system/cb185ec8-9d30-4e53-b5dc-14b546013a60" class="radio-icon-image" mode="aspectFit"></image>
              </view>
              <text class="radio-label">指定日期有效</text>
            </view>
          </view>
        </view>

        <!-- 身份证有效期日期选择 -->
        <view class="box-cont">
          <view class="date-range-container">
            <view class="date-item">
              <text class="date-label">开始日期</text>
              <view class="date-picker-box" @click="editable && openDatePicker('idcard_start_date')">
                <text :class="displayData.idcard_start_date ? 'date-value' : 'placeholder'">
                  {{formatDateForDisplay(displayData.idcard_start_date) || '选择日期'}}
                </text>
                <view class="date-divider"></view>
                <image src="https://mrrplus.oss-cn-beijing.aliyuncs.com/photo/system/ce52b49f-2261-49ca-96ed-e9ad47049649" class="date-arrow" mode="aspectFit"></image>
              </view>
            </view>
            <view class="date-item">
              <text class="date-label">结束日期</text>
              <view class="date-picker-box" :class="{ disabled: displayData.idcard_expiry_type === 1 }" 
                    @click="editable && displayData.idcard_expiry_type !== 1 && openDatePicker('idcard_end_date')">
                <text :class="displayData.idcard_end_date ? 'date-value' : 'placeholder'">
                  {{formatDateForDisplay(displayData.idcard_end_date) || '选择日期'}}
                </text>
                <view class="date-divider"></view>
                <image :src="editable && displayData.idcard_expiry_type !== 1 ? 
                  'https://mrrplus.oss-cn-beijing.aliyuncs.com/photo/system/ce52b49f-2261-49ca-96ed-e9ad47049649' : 
                  'https://mrrplus.oss-cn-beijing.aliyuncs.com/photo/system/bb9a757f-a36c-46bb-a59f-2caddac5365b'" 
                  class="date-arrow" mode="aspectFit"></image>
              </view>
            </view>
          </view>
        </view>
      </view>

      <!-- 个人简介 -->
      <view class="section">
        <view class="box-cont">
          <view class="form-item">
            <text class="label required">个人介绍：</text>
            <textarea v-model="displayData.detail" placeholder="请输入个人简介、工作的经验等介绍" 
                  class="textarea" maxlength="500" :disabled="!editable" />
          </view>
        </view>
      </view>

      <!-- 所在地 -->
      <view class="section">  
        <view class="form-item-two box-cont" @click="editable ? showLocationPopup() : null">
          <text class="label required">所在地</text>
          <view class="picker-content">
            <text :class="displayData.dependency ? 'picker-value' : 'placeholder'">
              {{displayData.dependency || '请选择'}}
            </text>
            <image v-if="editable" src="https://mrrplus.oss-cn-beijing.aliyuncs.com/photo/system/dccc4513-377c-4bfa-9fd2-a5cfdb9798f3" class="arrow-right" mode="aspectFit"></image>
          </view>
        </view>

        <!-- 修改详细地址为选择方式 -->
          <view class="form-item-two box-cont" @click="editable ? getAddressInfo() : null">
            <text class="label required">详细地址</text>
            <view class="picker-content">
              <text :class="displayData.address ? 'picker-value' : 'placeholder'">
                {{displayData.address || '请选择'}}
              </text>
              <image v-if="editable" src="https://mrrplus.oss-cn-beijing.aliyuncs.com/photo/system/dccc4513-377c-4bfa-9fd2-a5cfdb9798f3" class="arrow-right" mode="aspectFit"></image>
            </view>
          </view>
      </view>

      <!-- 其他信息 -->
      <view class="section">
        <view class="section-title">
          <view class="title-bar"></view>
          <text class="title-text">其他信息</text>
        </view>

        <!-- 专业经验 -->
        <view class="form-item-two box-cont" @click="editable ? openExperiencePicker() : null">
          <text class="label required">专业经验</text>
          <view class="picker-content">
            <text :class="displayData.major ? 'picker-value' : 'placeholder'">
              {{getExperienceText(displayData.major) || '请选择'}}
            </text>
            <image v-if="editable" src="https://mrrplus.oss-cn-beijing.aliyuncs.com/photo/system/dccc4513-377c-4bfa-9fd2-a5cfdb9798f3" class="arrow-right" mode="aspectFit"></image>
          </view>
        </view>

        <!-- 目前工作状态 -->
        <view class="form-item-two box-cont" @click="editable ? openWorkStatusPicker() : null">
          <text class="label required">目前工作状态</text>
          <view class="picker-content">
            <text :class="displayData.work_state ? 'picker-value' : 'placeholder'">
              {{getWorkStatusText(displayData.work_state) || '请选择'}}
            </text>
            <image v-if="editable" src="https://mrrplus.oss-cn-beijing.aliyuncs.com/photo/system/dccc4513-377c-4bfa-9fd2-a5cfdb9798f3" class="arrow-right" mode="aspectFit"></image>
          </view>
        </view>
      </view>



      <!-- 日期选择器 -->
      <view class="popup" :class="{ show: showDatePickerFlag }">
        <view class="popup-mask" @click="hideDatePicker"></view>
        <view class="popup-content">
          <view class="popup-header">
            <text class="cancel-text" @click="hideDatePicker">取消</text>
            <text class="title">选择日期</text>
            <text class="confirm-text" @click="confirmDate">确定</text>
          </view>
          <view class="region-body">
            <picker-view :value="dateValue" @change="bindDateChange" class="picker-scroll" 
                        :indicator-style="indicatorStyle" mode="date" fields="day">
              <picker-view-column>
                <view class="picker-item" v-for="(year, index) in years" :key="index">{{year}}年</view>
              </picker-view-column>
              <picker-view-column>
                <view class="picker-item" v-for="(month, index) in months" :key="index">{{month}}月</view>
              </picker-view-column>
              <picker-view-column>
                <view class="picker-item" v-for="(day, index) in days" :key="index">{{day}}日</view>
              </picker-view-column>
            </picker-view>
          </view>
        </view>
      </view>

      <!-- 所在地选择弹出框 -->
      <view class="popup" :class="{ show: showLocationPopupFlag }">
        <view class="popup-mask" @click="hideLocationPopup"></view>
        <view class="popup-content">
          <view class="popup-header">
            <text class="popup-title">选择所在地</text>
            <text class="popup-close" @click="hideLocationPopup">×</text>
          </view>
          <view class="region-body">
            <picker-view @change="bindChangeLocation" class="picker-scroll"
                        :indicator-style="indicatorStyle" :value="locationValue">
              <picker-view-column>
                <view class="picker-item" v-for="(item,index) in ChinaCitys" :key="index">
                  {{item.province}}
                </view>
              </picker-view-column>
              <picker-view-column>
                <view class="picker-item" v-for="(item,index) in locatinCitys" :key="index">
                  {{item.city}}
                </view>
              </picker-view-column>
              <picker-view-column>
                <view class="picker-item" v-for="(item,index) in locationAreas" :key="index">
                  {{item.area}}
                </view>
              </picker-view-column>
            </picker-view>
          </view>
          <view class="popup-footer">
            <view class="popup-btn cancel" @click="hideLocationPopup">
              <text class="btn-text">取消</text>
            </view>
            <view class="popup-btn confirm" @click="confirmLocationSelect">
              <text class="btn-text">确定</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 提示信息弹窗 -->
      <view class="tip-popup" :class="{ show: showTipPopupFlag }">
        <view class="tip-popup-mask" @click="hideTipPopup"></view>
        <view class="tip-popup-content">
          <image class="tip-popup-bg" src="https://mrrplus.oss-cn-beijing.aliyuncs.com/photo/system/ab410a5d-5819-47f2-a0fc-3fd6b90d6770" mode="aspectFit"></image>
          
          <view class="tip-popup-body">
            <view class="tip-title">{{ tipTitle }}</view>
            <view class="tip-image-container">
              <image class="tip-image" :class="currentTipType" :src="tipImage" mode="widthFix"></image>
            </view>
            <view class="tip-buttons">
              <view class="tip-btn cancel" @click="hideTipPopup">
                <text class="btn-text">取消</text>
              </view>
              <view class="tip-btn confirm" @click="hideTipPopup">
                <text class="btn-text">我已了解</text>
              </view>
            </view>
          </view>
        </view>
      </view>
      <!-- 底部安全间距 -->
      <view class="safe-bottom"></view>
    </view>

    <!-- 底部按钮区域 -->
    <view class="bottom-actions" ref="buttonArea">
      <!-- 驳回原因提示 -->
      <view class="reject-reason" v-if="shouldShowRejectReason">
        <view class="reject-title">您的提交已驳回</view>
        <view class="reject-detail">驳回原因：{{ backText }}</view>
      </view>
      <!-- 审核中提示 -->
      <view class="audit-tip" v-if="showAuditTip">
        <text class="audit-text">您的提交变更正在审核中...</text>
      </view>

      <!-- 变更信息按钮 -->
      <view class="action-btn change-info-btn" v-if="buttonType === 'change'" @click="startChange">
        <text class="btn-text">变更信息</text>
      </view>

      <!-- 取消和提交按钮 -->
      <view class="action-buttons-row" v-if="buttonType === 'edit'">
        <view class="action-btn cancel-btn" @click="cancelChange">
          <text class="btn-text cancel-text">取消</text>
        </view>
        <view class="action-btn submit-btn" @click="submitChange">
          <text class="btn-text">提交</text>
        </view>
      </view>

      <!-- 查看我的变更/返回按钮 -->
      <view class="action-btn view-change-btn" v-if="buttonType === 'view'" @click="togglePendingData">
        <text class="btn-text">{{ showPendingData ? '返回' : '查看我的变更' }}</text>
      </view>

      <!-- 重新提交按钮 -->
      <view class="action-btn resubmit-btn" v-if="buttonType === 'reject'" @click="startChange">
        <text class="btn-text">重新提交</text>
      </view>
    </view>
  </view>
</template>

<script>
import request from '../../utils/request';
import uploadImage from '../../utils/uploadImage';
import permissionUtils from '../../utils/per';
import ChinaCitys from '../../static/data/ChinaCitys.json';
import { recognizeIdCard, parseValidPeriod } from '../../utils/orc';

export default {
  data() {
    const currentDate = new Date();
    const currentYear = new Date().getFullYear();
    const years = Array.from({length: 130}, (_, i) => 1970 + i);
    const months = Array.from({length: 12}, (_, i) => i + 1);
    const days = Array.from({length: 31}, (_, i) => i + 1);

    const initialChinaCitys = ChinaCitys || [];
    const initialLocatinCitys = initialChinaCitys[0]?.citys || [];
    const initialLocationAreas = initialLocatinCitys[0]?.areas || [];
    
    return {
      // 页面状态
      editable: false,
      buttonType: 'change', // change-变更信息, edit-取消/提交, view-查看我的变更, reject-重新提交
      showAuditTip: false,
      auditStatus: null, // 审核状态: null-无申请, 1-审核中, 2-审核通过, 3-审核驳回
      applyId: null,
      showPendingData: false, // 是否显示待审核数据
      navTitle: '个人信息',
      buttonAreaHeight: 120,
      backText: '', // 驳回原因
      hasResubmitted: false,
      
      // 数据管理
      originalData: {}, // 老数据（当前生效的）
      pendingData: {}, // 新数据（待审核的）
      displayData: {}, // 当前显示的数据

      // 用户信息
      userId: null,
      identity: null,
      applyType: 5, // 个人信息变更

      // 表单相关
      currentDateField: '',
      years,
      months,
      days,
      dateValue: [currentYear - 1970, currentDate.getMonth(), currentDate.getDate() - 1],
      indicatorStyle: 'height: 68rpx;',
      
      // 地区选择相关
      ChinaCitys: initialChinaCitys,
      locatinCitys: initialLocatinCitys,
      locationAreas: initialLocationAreas,
      locationValue: [0, 0, 0],
      
      showLocationPopupFlag: false,
      showDatePickerFlag: false,

      // 提示弹窗
      showTipPopupFlag: false,
      tipTitle:'',
      tipImage: '',
      currentTipType: '',
      
      // 地址相关字段
      fromAddressPage: false,
      addressListener: null,
      
      // 识别状态
      isRecognizing: false,
      recognizeType: '', // 'idcard_positive', 'idcard_negative'
    }
  },
  computed: {
    shouldShowRejectReason() {
      return this.auditStatus === 3 && !this.showPendingData && this.backText;
    }
  },
  
  async onLoad() {
    console.log('页面开始加载...');
    
    // 监听地址选择事件（参考商家代码）
    uni.$on('address-selected-for-syr', (addressData) => {
      this.handleAddressSelected(addressData);
    });
    
    this.identity = getApp().globalData.artisanType;
    console.log('身份类型:', this.identity);
    
    await this.getUserInfo();
    console.log('用户信息获取完成');
    
    await this.loadApplyDetails();
    console.log('申请详情加载完成');
    
    // 预填用户手机号
    const userInfo = getApp().globalData.userInfo || uni.getStorageSync('userInfo');
    if (userInfo && userInfo.account) {
      this.displayData.account = userInfo.account;
      console.log('预填手机号:', this.displayData.account);
    }
    
    // 获取定位
    await this.getLocation();
    console.log('定位获取完成');
    
    console.log('页面加载完成');
  },
  
  onUnload() {
    // 移除事件监听
    uni.$off('address-selected-for-syr');
  },
  
  onReady() {
    this.getButtonAreaHeight();
  },
  
  onShow() {
    console.log('当前 editable 状态:', this.editable);
    
    // 检查地址数据（放在最前面，确保最先执行）
    this.checkAddressData();
    
    // 只有在非编辑状态下才重新加载数据
    if (!this.editable) {
      console.log('非编辑状态，刷新数据');
      this.loadApplyDetails();
      
      if (this.auditStatus !== 3) {
        this.backText = '';
        this.hasResubmitted = false;
      }
    } else {
      console.log('编辑状态，保持当前状态不刷新');
    }
  },
  
  onHide() {
    this.fromAddressPage = false;
  },

  methods: {
    // OCR识别相关方法
    
    /**
     * 识别身份证正面
     */
    async recognizeIdCardFront(imageUrl) {
      try {
        this.isRecognizing = true;
        this.recognizeType = 'idcard_positive';
        
        uni.showLoading({
          title: '正在识别身份证正面...',
          mask: true
        });
        
        // 调用OCR接口
        const result = await recognizeIdCard(imageUrl, 1);

        // 验证是否真的识别到了数据
        const hasRecognizedData = this.checkIdCardFrontRecognition(result);
        
        if (!hasRecognizedData) {
          uni.hideLoading();
          uni.showToast({
            title: '未识别到身份证信息，请手动填写或重新拍摄',
            icon: 'none',
            duration: 3000
          });
          this.isRecognizing = false;
          return;
        }
        
        // 填充身份证正面信息
        let recognizedFields = 0;
        
        if (result.name) {
          this.displayData.name = result.name;
          recognizedFields++;
        }
        
        if (result.id_number) {
          this.displayData.idcard_num = result.id_number;
          recognizedFields++;
        }
        
        // 根据识别的字段数量给出不同的提示
        if (recognizedFields > 0) {
          uni.showToast({
            title: '身份证正面识别成功',
            icon: 'none'
          });
        } else {
          uni.showToast({
            title: '识别完成，但未获取到有效信息',
            icon: 'none',
            duration: 3000
          });
        }
        
      } catch (error) {
        console.error('身份证正面识别失败:', error);
        uni.showToast({
          title: error.message || '识别失败，请手动填写',
          icon: 'none',
          duration: 3000
        });
      } finally {
        this.isRecognizing = false;
        uni.hideLoading();
      }
    },

    // 检查身份证正面识别结果是否有效
    checkIdCardFrontRecognition(result) {
      return (result.name && result.name.trim()) || (result.id_number && result.id_number.trim());
    },

    /**
     * 识别身份证反面
     */
    async recognizeIdCardBack(imageUrl) {
      try {
        this.isRecognizing = true;
        this.recognizeType = 'idcard_negative';
        
        uni.showLoading({
          title: '正在识别身份证反面...',
          mask: true
        });
        
        // 调用OCR接口
        const result = await recognizeIdCard(imageUrl, 2);

        // 验证是否真的识别到了数据
        const hasRecognizedData = this.checkIdCardBackRecognition(result);
        
        if (!hasRecognizedData) {
          uni.hideLoading();
          uni.showToast({
            title: '未识别到身份证有效期信息，请手动填写或重新拍摄',
            icon: 'none',
            duration: 3000
          });
          this.isRecognizing = false;
          return;
        }
        
        // 解析有效期
        const validPeriod = parseValidPeriod(result.start_date, result.end_date);
        
        // 填充有效期数据
        if (validPeriod.startDate) {
          this.displayData.idcard_start_date = validPeriod.startDate;
        }
        
        if (validPeriod.isPermanent) {
          this.displayData.idcard_expiry_type = 1;
          this.displayData.idcard_end_date = '长久有效';
        } else if (validPeriod.endDate) {
          this.displayData.idcard_expiry_type = 2;
          this.displayData.idcard_end_date = validPeriod.endDate;
        }
        
        uni.showToast({
          title: '身份证反面识别成功',
          icon: 'none'
        });
        
      } catch (error) {
        console.error('身份证反面识别失败:', error);
        uni.showToast({
          title: error.message || '识别失败，请手动填写',
          icon: 'none',
          duration: 3000
        });
      } finally {
        this.isRecognizing = false;
        uni.hideLoading();
      }
    },

    // 检查身份证反面识别结果是否有效
    checkIdCardBackRecognition(result) {
      return (result.start_date && result.start_date.trim()) || 
             (result.end_date && result.end_date.trim());
    },

    // ============ 地址选择相关方法 ============
    // 检查地址数据
    checkAddressData() {
      console.log('=== 执行 checkAddressData ===');
      
      try {
        // 先检查手艺人专用存储
        const syrAddress = uni.getStorageSync('syr_selected_address');
        console.log('检查 syr_selected_address:', syrAddress);
        
        if (syrAddress) {
          console.log('找到手艺人地址数据，调用 handleAddressSelected');
          this.handleAddressSelected(syrAddress);
          uni.removeStorageSync('syr_selected_address');
          return;
        }
      } catch (e) {
        console.error('检查手艺人地址失败:', e);
      }
      
      // 检查通用存储
      try {
        const storedAddress = uni.getStorageSync('selectedAddress');
        console.log('检查 selectedAddress:', storedAddress);
        
        if (storedAddress) {
          this.handleAddressSelected(storedAddress);
          uni.removeStorageSync('selectedAddress');
          return;
        }
      } catch (e) {
        console.error('检查通用地址存储失败:', e);
      }
      
      // 检查全局数据
      if (getApp().globalData && getApp().globalData.selectedAddress) {
        console.log('从 globalData 获取地址:', getApp().globalData.selectedAddress);
        this.handleAddressSelected(getApp().globalData.selectedAddress);
        delete getApp().globalData.selectedAddress;
      }
    },

    // 处理地址选择结果
    handleAddressSelected(addressData) {
      if (!addressData || !addressData.name) {
        console.log('地址数据无效:', addressData);
        return;
      }
      
      // 提取地址
      const address = addressData.name || addressData.address || '';
      if (!address) {
        console.log('无法提取地址');
        return;
      }
      
      console.log('设置地址:', address);
      
      // 更新 displayData
      this.displayData.address = address;
      
      // 更新经纬度
      if (addressData.location) {
        const [longitude, latitude] = addressData.location.split(',');
        this.displayData.longitude = longitude || '';
        this.displayData.latitude = latitude || '';
      }
      
      // 更新省市区信息（如果地址数据中有的话）
      if (addressData.pname || addressData.cityname || addressData.adname) {
        const locationParts = [];
        if (addressData.pname) locationParts.push(addressData.pname);
        if (addressData.cityname) locationParts.push(addressData.cityname);
        if (addressData.adname) locationParts.push(addressData.adname);
        const newDependency = locationParts.join('-');
        this.displayData.dependency = newDependency;
      }
      
      // 同时更新 pendingData
      this.pendingData.address = address;
      this.pendingData.longitude = this.displayData.longitude;
      this.pendingData.latitude = this.displayData.latitude;
      this.pendingData.dependency = this.displayData.dependency;
      
      console.log('地址更新完成:', {
        address: this.displayData.address,
        dependency: this.displayData.dependency,
        longitude: this.displayData.longitude,
        latitude: this.displayData.latitude
      });
      
      // 显示成功提示
      // uni.showToast({
      //   title: '地址已选择',
      //   icon: 'none',
      //   duration: 2000
      // });
      
      // 强制视图更新
      this.$forceUpdate();
      
      // 延迟刷新，确保视图更新
      setTimeout(() => {
        console.log('延迟刷新视图');
        this.$forceUpdate();
      }, 100);
    },

    // 清理地址存储
    clearAddressStorage() {
      try {
        uni.removeStorageSync('selectedAddress');
        uni.removeStorageSync('syr_selected_address');
        if (getApp().globalData) {
          getApp().globalData.selectedAddress = null;
        }
        console.log('已清理地址存储');
      } catch (error) {
        console.error('清理地址存储失败:', error);
      }
    },
    
    // 获取详细地址
    getAddressInfo() {
      if (!this.editable) return;
      
      // 构建URL参数
      let params = 'source=syr_info';
      
      // 如有所在地，添加dependency参数
      if (this.displayData.dependency) {
        const locationStr = encodeURIComponent(this.displayData.dependency);
        params += `&dependency=${locationStr}`;
        
        if (this.displayData.dependency_code) {
          params += `&dependency_code=${this.displayData.dependency_code}`;
        }
        
        console.log('传递的地区信息:', this.displayData.dependency);
        console.log('编码后的地区信息:', locationStr);
      }
      
      // 如有已选择的地址坐标，也传递过去作为初始位置
      if (this.displayData.longitude && this.displayData.latitude) {
        params += `&longitude=${this.displayData.longitude}&latitude=${this.displayData.latitude}`;
      }
      
      console.log('跳转URL参数:', params);
      
      // 清理旧的地址数据
      try {
        uni.removeStorageSync('syr_selected_address');
        uni.removeStorageSync('selectedAddress');
        if (getApp().globalData) {
          getApp().globalData.selectedAddress = null;
        }
        console.log('已清理旧地址数据');
      } catch (error) {
        console.error('清理地址存储失败:', error);
      }
      
      uni.navigateTo({
        url: `/pages/address/search?${params}`,
        success: () => {
          console.log('成功跳转到地址选择页面');
        },
        fail: (err) => {
          console.error('跳转地址选择页面失败:', err);
        }
      });
    },

    // 保存当前数据（可选）
    saveCurrentData() {
      try {
        // 如果需要保存当前表单数据，可以在这里实现
        const currentData = {
          address: this.displayData.address,
          longitude: this.displayData.longitude,
          latitude: this.displayData.latitude
        };
        uni.setStorageSync('current_address_data', currentData);
      } catch (e) {
        console.error('保存当前数据失败:', e);
      }
    },

    // 获取用户信息（包含老信息）
    async getUserInfo() {
      try {
        const result = await request.post('/user/getuser', { type: 2 }); // type=2 手艺人
        
        if (result.state === 1 && result.data) {
          const userData = result.data;
          console.log('获取到的用户数据:', userData);
          
          this.userId = userData.id;
          
          // 初始化老数据
          this.originalData = {
            head_photo: userData.head_photo || '',
            name: userData.name || userData.real_name || '',
            account: userData.account || userData.phone || '',
            second_phone: userData.second_phone || userData.backup_phone || '',
            idcard_num: userData.idcard_num || userData.id_card || '',
            idcard_expiry_type: userData.idcard_expiry_type || 0,
            idcard_positive: userData.idcard_positive || userData.id_card_front || '',
            idcard_negative: userData.idcard_negative || userData.id_card_back || '',
            idcard_hands: userData.idcard_hands || userData.id_card_handheld || '',
            detail: userData.detail || userData.introduction || '',
            dependency: userData.dependency || userData.region || '',
            address: userData.address || userData.detail_address || '',
            dependency_code: userData.dependency_code || '',
            dependency_province: userData.dependency_province || '',
            dependency_city: userData.dependency_city || '',
            major: userData.major || userData.professional_experience || '',
            work_state: userData.work_state || userData.work_status || '',
            longitude: userData.longitude || '',
            latitude: userData.latitude || '',
            idcard_start_date: '',
            idcard_end_date: ''
          };

          // 处理身份证有效期
          if (userData.idcard_expiry) {
            this.processIdcardExpiry(userData.idcard_expiry, this.originalData);
          }

          // 初始化pendingData和displayData
          this.pendingData = { ...this.originalData };
          this.displayData = { ...this.originalData };
          
          console.log('数据初始化完成:', {
            originalData: this.originalData,
            pendingData: this.pendingData,
            displayData: this.displayData
          });
        } else {
          console.error('获取用户信息失败:', result.msg);
        }
      } catch (error) {
        console.error('获取用户信息接口错误:', error);
      }
    },

    // 加载申请详情
    async loadApplyDetails() {
      try {
        console.log('开始加载申请详情...');
        const res = await request.post('/syr/userSyrAuth/details', {
          apply_type: this.applyType
        });

        console.log('申请详情接口返回:', res);
        
        if (res.code === 200 && res.data) {
          const detail = res.data;
          
          this.applyId = detail.id;
          this.auditStatus = detail.apply_state;
          this.backText = detail.back_text || '';
          
          console.log('审核状态:', this.auditStatus);
          console.log('驳回原因:', this.backText);

          // 更新pendingData
          if (this.auditStatus === 1 || this.auditStatus === 3) {
            this.pendingData = {
              head_photo: detail.head_photo || this.originalData.head_photo,
              name: detail.name || this.originalData.name,
              account: detail.account || this.originalData.account,
              second_phone: detail.second_phone || this.originalData.second_phone,
              idcard_num: detail.idcard_num || this.originalData.idcard_num,
              idcard_expiry_type: detail.idcard_expiry_type || this.originalData.idcard_expiry_type,
              idcard_positive: detail.idcard_positive || this.originalData.idcard_positive,
              idcard_negative: detail.idcard_negative || this.originalData.idcard_negative,
              idcard_hands: detail.idcard_hands || this.originalData.idcard_hands,
              detail: detail.detail || this.originalData.detail,
              dependency: detail.dependency || this.originalData.dependency,
              address: detail.address || this.originalData.address,
              dependency_code: detail.dependency_code || this.originalData.dependency_code,
              dependency_province: detail.dependency_province || this.originalData.dependency_province,
              dependency_city: detail.dependency_city || this.originalData.dependency_city,
              major: detail.major || this.originalData.major,
              work_state: detail.work_state || this.originalData.work_state,
              longitude: detail.longitude || this.originalData.longitude,
              latitude: detail.latitude || this.originalData.latitude,
              idcard_start_date: '',
              idcard_end_date: ''
            };

            // 处理身份证有效期
            if (detail.idcard_expiry) {
              this.processIdcardExpiry(detail.idcard_expiry, this.pendingData);
            }
          }
          
          // 审核通过时同步数据
          if (this.auditStatus === 2) {
            this.originalData = { ...this.pendingData };
          }
          
          this.updatePageStatus();
          
        } else {
          console.log('申请详情返回数据为空或state不为1:', res);
          this.backText = '';
          this.updatePageStatus();
        }
        
      } catch (error) {
        console.error('加载申请详情失败:', error);
        this.backText = '';
        this.updatePageStatus();
      }
    },

    // 更新页面状态
    updatePageStatus() {
      console.log('更新页面状态，审核状态:', this.auditStatus);

      // 如果已经重新提交过，强制设置为审核中状态
      if (this.hasResubmitted && this.auditStatus === 3) {
        console.log('检测到已重新提交，强制设置为审核中状态');
        this.auditStatus = 1;
        this.backText = '';
      }

      if (this.auditStatus === 1) { // 审核中
        this.showAuditTip = true;
        this.buttonType = 'view';
        this.editable = false;
        this.showPendingData = false;
        this.displayData = { ...this.originalData };
        console.log('状态更新为：审核中');
      } else if (this.auditStatus === 3) { // 审核驳回
        this.showAuditTip = false;
        this.buttonType = 'reject';
        this.editable = false;
        this.showPendingData = false;
        this.displayData = { ...this.originalData };
        console.log('状态更新为：审核驳回');
      } else { // 无申请或审核通过
        this.showAuditTip = false;
        this.buttonType = 'change';
        this.editable = false;
        this.showPendingData = false;
        this.displayData = { ...this.originalData };
        console.log('状态更新为：无申请/审核通过');
      }

      this.updateNavTitle();
      console.log('最终页面状态:', {
        auditStatus: this.auditStatus,
        backText: this.backText,
        buttonType: this.buttonType,
        editable: this.editable,
        showAuditTip: this.showAuditTip
      });
    },

    // 更新导航栏标题
    updateNavTitle() {
      if (this.editable || this.showPendingData) {
        this.navTitle = '个人信息变更';
      } else {
        this.navTitle = '个人信息';
      }
    },

    // 处理身份证有效期
    processIdcardExpiry(expiry, targetData) {
      if (!expiry) return;
      
      console.log('处理身份证有效期:', expiry);
      
      if (expiry.includes('——')) {
        const [startStr, endStr] = expiry.split('——');
        const startDate = startStr.trim();
        const endDate = endStr.trim();
        
        console.log('开始日期:', startDate, '结束日期:', endDate);
        
        if (endDate === '长久' || !endDate) {
          targetData.idcard_expiry_type = 1;
          targetData.idcard_start_date = this.formatDateFromBackend(startDate);
          targetData.idcard_end_date = '长久有效';
        } else {
          targetData.idcard_expiry_type = 2;
          targetData.idcard_start_date = this.formatDateFromBackend(startDate);
          targetData.idcard_end_date = this.formatDateFromBackend(endDate);
        }
      } else if (expiry === '长久') {
        targetData.idcard_expiry_type = 1;
        targetData.idcard_end_date = '长久有效';
      }
    },

    // 从后端格式转换日期
    formatDateFromBackend(dateStr) {
      if (!dateStr) return '';
      if (dateStr.includes('-')) {
        const [year, month, day] = dateStr.split('-');
        return `${year}年${parseInt(month)}月${parseInt(day)}日`;
      }
      return dateStr;
    },

    // 获取专业经验文本
    getExperienceText(value) {
      const experiences = ['', '实习', '1-3年', '3-5年', '5-10年', '10年以上'];
      return experiences[value] || '';
    },

    // 获取工作状态文本
    getWorkStatusText(value) {
      const statusList = ['', '在职', '离职'];
      return statusList[value] || '';
    },

    // 开始变更
    startChange() {
      this.editable = true;
      this.buttonType = 'edit';
      // 进入编辑模式时，将pendingData复制到displayData进行编辑
      this.displayData = { ...this.pendingData };
      this.updateNavTitle();
    },

    // 取消变更
    cancelChange() {
      this.editable = false;
      this.buttonType = 'change';
      // 恢复显示原始数据
      this.displayData = { ...this.originalData };
      this.updateNavTitle();
    },

    // 切换显示待审核数据
    togglePendingData() {
      this.showPendingData = !this.showPendingData;
      if (this.showPendingData) {
        // 显示待审核数据
        this.displayData = { ...this.pendingData };
      } else {
        // 显示原始数据
        this.displayData = { ...this.originalData };
      }
      this.updateNavTitle();
    },

    // 设置身份证有效期类型
    setIdCardValidType(type) {
      this.displayData.idcard_expiry_type = type;
      if (type === 1) {
        this.displayData.idcard_end_date = '长久有效';
      } else {
        if (this.displayData.idcard_end_date === '长久有效') {
          this.displayData.idcard_end_date = '';
        }
      }
    },

    // 日期格式化方法
    formatDateForDisplay(dateStr) {
      if (!dateStr) return '';
      if (dateStr === '长久有效') return '长久有效';
      
      if (dateStr.includes('-')) {
        const [year, month, day] = dateStr.split('-');
        return `${year}年${parseInt(month)}月${parseInt(day)}日`;
      }
      
      return dateStr;
    },

    formatDateForBackend(dateStr) {
      if (!dateStr) return '';
      if (dateStr === '长久有效') return '长久有效';
      
      const match = dateStr.match(/(\d+)年(\d+)月(\d+)日/);
      if (match) {
        const year = match[1];
        const month = match[2].padStart(2, '0');
        const day = match[3].padStart(2, '0');
        return `${year}-${month}-${day}`;
      }
      
      return dateStr;
    },

    // 日期选择器方法
    openDatePicker(field) {
      this.currentDateField = field;
      
      const currentDate = new Date();
      let initialDate = currentDate;
      
      if (this.displayData[field] && this.displayData[field] !== '长久有效') {
        const dateStr = this.displayData[field];
        const match = dateStr.match(/(\d+)年(\d+)月(\d+)日/);
        if (match) {
          initialDate = new Date(parseInt(match[1]), parseInt(match[2]) - 1, parseInt(match[3]));
        }
      }
      
      const yearIndex = this.years.indexOf(initialDate.getFullYear());
      const monthIndex = initialDate.getMonth();
      const dayIndex = initialDate.getDate() - 1;
      
      this.dateValue = [
        yearIndex >= 0 ? yearIndex : 0,
        monthIndex,
        dayIndex
      ];
      
      this.showDatePickerFlag = true;
    },
    
    hideDatePicker() {
      this.showDatePickerFlag = false;
    },
    
    bindDateChange(e) {
      this.dateValue = e.detail.value;
    },
    
    confirmDate() {
      const [yearIndex, monthIndex, dayIndex] = this.dateValue;
      const year = this.years[yearIndex];
      const month = this.months[monthIndex];
      const day = this.days[dayIndex];
      const dateStr = `${year}年${month}月${day}日`;
      const selectedDate = new Date(year, month - 1, day);
      const today = new Date();
      today.setHours(0, 0, 0, 0);
      
      if (this.currentDateField.endsWith('_start_date')) {
        if (selectedDate > today) {
          uni.showToast({
            title: '开始日期不能晚于今天',
            icon: 'none'
          });
          return;
        }
        
        const relatedEndField = this.currentDateField.replace('_start_date', '_end_date');
        if (this.displayData[relatedEndField] && this.displayData[relatedEndField] !== '长久有效') {
          const endDateStr = this.displayData[relatedEndField];
          const match = endDateStr.match(/(\d+)年(\d+)月(\d+)日/);
          if (match) {
            const endDate = new Date(parseInt(match[1]), parseInt(match[2]) - 1, parseInt(match[3]));
            if (selectedDate > endDate) {
              uni.showToast({
                title: '开始日期不能晚于结束日期',
                icon: 'none'
              });
              return;
            }
          }
        }
        
        // 恢复自动计算20年结束日期的逻辑
        if (this.currentDateField === 'idcard_start_date') {
          const endYear = year + 20;
          const endDateStr = `${endYear}年${month}月${day}日`;
          this.displayData.idcard_end_date = endDateStr;
        }

      } else if (this.currentDateField.endsWith('_end_date')) {
        const relatedStartField = this.currentDateField.replace('_end_date', '_start_date');
        if (this.displayData[relatedStartField]) {
          const startDateStr = this.displayData[relatedStartField];
          const match = startDateStr.match(/(\d+)年(\d+)月(\d+)日/);
          if (match) {
            const startDate = new Date(parseInt(match[1]), parseInt(match[2]) - 1, parseInt(match[3]));
            if (selectedDate <= startDate) {
              uni.showToast({
                title: '结束日期必须晚于开始日期',
                icon: 'none'
              });
              return;
            }
          }
        } else {
          if (selectedDate < today) {
            uni.showToast({
              title: '结束日期不能早于今天',
              icon: 'none'
            });
            return;
          }
        }
      }
      
      this.displayData[this.currentDateField] = dateStr;
      this.hideDatePicker();
    },

    // 所在地选择方法
    showLocationPopup() {
      if (!this.editable) return;
      
      if (this.ChinaCitys && this.ChinaCitys.length > 0) {
        this.locatinCitys = this.ChinaCitys[0].citys;
        if (this.locatinCitys && this.locatinCitys.length > 0) {
          this.locationAreas = this.locatinCitys[0].areas;
        } else {
          this.locationAreas = [];
        }
        this.locationValue = [0, 0, 0];
      }
      this.showLocationPopupFlag = true;
    },

    hideLocationPopup() {
      this.showLocationPopupFlag = false;
    },

    bindChangeLocation(e) {
      this.locationValue = e.detail.value;
      let index1 = e.detail.value[0] || 0;
      let index2 = e.detail.value[1] || 0;
      this.locatinCitys = this.ChinaCitys[index1].citys;
      this.locationAreas = this.locatinCitys[index2].areas;
    },

    // 在选择所在地后清空详细地址
    confirmLocationSelect() {
      let valueArr = this.locationValue;
      let index1 = valueArr[0] || 0;
      let index2 = valueArr[1] || 0;
      let index3 = valueArr[2] || 0;
      let province = this.ChinaCitys[index1].province;
      let city = this.locatinCitys[index2].city;
      let area = this.locationAreas[index3].area;
      this.displayData.dependency = province + '-' + city + '-' + area;

      // 清空详细地址，因为所在地已经改变
      this.displayData.address = '';
      this.displayData.longitude = '';
      this.displayData.latitude = '';
      
      // 同时清空pendingData中的地址信息
      this.pendingData.address = '';
      this.pendingData.longitude = '';
      this.pendingData.latitude = '';

      if (this.ChinaCitys[index1] && this.ChinaCitys[index1].code) {
        let provinceCode = this.ChinaCitys[index1].code.toString();
        this.displayData.dependency_province = provinceCode.substring(0, 6);
        this.pendingData.dependency_province = provinceCode.substring(0, 6);
      }
      if (this.locatinCitys[index2] && this.locatinCitys[index2].code) {
        let cityCode = this.locatinCitys[index2].code.toString();
        this.displayData.dependency_city = cityCode.substring(0, 6);
        this.pendingData.dependency_city = cityCode.substring(0, 6);
      }
      if (this.locationAreas[index3] && this.locationAreas[index3].code) {
        let areaCode = this.locationAreas[index3].code.toString();
        this.displayData.dependency_code = areaCode.substring(0, 6);
        this.pendingData.dependency_code = areaCode.substring(0, 6);
      }

      console.log('地址编码:', {
        province: this.displayData.dependency_province,
        city: this.displayData.dependency_city,
        area: this.displayData.dependency_code
      });

      this.hideLocationPopup();
    },

    // 定位方法
    async getLocation() {
      try {
        const location = await new Promise((resolve, reject) => {
          uni.getLocation({
            type: 'wgs84',
            success: resolve,
            fail: reject
          });
        });
        
        this.displayData.longitude = location.longitude.toString();
        this.displayData.latitude = location.latitude.toString();
        console.log('获取定位成功:', this.displayData.longitude, this.displayData.latitude);
      } catch (error) {
        console.log('获取定位失败，使用默认值');
        this.displayData.longitude = '116.397428';
        this.displayData.latitude = '39.90923';
      }
    },

    // 其他选择器方法
    openExperiencePicker() {
      if (!this.editable) return;
      
      uni.showActionSheet({
        itemList: ['实习', '1-3年', '3-5年', '5-10年', '10年以上'],
        success: (res) => {
          this.displayData.major = res.tapIndex + 1;
        }
      });
    },

    openWorkStatusPicker() {
      if (!this.editable) return;
      
      uni.showActionSheet({
        itemList: ['在职', '离职'],
        success: (res) => {
          this.displayData.work_state = res.tapIndex + 1;
        }
      });
    },

    // 图片上传方法
    async chooseImage(type) {
      if (!this.editable) return;
      
      try {
        const systemInfo = uni.getSystemInfoSync();
        
        if (systemInfo.platform === 'ios') {
          this.openCamera(type);
        } else {
          const xc = await permissionUtils.checkPermission('photo_library', '需要相册权限用于上传照片');
          const xj = await permissionUtils.checkPermission('camera', '需要相机权限用于拍摄照片');
          if (xc.granted && xj.granted) {
            this.openCamera(type);
            return;
          }

          const result1 = await permissionUtils.requestPermission('photo_library', '我们需要访问您的相册以上传图片/视频');
          const result2 = await permissionUtils.requestPermission('camera', '我们需要访问您的相机以上传图片/视频');
          if (result1 && result2) {
            this.openCamera(type);
          }
        }
      } catch (err) {
        console.log('选择图片出错:', err);
        this.openCamera(type);
      }
    },

    async openCamera(type) {
      try {
        if (!this.userId) {
          await this.getUserInfo();
        }
        
        if (!this.identity) {
          this.identity = getApp().globalData.artisanType;
        }

        const chooseResult = await new Promise((resolve, reject) => {
          uni.chooseImage({
            count: 1,
            sizeType: ['compressed'],
            sourceType: ['album', 'camera'],
            success: resolve,
            fail: reject
          });
        });

        if (!chooseResult.tempFilePaths || chooseResult.tempFilePaths.length === 0) {
          uni.hideLoading();
          return;
        }

        const tempFilePath = chooseResult.tempFilePaths[0];
        const file = {
          path: tempFilePath,
          size: 0
        };

        const result = await this.directUpload(file, this.userId, this.identity + 1);
        
        // 上传成功，更新loading显示为识别中
        uni.hideLoading();
        
        if (result) {
          this.displayData[type] = result;
          
          // 上传成功后自动识别
          if (type === 'idcard_positive') {
            await this.recognizeIdCardFront(result);
          } else if (type === 'idcard_negative') {
            await this.recognizeIdCardBack(result);
          }
        }
      } catch (err) {
        uni.hideLoading();
        console.log('上传图片错误:', err);
      }
    },

    // 直接上传方法
    async directUpload(file, userId, type) {
      try {
        let date = new Date().getTime();
        let artisan = type == 1 ? 'yh' : type == 2 ? 'syr' : type == 3 ? 'sj' : '';
        
        let fileExtension = 'jpg';
        if (file.path.includes('.')) {
          let parts = file.path.split('.');
          let ext = parts[parts.length - 1].toLowerCase();
          if (ext && ext.length <= 4) {
            fileExtension = ext;
          }
        }
        
        let name = `${userId}_${artisan}_${date}.${fileExtension}`;

        const ossConfig = await request.post('/user/getalioss', {type: type, kind: 1});
        
        return await new Promise((resolve, reject) => {
          uni.uploadFile({
            url: ossConfig.host,
            filePath: file.path,
            name: 'file',
            formData: {
              key: ossConfig.dir + name,
              policy: ossConfig.policy,
              OSSAccessKeyId: ossConfig.ossAccessKeyId,
              success_action_status: '200',
              signature: ossConfig.signature
            },
            success: (res) => {
              if (res.statusCode === 200) {
                const fileUrl = `${ossConfig.host}/${ossConfig.dir}${name}`;
                resolve(fileUrl);
              } else {
                reject(new Error('上传失败'));
              }
            },
            fail: reject
          });
        });
        
      } catch (error) {
        console.error('直接上传失败:', error);
        throw error;
      }
    },

    // 显示提示弹窗
    showTipPopup(field) {
      const tipConfig = {
        'head_photo': {
          title: '如何查看工装头像',
          image: 'https://mrrplus.oss-cn-beijing.aliyuncs.com/photo/system/2af00609-f9f5-4fa7-8013-ef92f15bbea3'
        }
      };
      
      if (tipConfig[field]) {
        this.currentTipType = field;
        this.tipTitle = tipConfig[field].title;
        this.tipImage = tipConfig[field].image;
        this.showTipPopupFlag = true;
      }
    },
    
    // 隐藏提示弹窗
    hideTipPopup() {
      this.showTipPopupFlag = false;
    },

    // 验证表单
    validateForm() {
      const validationRules = [
        { field: 'head_photo', message: '请上传头像' },
        { field: 'idcard_positive', message: '请上传身份证正面照片' },
        { field: 'idcard_negative', message: '请上传身份证反面照片' },
        { field: 'name', message: '请输入真实姓名' },
        { field: 'account', message: '请输入联系方式' },
        { field: 'second_phone', message: '请输入备用联系方式' },
        { field: 'idcard_num', message: '请输入身份证号' },
        { 
          condition: () => !this.displayData.idcard_expiry_type, 
          message: '请选择身份证有效期类型' 
        },
        { 
          condition: () => !this.displayData.idcard_start_date, 
          message: '请选择身份证开始日期' 
        },
        {
          condition: () => {
            if (this.displayData.idcard_expiry_type === 2 && !this.displayData.idcard_end_date) {
              return true;
            }
            // 如果选择长久有效，则不需要结束日期
            return false;
          },
          message: '请选择身份证结束日期' 
        },

        { field: 'detail', message: '请输入个人介绍' },
        { field: 'dependency', message: '请选择所在地' },
        { field: 'address', message: '请选择详细地址' },
        { field: 'major', message: '请选择专业经验' },
        { field: 'work_state', message: '请选择目前工作状态' }
      ];

      for (let rule of validationRules) {
        let isValid = true;
        
        if (rule.field) {
          if (!this.displayData[rule.field]) {
            isValid = false;
          }
        } else if (rule.condition) {
          if (rule.condition()) {
            isValid = false;
          }
        }
        
        if (!isValid) {
          uni.showToast({
            title: rule.message,
            icon: 'none'
          });
          return false;
        }
      }
      
      // 验证手机号格式
      if (this.displayData.account && !/^1[3-9]\d{9}$/.test(this.displayData.account)) {
        uni.showToast({
          title: '请输入正确的手机号码',
          icon: 'none'
        });
        return false;
      }
      if (this.displayData.second_phone && !/^1[3-9]\d{9}$/.test(this.displayData.second_phone)) {
        uni.showToast({
          title: '请输入正确的备用手机号码',
          icon: 'none'
        });
        return false;
      }
      
      // 验证身份证格式
      if (!/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(this.displayData.idcard_num)) {
        uni.showToast({
          title: '请输入正确的身份证号码',
          icon: 'none'
        });
        return false;
      }
      
      return true;
    },

    // 提交变更
    async submitChange() {
      console.log('开始提交变更...');
      
      if (!this.validateForm()) {
        return;
      }

      try {
        uni.showLoading({
          title: '提交中...',
          mask: true
        });

        // 身份证姓名验证
        const checkRes = await request.post('/user/check', {
          name: this.displayData.name,
          idcard: this.displayData.idcard_num
        });
        
        if (checkRes.Code == '401') {
          uni.hideLoading();
          uni.showToast({
            title: '您的身份证号与姓名不匹配',
            icon: 'none'
          });
          return;
        }
        
        if (checkRes.ResultObject?.BizCode != '1') {
          uni.hideLoading();
          uni.showToast({
            title: '您的身份证号与姓名不匹配',
            icon: 'none'
          });
          return;
        }

        // 构建提交数据
        const submitData = {
          apply_type: this.applyType, // 个人信息变更
          head_photo: this.displayData.head_photo,
          name: this.displayData.name,
          second_phone: this.displayData.second_phone,
          idcard_num: this.displayData.idcard_num,
          idcard_expiry_type: this.displayData.idcard_expiry_type,
          idcard_positive: this.displayData.idcard_positive,
          idcard_negative: this.displayData.idcard_negative,
          idcard_hands: this.displayData.idcard_hands,
          detail: this.displayData.detail,
          dependency: this.displayData.dependency,
          address: this.displayData.address,
          longitude: this.displayData.longitude,
          latitude: this.displayData.latitude,
          dependency_code: this.displayData.dependency_code,
          dependency_province: this.displayData.dependency_province,
          dependency_city: this.displayData.dependency_city,
          major: this.displayData.major,
          work_state: this.displayData.work_state
        };

        // 处理身份证有效期
        if (this.displayData.idcard_expiry_type === 1) {
          submitData.idcard_expiry = '长久';
        } else if (this.displayData.idcard_expiry_type === 2) {
          const startDate = this.formatDateForBackend(this.displayData.idcard_start_date);
          const endDate = this.formatDateForBackend(this.displayData.idcard_end_date);
          submitData.idcard_expiry = `${startDate} —— ${endDate}`;
        }

        console.log('提交数据:', submitData);

        const result = await request.post('/syr/userSyrAuth/apply', submitData);
        
        uni.hideLoading();

        if (result.code === 200) {
          uni.showToast({
            title: '提交成功',
            icon: 'none'
          });
          
          // 提交成功后重置状态
          this.backText = '';
          this.auditStatus = 1;
          this.hasResubmitted = true;
          
          console.log('提交成功，重置所有状态');
          
          // 更新pendingData为当前提交的数据
          this.pendingData = { ...this.displayData };
          
          // 更新页面状态为审核中
          this.editable = false;
          this.buttonType = 'view';
          this.showAuditTip = true;
          this.showPendingData = false;
          
          // 重新加载申请详情获取最新状态
          setTimeout(() => {
            this.loadApplyDetails();
          }, 1500);
        } else {
          uni.showToast({
            title: result.msg || '提交失败',
            icon: 'none'
          });
        }
      } catch (error) {
        uni.hideLoading();
        console.error('提交失败:', error);
        uni.showToast({
          title: '提交失败，请重试',
          icon: 'none'
        });
      }
    },

    // 获取按钮区域高度
    getButtonAreaHeight() {
      setTimeout(() => {
        const query = uni.createSelectorQuery().in(this);
        query.select('.bottom-actions').boundingClientRect(data => {
          if (data) {
            this.buttonAreaHeight = data.height + 20;
          }
        }).exec();
      }, 100);
    }
  }
}
</script>

<style scoped>
.personal-info-page {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background: #f5f5f5;
}

.content-area {
  flex: 1;
  overflow-y: auto;
  padding: 20rpx 20rpx;
  padding-bottom: 0;
}

/* 变更提示 */
.change-tip {
  background: #FAE7EC;
  padding: 20rpx;
  text-align: center;
}

.change-tip text {
  font-size: 28rpx;
  color: #D4131F;
}

/* 驳回原因样式 */
.reject-reason {
  background: transparent;
  padding: 24rpx;
}

.reject-title {
  font-family: PingFangSC, PingFang SC;
  font-weight: 500;
  font-size: 32rpx;
  color: #333333;
  line-height: 45rpx;
  text-align: center;
  font-style: normal;
}

.reject-detail {
  font-family: PingFangSC, PingFang SC;
  font-weight: 400;
  font-size: 28rpx;
  color: #999999;
  line-height: 40rpx;
  text-align: center;
  font-style: normal;
  margin-top: 12rpx;

}

/* 审核中提示 */
.audit-tip {
  margin: 20rpx 24rpx 20rpx 24rpx;
  border-radius: 12rpx;
}

.audit-text {
  font-weight: 400;
  font-size: 32rpx;
  color: #333333;
  text-align: center;
  display: block;
}

/* 底部按钮样式 */
.bottom-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 0rpx 24rpx 40rpx 24rpx;
  background: #ffffff;
  z-index: 100;
}

.action-btn {
  height: 88rpx;
  border-radius: 43rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 32rpx;
  font-weight: 400;
}

.change-info-btn, .view-change-btn, .resubmit-btn {
  background: linear-gradient(180deg, #f52540 0%, #e8101e 100%);
}

/* 双按钮行样式 */
.action-buttons-row {
  display: flex;
  justify-content: space-between;
  margin: 0 30rpx;
}

.action-buttons-row .action-btn {
  width: 270rpx;
}

.cancel-btn {
  background: #E5E5E5;
  border-radius: 43rpx;
  padding: 0 15rpx;
}

.submit-btn {
  background: linear-gradient(180deg, #F52540 0%, #E8101E 100%, #E8101E 100%);
  border-radius: 43rpx;
  padding: 0 15rpx;
}

.btn-text {
  font-family: PingFangSC, PingFang SC;
  font-weight: 400;
  font-size: 36rpx;
  color: #FFFFFF;
  line-height: 50rpx;
  text-align: left;
  font-style: normal;
}

.cancel-text {
  color: #666666;
}

.section {
  margin-bottom: 30rpx;
}

.section-title {
  display: flex;
  align-items: center;
  margin-bottom: 30rpx;
}

.title-bar {
  width: 6rpx;
  height: 30rpx;
  background-color: #E8101E;
  margin-right: 7rpx;
  border-radius: 5rpx;
}

.title-text {
  font-family: PingFangSC, PingFang SC;
  font-weight: 500;
  font-size: 32rpx;
  color: #1D2129;
  line-height: 48rpx;
}

.box-cont {
  background: #ffffff;
  border-radius: 20rpx;
  margin-bottom: 24rpx;
  margin-left: 8rpx;
  margin-right: 8rpx;
  box-shadow: none;

}

.form-item {
  padding: 24rpx;
}

.form-item-one {
  display: flex;
  align-items: center;
  padding: 24rpx;
}

.form-item-two {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 24rpx;
}

.label-wrapper {
  display: inline-flex;
  align-items: center;
}

.label {
  font-size: 28rpx;
  color: #333333;
  font-weight: 500;
  line-height: 1;
  min-width: 200rpx;
}

.label-icon {
  width: 26rpx;
  height: 26rpx;
  margin-left: -65rpx;
  align-items: center;
}

.required::before {
  content: '*';
  color: #FF0000;
  margin-right: 4rpx;
}

.upload-tip {
  font-size: 26rpx;
  color: #999;
  margin: 35rpx 20rpx 20rpx 20rpx;
  font-weight: 400;
  font-family: PingFangSC, PingFang SC;
  text-align: center;
  font-style: normal;
  line-height: 40rpx;
}

.upload-tip-sfz {
  font-size: 26rpx;
  color: #999;
  margin: 10rpx 0 30rpx 0;
  font-weight: 400;
  font-family: PingFangSC, PingFang SC;
  font-style: normal;
}

.upload-box {
  display: flex;
  justify-content: center;
  align-items: center;
}

.upload-camera {
  width: 446rpx;
  height: 298rpx;
  border-radius: 48rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
  background-color: #F8F9FD;
  position: relative;
}

.head_photo-upload {
  width: 120rpx;
  height: 120rpx;
  border-radius: 0;
}

.idcard-upload-vertical-container {
  display: flex;
  flex-direction: column;
  padding: 24rpx;
}

.idcard-upload-vertical-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 45rpx;
}

.idcard-upload-vertical-item:last-child {
  margin-bottom: -5rpx;
}

.upload-label.required::before {
  content: '*';
  color: #FF0000;
  margin-right: 4rpx;
}

.camera-icon {
  width: 446rpx;
  height: 298rpx;
}

.preview-image {
  width: 100%;
  height: 100%;
  border-radius: 20rpx;
}

/* 识别状态样式 */
.recognize-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.6);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  border-radius: 20rpx;
}

.recognize-loading {
  width: 60rpx;
  height: 60rpx;
  border: 4rpx solid #fff;
  border-top: 4rpx solid #E8101E;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 16rpx;
}

.recognize-text {
  color: #fff;
  font-size: 24rpx;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.picker-content {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  flex: 1;
}

.picker-content text {
  margin-right: 19rpx;
}

.arrow-right {
  width: 14rpx;
  height: 26rpx;
  margin-left: 16rpx;
}

.placeholder {
  color: #999999;
  font-size: 28rpx;
}

.picker-value {
  font-size: 28rpx;
  color: #333333;
}

.input {
  flex: 1;
  font-size: 28rpx;
  color: #333333;
  text-align: right;
}

.textarea {
  margin-top: 15rpx;
  height: 165rpx;
  width: 605rpx;
  font-size: 28rpx;
  color: #333333;
  line-height: 1.5;
  background: #F8F9FD;
  border-radius: 20rpx;
  padding: 20rpx 24rpx;
}

.radio-group {
  display: flex;
  margin-top: 24rpx;
  width: 100%;
}

.radio-item {
  display: flex;
  align-items: center;
  margin-right: 130rpx;
}

.radio {
  width: 30rpx;
  height: 30rpx;
  border: 2rpx solid #DDDDDD;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16rpx;
}

.radio.checked {
  background-color: #E8101E;
  border-color: #E8101E;
}

.radio-icon-image {
  width: 32rpx;
  height: 32rpx;
}

.radio-label {
  font-size: 28rpx;
  color: #333333;
}

.date-range-container {
  padding: 24rpx;
  display: flex;
  justify-content: space-between;
}

.date-item {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.date-item:first-child {
  margin-right: 24rpx;
}

.date-label {
  font-size: 28rpx;
  color: #333333;
  margin-bottom: 16rpx;
  font-weight: 500;
  margin-left: 8rpx;
}

.date-picker-box {
  display: flex;
  align-items: center;
  justify-content: space-between;
  border: 2rpx solid #E9E9E9;
  border-radius: 10rpx;
  padding: 12rpx 19rpx;
  background-color: transparent;
}

.date-picker-box.disabled {
  border: 2rpx solid #F3F3F3;
}

.date-picker-box.disabled .date-value,
.date-picker-box.disabled .placeholder {
  color: #CCCCCC;
}

/* 日期值文本 - 添加弹性布局 */
.date-picker-box text {
  flex: 1;
  text-align: left;
  min-width: 0; 
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.date-value {
  font-size: 28rpx;
  color: #333;
}

.date-arrow {
  width: 35rpx;
  height: 33rpx;
}

.upload-label {
  font-size: 28rpx;
  color: #999;
  line-height: 40rpx;
  margin-top: 24rpx;
}

.date-divider {
  width: 2rpx;
  height: 30rpx;
  background-color: #E9E9E9;
  margin: 0 15rpx;
}

.date-picker-box.disabled .date-divider {
  background-color: #F3F3F3;
}

/* 弹窗样式 */
.popup {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 999;
  visibility: hidden;
  opacity: 0;
  transition: all 0.3s ease;
}

.popup.show {
  visibility: visible;
  opacity: 1;
}

.popup-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
}

.popup-content {
  position: relative;
  background-color: #FFFFFF;
  border-radius: 24rpx 24rpx 0 0;
  padding: 32rpx;
  transform: translateY(100%);
  transition: transform 0.3s ease;
  max-height: 70vh;
}

.popup.show .popup-content {
  transform: translateY(0);
}

.popup-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20rpx;
}

.popup-title {
  font-size: 32rpx;
  color: #333333;
  font-weight: 500;
}

.popup-close {
  font-size: 40rpx;
  color: #999999;
  padding: 16rpx;
}

.region-body {
  height: 400rpx;
}

.picker-scroll {
  height: 400rpx;
}

.picker-item {
  height: 68rpx;
  line-height: 68rpx;
  text-align: center;
  font-size: 28rpx;
}

.cancel-text {
  font-size: 32rpx;
  color: #666666;
}

.confirm-text {
  font-size: 32rpx;
  color: #E8101E;
  font-weight: 500;
}

.title {
  font-size: 32rpx;
  color: #333;
  font-weight: 500;
}

.popup-footer {
  display: flex;
  margin-top: 32rpx;
}

.popup-btn {
  flex: 1;
  height: 88rpx;
  border-radius: 44rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 16rpx;
}

.popup-btn.cancel {
  background-color: #F5F5F5;
}

.popup-btn.confirm {
  background: linear-gradient(180deg, #f52540 0%, #e8101e 100%);
}

.popup-btn .btn-text {
  font-size: 32rpx;
  font-weight: 500;
}

.popup-btn.cancel .btn-text {
  color: #666666;
}

.popup-btn.confirm .btn-text {
  color: #FFFFFF;
}

/* 提示弹窗样式 */
.tip-popup {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 1000;
  display: flex;
  align-items: center;
  justify-content: center;
  visibility: hidden;
  opacity: 0;
  transition: all 0.3s ease;
}

.tip-popup.show {
  visibility: visible;
  opacity: 1;
}

.tip-popup-mask {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
}

.tip-popup-content {
  position: relative;
  width: 620rpx;
  height: 810rpx;
}

.tip-popup-bg {
  width: 620rpx;
  height: 810rpx;
  position: absolute;
  top: 0;
  left: 0;
}

.tip-popup-body {
  position: relative;
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 80rpx 20rpx 40rpx 0rpx;
  box-sizing: border-box;
}

.tip-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
  text-align: center;
  margin-top: 107rpx;
  margin-bottom: 37rpx;
}

.tip-image-container {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 60rpx;
}

.tip-image {
  width: 672rpx;
  height: 327rpx;
  margin-right: 20rpx; 
}

.tip-buttons {
  display: flex;
  justify-content: space-between;
  padding: 0 38rpx;
}

.tip-btn {
  width: 250rpx;
  height: 80rpx;
  border-radius: 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 32rpx;
  font-weight: 500;
}

.tip-btn.cancel {
  border: #E8101E 2rpx solid;
  background-color: transparent;
  color: #e8101e;
}

.tip-btn.confirm {
  background: linear-gradient(180deg, #f52540 0%, #e8101e 100%);
  color: #FFFFFF;
}

.tip-btn .btn-text {
  color: inherit;
}
</style>