<template>
  <view class="personal-info-page">
    <!-- 个人资料部分 -->
    <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="formData.head_photo" :src="formData.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('id_card_front')">
                <view class="upload-camera idcard-front">
                  <image v-if="formData.id_card_front" :src="formData.id_card_front" 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 v-if="isRecognizing && recognizeType === 'id_card_front'" class="recognize-overlay">
                    <view class="recognize-loading"></view>
                    <text class="recognize-text">识别中...</text>
                  </view> -->
                </view>
              </view>
              <text class="upload-label required">请上传身份证正面（人像面）</text>
            </view>
            
            <!-- 身份证反面 -->
            <view class="idcard-upload-vertical-item">
              <view class="upload-box" @click="chooseImage('id_card_back')">
                <view class="upload-camera idcard-back">
                  <image v-if="formData.id_card_back" :src="formData.id_card_back" 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 v-if="isRecognizing && recognizeType === 'id_card_back'" class="recognize-overlay">
                    <view class="recognize-loading"></view>
                    <text class="recognize-text">识别中...</text>
                  </view> -->
                </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="formData.real_name" placeholder="请输入真实姓名" 
               placeholder-class="placeholder" class="input" 
               @input="saveFormDataToLocalDebounce" />
      </view>

      <!-- 联系方式 -->
      <view class="form-item-one box-cont">
        <text class="label required">联系方式</text>
        <input type="number" v-model="formData.phone" placeholder="请输入联系方式" 
               placeholder-class="placeholder" class="input" 
               @input="saveFormDataToLocalDebounce" />
      </view>

      <!-- 备用联系方式 -->
      <view class="form-item-one box-cont">
        <text class="label required">备用联系方式</text>
        <input type="number" v-model="formData.backup_phone" placeholder="请输入备用联系方式" 
               placeholder-class="placeholder" class="input" 
               @input="saveFormDataToLocalDebounce" />
      </view>

      <!-- 身份证号 -->
      <view class="form-item-one box-cont">
        <text class="label required">身份证号</text>
        <input type="idcard" v-model="formData.id_card" placeholder="请输入证件号码" 
               placeholder-class="placeholder" class="input" 
               @input="saveFormDataToLocalDebounce" />
      </view>

      <!-- 身份证有效期 -->
      <view class="form-item box-cont">
        <text class="label required">身份证有效期至：</text>
        <view class="radio-group">
          <view class="radio-item" @click="setIdCardValidType('permanent')">
            <view class="radio" :class="{ checked: formData.id_card_valid_type === 'permanent' }">
              <image v-if="formData.id_card_valid_type === 'permanent'" 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="setIdCardValidType('date')">
            <view class="radio" :class="{ checked: formData.id_card_valid_type === 'date' }">
              <image v-if="formData.id_card_valid_type === 'date'" 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="openDatePicker('id_card_start_date')">
              <text :class="formData.id_card_start_date ? 'date-value' : 'placeholder'">
                {{formatDateForDisplay(formData.id_card_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: formData.id_card_valid_type === 'permanent' }" 
                  @click="formData.id_card_valid_type !== 'permanent' && openDatePicker('id_card_end_date')">
              <text :class="formData.id_card_end_date ? 'date-value' : 'placeholder'">
                {{formatDateForDisplay(formData.id_card_end_date) || '选择日期'}}
              </text>
              <view class="date-divider"></view>
              <image :src="formData.id_card_valid_type === 'permanent' ? 
                'https://mrrplus.oss-cn-beijing.aliyuncs.com/photo/system/bb9a757f-a36c-46bb-a59f-2caddac5365b' : 
                'https://mrrplus.oss-cn-beijing.aliyuncs.com/photo/system/ce52b49f-2261-49ca-96ed-e9ad47049649'" 
                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="formData.introduction" placeholder="请输入个人简介、工作的经验等介绍" 
                class="textarea" maxlength="500" 
                @input="saveFormDataToLocalDebounce" />
        </view>
      </view>
    </view>

    <!-- 所在地 -->
    <view class="section">  
      <view class="form-item-two box-cont" @click="showLocationPopup">
        <text class="label required">所在地</text>
        <view class="picker-content">
          <text :class="formData.region ? 'picker-value' : 'placeholder'">
            {{formData.region || '请选择'}}
          </text>
          <image 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="getAddressInfo">
        <text class="label required">详细地址</text>
        <view class="picker-content">
          <text :class="formData.detail_address ? 'picker-value' : 'placeholder'">
            {{formData.detail_address || '请选择'}}
          </text>
          <image 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="showServicePopup">
        <text class="label required">服务技能（多选）</text>
        <view class="picker-content">
          <text :class="formData.service_skills.length > 0 ? 'picker-value' : 'placeholder'">
            {{selectedServicesText || '请选择'}}
          </text>
          <image 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="showRegionPopup">
        <text class="label required">服务区域</text>
        <view class="picker-content">
          <text :class="serviceAreaDisplayText ? 'picker-value' : 'placeholder'">
            {{serviceAreaDisplayText || '请选择'}}
          </text>
          <image 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="openTimePicker">
        <text class="label required">服务时间</text>
        <view class="picker-content">
          <text :class="formData.service_time ? 'picker-value' : 'placeholder'">
            {{formData.service_time || '请选择'}}
          </text>
          <image 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="openMessageMethodPicker">
        <text class="label required">获取消息方式</text>
        <view class="picker-content">
          <text :class="formData.get_message_method ? 'picker-value' : 'placeholder'">
            {{messageMethodText || '请选择'}}
          </text>
          <image 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-one-yqr box-cont invite-code-container">
      <view class="invite-code-top">
        <view class="label-wrapper">
          <text class="label required">邀请码</text>
        </view>
        <input type="text" v-model="formData.invite_code" placeholder="请输入邀请码" 
              placeholder-class="placeholder" class="input" 
              @input="handleInviteCodeInput" />
      </view>
      
      <!-- 分割线 -->
      <view class="divider"></view>
      
      <!-- 邀请人信息 -->
      <view class="invite-info-container">
        <!-- 默认提示 -->
        <text v-if="!formData.invite_code" class="invite-tip">
          请填写邀请人的邀请码，若没有邀请人请填写13131313
        </text>
        
        <!-- 验证中 -->
        <view v-else-if="inviteCodeValidating" class="invite-validating">
          <text>验证中...</text>
        </view>
        
        <!-- 验证失败 -->
        <view v-else-if="inviteCodeError" class="invite-error" :class="{ 'shake-animation': shakeInviteError }">
          <text>邀请码无效</text>
        </view>
        
        <!-- 特殊邀请码13131313 -->
        <view v-else-if="formData.invite_code === '13131313' && !inviterInfo" class="invite-tip">
          请填写邀请人的邀请码，若没有邀请人请填写13131313
        </view>
        
        <!-- 显示邀请人信息 -->
        <view v-else-if="inviterInfo" class="inviter-info">
          <text class="inviter-label">邀请人：</text>
          <text class="inviter-name">{{ inviterInfo.name || inviterInfo.nick_name }}</text>
          <text class="inviter-divider">/</text>
          <text class="inviter-phone">{{ inviterInfo.account }}</text>
        </view>
        
        <!-- 其他情况（接口返回成功但没有认证铁军的邀请码） -->
        <view v-else class="invite-error" :class="{ 'shake-animation': shakeInviteError }">
            <text>邀请码无效</text>
        </view>
      </view>
    </view>


      <!-- 专业经验 -->
      <view class="form-item-two box-cont" @click="openExperiencePicker">
        <text class="label required">专业经验</text>
        <view class="picker-content">
          <text :class="formData.professional_experience ? 'picker-value' : 'placeholder'">
            {{experienceText || '请选择'}}
          </text>
          <image 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="openWorkStatusPicker">
        <text class="label required">目前工作状态</text>
        <view class="picker-content">
          <text :class="formData.work_status ? 'picker-value' : 'placeholder'">
            {{workStatusText || '请选择'}}
          </text>
          <image 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: showServicePopupFlag }">
      <view class="popup-mask" @click="hideServicePopup"></view>
      <view class="popup-content">
        <view class="popup-header">
          <text class="popup-title">选择服务技能</text>
          <text class="popup-close" @click="hideServicePopup">×</text>
        </view>
        <view class="popup-body">
          <view class="checkbox-list">
            <view class="checkbox-item" v-for="(item, index) in serviceList" :key="index"
                  @click="toggleServiceSelect(index)">
              <view class="checkbox" :class="{ checked: item.checked }">
                <image v-if="item.checked" class="check-icon" src="https://mrrplus.oss-cn-beijing.aliyuncs.com/photo/system/66325904-4603-48fd-b03b-90c684af96e9" mode="aspectFit"></image>
              </view>
              <text class="checkbox-label">{{item.title}}</text>
            </view>
          </view>
        </view>
        <view class="popup-footer">
          <view class="popup-btn cancel" @click="hideServicePopup">
            <text class="btn-text">取消</text>
          </view>
          <view class="popup-btn confirm" @click="confirmServiceSelect">
            <text class="btn-text">确定</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 服务时间选择器 -->
    <view class="popup" :class="{ show: showTimePicker }">
      <view class="popup-mask" @click="hideTimePopup"></view>
      <view class="popup-content">
        <view class="popup-header">
          <text class="cancel-text" @click="hideTimePopup">取消</text>
          <text class="title">选择服务时间</text>
          <text class="confirm-text" @click="confirmTime">确定</text>
        </view>
        <view class="time-range">
          <view class="time-block" :class="{ active: timeType === 'start' }"
                @click="switchTimeType('start')">
            <text class="time-value">{{formatTime(startTime)}}</text>
            <text class="time-label">开始时间</text>
          </view>
          <text class="time-separator">至</text>
          <view class="time-block" :class="{ active: timeType === 'end' }"
                @click="switchTimeType('end')">
            <text class="time-value">{{formatTime(endTime)}}</text>
            <text class="time-label">结束时间</text>
          </view>
        </view>
        <view class="region-body">
          <picker-view :value="pickerValue" @change="handleTimeChange" class="picker-scroll"
                      :indicator-style="indicatorStyle">
            <picker-view-column>
              <view class="picker-item" v-for="(hour, index) in hours" :key="index">
                {{hour}}
              </view>
            </picker-view-column>
            <picker-view-column>
              <view class="picker-item" v-for="(minute, index) in minutes" :key="index">
                {{minute}}
              </view>
            </picker-view-column>
            <picker-view-column>
              <view class="picker-item">-</view>
            </picker-view-column>
            <picker-view-column>
              <view class="picker-item" v-for="(hour, index) in hours" :key="index">
                {{hour}}
              </view>
            </picker-view-column>
            <picker-view-column>
              <view class="picker-item" v-for="(minute, index) in minutes" :key="index">
                {{minute}}
              </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="popup" :class="{ show: showRegionPopupFlag }">
      <view class="popup-mask" @click="hideRegionPopup"></view>
      <view class="popup-content region-popup">
        <view class="popup-header">
          <text class="popup-title">选择服务区域</text>
          <text class="popup-close" @click="hideRegionPopup">×</text>
        </view>
        <view class="region-tabs">
          <view 
            v-for="(tab, index) in regionTabs" 
            :key="index"
            class="region-tab"
            :class="{ active: currentTab === index }"
            @click="switchTab(index)"
          >
            {{tab}}
          </view>
        </view>
        <view class="region-body">
          <scroll-view 
            scroll-y 
            class="region-scroll"
            v-if="currentTab === 0"
          >
            <view 
              class="region-item"
              v-for="(province, index) in ChinaCitys"
              :key="index"
              @click="selectProvince(province,index)"
            >
              <text>{{province.province}}</text>
              <image class="arrow-right" src="https://mrrplus.oss-cn-beijing.aliyuncs.com/photo/system/dccc4513-377c-4bfa-9fd2-a5cfdb9798f3" mode="aspectFit"></image>
            </view>
          </scroll-view>
          
          <scroll-view 
            scroll-y 
            class="region-scroll"
            v-if="currentTab === 1"
          >
            <view 
              class="region-item"
              v-for="(city, index) in cityList"
              :key="index"
              @click="selectCity(city,index)"
            >
              <text>{{city.city}}</text>
              <image class="arrow-right" src="https://mrrplus.oss-cn-beijing.aliyuncs.com/photo/system/dccc4513-377c-4bfa-9fd2-a5cfdb9798f3" mode="aspectFit"></image>
            </view>
          </scroll-view>
          
          <scroll-view 
            scroll-y 
            class="region-scroll"
            v-if="currentTab === 2"
          >
            <view 
              class="region-item checkbox-item"
              v-for="(district, index) in districtList"
              :key="index"
              @click="toggleDistrictSelect(index)"
            >
              <view class="checkbox" :class="{ checked: district.checked }">
                <image v-if="district.checked" class="check-icon" src="https://mrrplus.oss-cn-beijing.aliyuncs.com/photo/system/66325904-4603-48fd-b03b-90c684af96e9" mode="aspectFit"></image>
              </view>
              <text class="checkbox-label">{{district.area}}</text>
            </view>
          </scroll-view>
        </view>
        <view class="popup-footer">
          <view class="popup-btn cancel" @click="hideRegionPopup">
            <text class="btn-text">取消</text>
          </view>
          <view class="popup-btn confirm" @click="confirmRegionSelect">
            <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>
</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 { debounce } from '@/utils/debounce.js';
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 || [];
      
      // 从本地存储加载数据
      let loadedFormData = null;
      let loadedInviteState = null;
      
      try {
        loadedFormData = uni.getStorageSync('personal_info_form_data');
        loadedInviteState = uni.getStorageSync('personal_invite_state');
      } catch (e) {
        console.log('读取本地存储失败:', e);
      }
      
      // 确保 service_area 是数组格式
      if (loadedFormData && loadedFormData.service_area && !Array.isArray(loadedFormData.service_area)) {
        loadedFormData.service_area = [loadedFormData.service_area];
      }
      
      // 初始化邀请码状态
      const initialInviteState = loadedInviteState || {};
      
      return {
        userId: null,
        identity: null,
        formData: loadedFormData || {
          head_photo: '',
          real_name: '',
          phone: '',
          backup_phone: '',
          id_card: '',
          id_card_valid_type: '',
          id_card_start_date: '',
          id_card_end_date: '',
          id_card_front: '',
          id_card_back: '',
          id_card_handheld: '',
          detail_address: '',
          introduction: '',
          region: '',
          dependency_code: '',
          dependency_province: '',
          dependency_city: '',
          longitude: '',
          latitude: '',
          service_skills: [],
          service_area: [],
          service_time: '',
          get_message_method: '',
          invite_code: '',
          professional_experience: '',
          work_status: ''
        },
        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,

        // 服务技能相关
        showServicePopupFlag: false,
        serviceList: [],
        selectedServicesText: '',

        // 服务时间相关
        showTimePicker: false,
        showDatePickerFlag: false,
        
        pickerValue: [8, 0, 0, 18, 0],
        hours: Array.from({ length: 24 }, (_, i) => i < 10 ? `0${i}` : `${i}`),
        minutes: Array.from({ length: 60 }, (_, i) => i < 10 ? `0${i}` : `${i}`),
        timeType: 'start',

        // 其他选择器文本
        messageMethodText: '',
        experienceText: '',
        workStatusText: '',
        
        // 提示弹窗
        showTipPopupFlag: false,
        tipTitle:'',
        tipImage: '',
        currentTipType: '',
        
        // 图片预加载
        tipImagesPreloaded: false,
        
        // 服务区域选择器相关数据
        showRegionPopupFlag: false,
        currentTab: 0,
        regionTabs: ['省', '市', '区'],
        cityList: [],
        districtList: [],
        selectedProvince: null,
        selectedCity: null,
        currentSelectedCity: '',
        
        // 邀请码相关字段 直接从本地存储初始化
        inviteCodeValidating: false,
        inviteCodeError: initialInviteState.inviteCodeError || false,
        inviterInfo: initialInviteState.inviterInfo || null,
        currentValidatingCode: initialInviteState.currentValidatingCode || '',
        shakeInviteError: false,

        // 服务区域显示文本
        serviceAreaDisplayText: '',
        
        // 识别状态
        isRecognizing: false,
        recognizeType: '', // 'id_card_front', 'id_card_back'

        inviteValidationTimer: null, // 邀请码验证定时器
      }
    },
  
  computed: {
    startTime() {
      return {
        hour: this.hours[this.pickerValue[0]],
        minute: this.minutes[this.pickerValue[1]]
      }
    },
    endTime() {
      return {
        hour: this.hours[this.pickerValue[3]],
        minute: this.minutes[this.pickerValue[4]]
      }
    },
  },
  
  watch: {
    'formData.real_name'(newVal) {
      this.saveFormDataToLocalDebounce();
    },
    'formData.phone'(newVal) {
      this.saveFormDataToLocalDebounce();
    },
    'formData.backup_phone'(newVal) {
      this.saveFormDataToLocalDebounce();
    },
    'formData.id_card'(newVal) {
      this.saveFormDataToLocalDebounce();
    },
    'formData.detail_address'(newVal) {
      this.saveFormDataToLocalDebounce();
    },
    'formData.introduction'(newVal) {
      this.saveFormDataToLocalDebounce();
    },
    // 移除对 invite_code 的 watch，改用输入事件处理
    'formData.head_photo'(newVal) {
      this.saveFormDataToLocalDebounce();
    },
    'formData.id_card_front'(newVal) {
      this.saveFormDataToLocalDebounce();
    },
    'formData.id_card_back'(newVal) {
      this.saveFormDataToLocalDebounce();
    },
    'formData.id_card_handheld'(newVal) {
      this.saveFormDataToLocalDebounce();
    },
    'formData.service_area': {
      handler(newVal) {
        this.saveFormDataToLocalDebounce();
      },
      deep: true
    }
  },
  
  async onLoad() {
    console.log('页面开始加载...');
    
    this.identity = getApp().globalData.artisanType;
    console.log('身份类型:', this.identity);

    // 预加载提示弹窗图片
    this.preloadTipImages();
    
    await this.getUserInfo();
    console.log('用户信息获取完成');

    this.setupAddressListener();
    
    console.log('地区数据加载完成:', this.ChinaCitys.length);

    // 确保正确监听手艺人地址选择事件
    uni.$on('address-selected-for-syr', (addressData) => {
      console.log('收到手艺人地址选择事件:', addressData);
      this.handleAddressSelected(addressData);
    });
    
    // 预加载服务技能数据
    await this.loadServiceSkills();
    console.log('服务技能数据加载完成:', this.serviceList.length);
    
    // 预填用户手机号
    const userInfo = getApp().globalData.userInfo || uni.getStorageSync('userInfo');
    if (userInfo && userInfo.account) {
      this.formData.phone = userInfo.account;
      console.log('预填手机号:', this.formData.phone);
    }
    
    // 获取定位
    await this.getLocation();
    console.log('定位获取完成');

    // 检查全局状态数据
    this.checkGlobalData();

    // 加载本地数据后更新显示文本
    this.updateDisplayTextsImmediately();
    
    console.log('页面加载完成');
  },
  
  onShow() {
    // 检查地址数据
    this.checkAddressData();
    
    // 从本地存储重新加载表单数据
    const localData = this.loadFormDataFromLocal();
    if (localData) {
      // 先保存原有的服务技能列表选中状态，防止被覆盖
      const serviceSkillsBefore = this.formData.service_skills;
      
      // 合并数据 不覆盖邀请码相关字段版
      const { invite_code, ...otherFormData } = localData;
      
      // 只更新非邀请码的表单字段
      Object.keys(otherFormData).forEach(key => {
        if (this.formData[key] !== undefined) {
          this.formData[key] = otherFormData[key];
        }
      });
      
      // 如果本地存储中有邀请码，更新表单的邀请码字段
      if (invite_code !== undefined) {
        this.formData.invite_code = invite_code;
      }
      
      // 立即更新显示文本
      this.updateDisplayTextsImmediately();
      
      // 恢复服务技能的选中状态（如果 serviceList 已加载）
      if (this.serviceList.length > 0) {
        this.restoreServiceSkillsSelection();
      } else {
        // 如果还没加载，先记录下来
        this.formData.service_skills = serviceSkillsBefore || localData.service_skills;
      }
    }

    // 重新从本地存储加载邀请码验证状态
    this.loadInviteStateFromLocal();
    
    // 检查全局状态数据
    this.checkGlobalData();
  },
  
  onHide() {
    // 页面隐藏时保存数据
    this.saveFormDataToLocal();
  },
  
  onUnload() {
    uni.$off('address-selected-for-syr');
    // 页面卸载时保存数据
    this.saveFormDataToLocal();
  },
  
  mounted() {
    
    // 确保有 editAddress 方法
    if (!this.editAddress) {
      console.log('添加 editAddress 方法');
      this.editAddress = this.handleAddressSelected.bind(this);
    }

    // 初始化显示文本
    this.updateDisplayTextsImmediately();
  },
  
  methods: {
    // 从本地存储加载邀请码验证状态
    loadInviteStateFromLocal() {
      try {
        const inviteState = uni.getStorageSync('personal_invite_state');
        if (inviteState) {
          console.log('加载邀请码验证状态:', inviteState);
          
          // 恢复邀请码验证状态
          this.inviterInfo = inviteState.inviterInfo || null;
          this.inviteCodeError = inviteState.inviteCodeError || false;
          this.currentValidatingCode = inviteState.currentValidatingCode || '';
          
          // 特殊处理：如果当前邀请码是13131313，确保状态正确
          if (this.formData.invite_code === '13131313') {
            console.log('检测到特殊邀请码13131313，重置验证状态');
            this.inviteCodeError = false;
            this.inviterInfo = null;
            this.currentValidatingCode = '13131313';
          }
          
          // 如果正在验证的邀请码与当前表单中的一致，保持验证状态
          if (this.currentValidatingCode === this.formData.invite_code) {
            // 状态已恢复，无需额外操作
          } else {
            // 如果不一致，重新验证
            if (this.formData.invite_code && this.formData.invite_code.trim() !== '') {
              console.log('邀请码不一致，重新验证:', this.formData.invite_code);
              this.handleInviteCodeInput({ detail: { value: this.formData.invite_code } });
            }
          }
        } else {
          // 如果没有保存的状态，重置为初始状态
          this.resetInviteCodeState();
        }
      } catch (e) {
        console.log('加载邀请码验证状态失败:', e);
        this.resetInviteCodeState();
      }
    },

    // 恢复服务技能选择状态
    restoreServiceSkillsSelection() {
      if (this.serviceList.length > 0 && this.formData.service_skills) {
        this.serviceList.forEach(item => {
          item.checked = this.formData.service_skills.includes(item.id);
        });
        // 更新显示文本
        this.updateSelectedServicesText();
      }
    },
    //邀请码相关方法

    // 新增方法：重置邀请码状态
    resetInviteCodeState() {
      this.inviteCodeValidating = false;
      this.inviteCodeError = false;
      this.inviterInfo = null;
      this.currentValidatingCode = '';
      this.shakeInviteError = false;
    },
    
    // 触发邀请码错误抖动效果
    triggerInviteErrorShake() {
      // 触发抖动效果
      this.shakeInviteError = true;
      
      // 滚动到邀请码容器位置
      this.$nextTick(() => {
        // 使用uni.createSelectorQuery获取邀请码容器的位置
        const query = uni.createSelectorQuery().in(this);
        query.select('.invite-code-container').boundingClientRect((rect) => {
          if (rect) {
            // 获取当前窗口高度
            const windowHeight = uni.getSystemInfoSync().windowHeight;
            
            // 判断邀请码容器是否已经在可视区域内
            // 计算容器在屏幕中的位置比例（0-1之间）
            const containerTopRatio = rect.top / windowHeight;
            const containerBottomRatio = (rect.top + rect.height) / windowHeight;
            
            // 如果容器已经在屏幕中上部（顶部在屏幕中间以上），就不需要滚动
            // 或者容器整体都在屏幕内，也不需要滚动
            if (containerTopRatio >= 0 && containerTopRatio < 0.7 && 
                containerBottomRatio <= 1) {
              console.log('邀请码容器已在可视区域内，不需要滚动');
              return;
            }
            
            // 滚动到邀请码容器位置，减去一些偏移量让用户体验更好
            uni.pageScrollTo({
              scrollTop: rect.top - 50,
              duration: 300
            });
          }
        }).exec();
      });

      // 0.5秒后重置抖动状态
      setTimeout(() => {
        this.shakeInviteError = false;
      }, 500);
    },
    
    // 处理邀请码输入
    handleInviteCodeInput(e) {
      const code = e.detail ? e.detail.value : this.formData.invite_code;
      
      console.log('邀请码输入:', code);
      
      // 立即重置状态
      this.inviteCodeValidating = false;
      this.inviteCodeError = false;
      this.inviterInfo = null;
      
      // 如果邀请码为空，不进行验证
      if (!code || code.trim() === '') {
        this.formData.invite_code = '';
        this.saveFormDataToLocalDebounce();
        // 保存空状态
        this.saveInviteStateToLocal();
        return;
      }
      
      this.formData.invite_code = code;
      this.saveFormDataToLocalDebounce();
      
      // 【关键修复】如果是13131313，立即通过验证并取消任何正在进行的验证
      if (code === '13131313') {
        console.log('检测到特殊邀请码13131313，立即通过');
        
        // 清除任何可能的定时器
        if (this.inviteValidationTimer) {
          clearTimeout(this.inviteValidationTimer);
          this.inviteValidationTimer = null;
        }
        
        // 立即更新状态
        this.inviteCodeValidating = false;
        this.inviteCodeError = false;
        this.inviterInfo = null;
        this.currentValidatingCode = code;
        
        // 特殊邀请码也需要保存状态
        const inviteState = {
          inviterInfo: null,
          inviteCodeError: false,
          currentValidatingCode: code
        };
        uni.setStorageSync('personal_invite_state', inviteState);
        
        // 强制更新视图
        this.$forceUpdate();
        return;
      }
      
      // 记录当前正在验证的邀请码
      this.currentValidatingCode = code;
      
      // 立即保存状态（验证中）
      this.saveInviteStateToLocal();
      
      // 【关键修复】使用更明确的防抖机制
      // 清除之前的定时器
      if (this.inviteValidationTimer) {
        clearTimeout(this.inviteValidationTimer);
        this.inviteValidationTimer = null;
      }
      
      // 设置新的定时器
      this.inviteValidationTimer = setTimeout(() => {
        // 检查邀请码是否变化
        if (this.formData.invite_code !== this.currentValidatingCode) {
          console.log('邀请码已变化，取消验证');
          return;
        }
        
        // 再次检查是否是13131313（双重检查）
        if (this.formData.invite_code === '13131313') {
          console.log('双重检查：检测到特殊邀请码13131313');
          this.inviteCodeValidating = false;
          this.inviteCodeError = false;
          this.inviterInfo = null;
          this.currentValidatingCode = '13131313';
          
          const inviteState = {
            inviterInfo: null,
            inviteCodeError: false,
            currentValidatingCode: '13131313'
          };
          uni.setStorageSync('personal_invite_state', inviteState);
          return;
        }
        
        console.log('开始验证邀请码:', this.formData.invite_code);
        this.validateInviteCode(this.formData.invite_code);
        
        // 清理定时器
        this.inviteValidationTimer = null;
      }, 600); // 适当增加延迟时间
    },
    
    // 验证邀请码
    async validateInviteCode(code) {
      console.log('开始验证邀请码:', code);

      // 特殊邀请码13131313直接通过
      if (code === '13131313') {
        console.log('特殊邀请码13131313，直接通过');
        this.inviteCodeValidating = false;
        this.inviteCodeError = false;
        this.inviterInfo = null;
        this.currentValidatingCode = code;
        // 特殊邀请码也需要保存状态
        const inviteState = {
          inviterInfo: null,
          inviteCodeError: false,
          currentValidatingCode: code
        };
        uni.setStorageSync('personal_invite_state', inviteState);

        // 强制更新视图
        this.$forceUpdate();
        return;
      }
      
      // 如果邀请码为空
      if (!code || code.trim() === '') {
        this.inviteCodeValidating = false;
        this.inviteCodeError = false;
        this.inviterInfo = null;
        this.currentValidatingCode = '';
        const inviteState = {
          inviterInfo: null,
          inviteCodeError: false,
          currentValidatingCode: ''
        };
        uni.setStorageSync('personal_invite_state', inviteState);
        return;
      }
      
      // 设置验证中状态
      this.inviteCodeValidating = true;
      this.inviteCodeError = false;
      this.inviterInfo = null;
      this.currentValidatingCode = code;
      
      try {
        // 调用接口验证邀请码
        const response = await request.post('/user/user/getInvite', {
          invite_code: code
        });
        
        console.log('邀请码验证响应:', response);
        
        // 验证完成
        this.inviteCodeValidating = false;
        
        if (response && response.code === 200 && response.data) {
          const userData = response.data;

          //检查返回的数据是否有效
          if (userData.account) {
              // 邀请码有效，保存邀请人信息
              this.inviterInfo = userData;
              this.inviteCodeError = false;
              console.log('邀请码验证通过，邀请人:', userData);
          } else {
              // 接口返回数据但没有account字段，说明不是有效邀请人
              console.log('接口返回数据无效，没有account字段:', userData);
              this.inviterInfo = null;
              this.inviteCodeError = true;
          }
        } else {
          // 接口返回错误或数据为空
          console.log('接口返回错误:', response?.msg || '未知错误');
          this.inviterInfo = null;
          this.inviteCodeError = true;
        }
      } catch (error) {
        console.error('验证邀请码失败:', error);
        this.inviteCodeValidating = false;
        this.inviteCodeError = true;
        this.inviterInfo = null;
      } finally {
        // 无论成功失败都保存状态
        const inviteState = {
          inviterInfo: this.inviterInfo,
          inviteCodeError: this.inviteCodeError,
          currentValidatingCode: this.currentValidatingCode
        };
        uni.setStorageSync('personal_invite_state', inviteState);
      }
    },

    // 新增方法：专门保存邀请码验证状态
    saveInviteStateToLocal() {
      try {
        const inviteState = {
          inviterInfo: this.inviterInfo,
          inviteCodeError: this.inviteCodeError,
          currentValidatingCode: this.currentValidatingCode || this.formData.invite_code || ''
        };
        uni.setStorageSync('personal_invite_state', inviteState);
        
        console.log('邀请码验证状态已保存:', {
          hasInviterInfo: !!this.inviterInfo,
          inviteCodeError: this.inviteCodeError,
          currentValidatingCode: this.currentValidatingCode
        });
      } catch (e) {
        console.log('保存邀请码验证状态失败:', e);
      }
    },

    // 立即更新所有显示文本
    updateDisplayTextsImmediately() {
      // 恢复服务技能显示文本
      this.updateSelectedServicesText();
      
      // 恢复获取消息方式的显示文本
      if (this.formData.get_message_method) {
        const methods = ['朋友圈', '抖音', '地推', '朋友介绍', '微博'];
        this.messageMethodText = methods[this.formData.get_message_method - 1] || '';
      }
      
      // 恢复专业经验的显示文本
      if (this.formData.professional_experience) {
        const experiences = ['实习', '1-3年', '3-5年', '5-10年', '10年以上'];
        this.experienceText = experiences[this.formData.professional_experience - 1] || '';
      }
      
      // 恢复工作状态的显示文本
      if (this.formData.work_status) {
        const statusList = ['在职', '离职', '自由职业', '在校学生', '其他'];
        this.workStatusText = statusList[this.formData.work_status - 1] || '';
      }
      
      // 恢复服务区域显示文本
      this.updateServiceAreaDisplayText();
    },

    // 更新服务区域显示文本
    updateServiceAreaDisplayText() {
      if (this.formData.service_area && this.formData.service_area.length > 0) {
        // 直接使用保存的区域字符串
        this.serviceAreaDisplayText = this.formData.service_area.join('、');
      } else {
        this.serviceAreaDisplayText = '';
      }
    },
    
    // 地址选择相关方法 
    // 添加 editAddress 方法
    editAddress(item) {
      console.log('接收到的地址数据:', item);
      this.handleAddressSelected(item);
    },
    
    // 处理地址选择结果
    async handleAddressSelected(addressData) {
      console.log('接收到的地址数据:', addressData);
      
      if (!addressData) {
        console.log('地址数据为空');
        return;
      }
      
      // 提取地址
      let address = '';
      if (addressData.name) {
        address = addressData.name;
      } else if (addressData.address) {
        address = addressData.address;
      }
      
      if (!address) {
        console.log('无法提取地址');
        return;
      }
      
      console.log('设置地址:', address);
      
      // 直接设置表单数据
      this.formData.detail_address = address;
      
      // 提取经纬度
      if (addressData.location) {
        const [longitude, latitude] = addressData.location.split(',');
        this.formData.longitude = longitude || '';
        this.formData.latitude = latitude || '';
      }

      // 如果地址数据中没有省市区信息，尝试通过逆地理编码获取
      if ((!addressData.pname || !addressData.cityname || !addressData.adname) && this.formData.longitude && this.formData.latitude) {
        try {
          console.log('开始逆地理编码，经纬度:', this.formData.longitude, this.formData.latitude);
          // 使用高德地图逆地理编码API
          const res = await uni.request({
            url: 'https://restapi.amap.com/v3/geocode/regeo',
            method: 'GET',
            data: {
              key: '30b7eb1a1b2f88edc085b9b3ee9a2188',
              location: `${this.formData.longitude},${this.formData.latitude}`
            }
          });
          console.log('逆地理编码结果:', res);
          if (res.data && res.data.regeocode) {
            const addressComponent = res.data.regeocode.addressComponent;
            addressData.pname = addressComponent.province;
            addressData.cityname = addressComponent.city || addressComponent.province; // 直辖市city为空，用province代替
            addressData.adname = addressComponent.district;
          }
        } catch (error) {
          console.error('逆地理编码失败:', error);
        }
      }

      // 更新所在地
      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);
        this.formData.region = locationParts.join('-');
        
        console.log('更新所在地为:', this.formData.region);
      }
      
      console.log('表单已更新:', {
        detail_address: this.formData.detail_address,
        region: this.formData.region,
        longitude: this.formData.longitude,
        latitude: this.formData.latitude
      });
      
      // 保存到本地存储
      this.saveFormDataToLocal();
      
      // 更新视图
      this.$forceUpdate();
      // uni.showToast({
      //   title: '地址已选择',
      //   icon: 'none'
      // });
    },

    
    // 获取详细地址
    getAddressInfo() {
      // 保存当前数据
      this.saveFormDataToLocalDebounce();
      
      // 清除旧数据
      this.clearOldAddressData();
      
      // 构建URL参数
      let params = 'source=syr_info'; // 手艺人来源标识
      
      // 如果有所在地，添加dependency参数
      if (this.formData.region) {
        // 将所在地作为dependency参数传递，格式为"省-市-区"
        const locationStr = encodeURIComponent(this.formData.region);
        params += `&dependency=${locationStr}`;
        
        // 如果有地区编码，也传递过去
        if (this.formData.dependency_code) {
          params += `&dependency_code=${this.formData.dependency_code}`;
        }
      }
      
      // 如果有已选择的地址坐标，也传递过去作为初始位置
      if (this.formData.longitude && this.formData.latitude) {
        params += `&longitude=${this.formData.longitude}&latitude=${this.formData.latitude}`;
      }
      
      console.log('跳转URL参数:', params);
      
      uni.navigateTo({
        url: `/pages/address/search?${params}`
      });
    },

    // 清理地址存储
    clearOldAddressData() {
      try {
        // 只清理存储，不清空当前表单数据
        uni.removeStorageSync('syr_selected_address');
        console.log('已清理手艺人地址存储数据');
      } catch (e) {
        console.error('清理地址数据失败:', e);
      }
    },

    // 处理地址选择结果 - 修改为从事件监听获取
    setupAddressListener() {
      // 监听地址选择事件
      uni.$on('address-selected-for-syr', (addressData) => {
        this.handleAddressSelected(addressData);
      });
    },

    // 检查地址数据
    checkAddressData() {
      try {
        // 先检查手艺人专用存储
        const syrAddress = uni.getStorageSync('syr_selected_address');
        if (syrAddress) {
          console.log('从手艺人专用存储获取地址:', syrAddress);
          this.handleAddressSelected(syrAddress);
          uni.removeStorageSync('syr_selected_address');
          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;
      }
    },

    
    // 从本地存储加载数据
    loadFormDataFromLocal() {
      try {
        const stored = uni.getStorageSync('personal_info_form_data');
        if (stored) {
          console.log('从本地存储加载个人信息数据:', stored);
          
          // 确保 service_area 是数组格式
          if (stored.service_area && !Array.isArray(stored.service_area)) {
            stored.service_area = [stored.service_area];
          }
          
          return stored;
        }
      } catch (e) {
        console.log('读取个人信息数据失败:', e);
      }
      return null;
    },
    
    // 保存数据到本地存储（带防抖）
    saveFormDataToLocalDebounce: debounce(function() {
      this.saveFormDataToLocal();
    }, 500),
    
    // 保存数据到本地存储
    saveFormDataToLocal() {
      try {
        // 首先保存表单数据
        uni.setStorageSync('personal_info_form_data', this.formData);
        console.log('个人信息表单数据已保存');
      } catch (e) {
        console.log('保存个人信息数据失败:', e);
      }
    },
    
    // 清空本地存储（在表单提交成功后调用）
    clearFormDataLocal() {
      try {
        uni.removeStorageSync('personal_info_form_data');
        console.log('已清空个人信息数据');
      } catch (e) {
        console.log('清空个人信息数据失败:', e);
      }
    },
    
    // 检查全局数据
    checkGlobalData() {
      if (getApp().globalData.personalInfoData) {
        // 如果全局有数据，合并到当前表单
        this.formData = { ...this.formData, ...getApp().globalData.personalInfoData };
        // 保存到本地存储
        this.saveFormDataToLocal();
        // 清空全局数据，避免重复使用
        // delete getApp().globalData.personalInfoData;
        getApp().globalData.qualificationData = null;
      }
    },
    
    // 更新已选择服务技能的显示文本
    updateSelectedServicesText() {
      if (this.formData.service_skills && this.formData.service_skills.length > 0 && this.serviceList.length > 0) {
        // 将保存的ID与serviceList匹配
        const selectedServices = this.serviceList
          .filter(item => this.formData.service_skills.includes(item.id))
          .map(item => {
            // 设置选中状态
            item.checked = true;
            return item.title;
          });
        
        this.selectedServicesText = selectedServices.join('、');
      }
    },

    // 获取用户信息
    getUserInfo() {
      return new Promise((resolve, reject) => {
        request.post('/user/getuser', { type: 1 }).then(result => {
          if (result.state === 1) {
            this.userId = result.data.id;
            console.log('用户ID获取成功:', this.userId);
            resolve(this.userId);
          } else {
            console.error('获取用户信息失败:', result.msg);
            reject(result.msg);
          }
        }).catch(error => {
          console.error('获取用户信息接口错误:', error);
          reject(error);
        });
      });
    },

    getFormData() {
      let idcard_expiry_type = 0;
      if (this.formData.id_card_valid_type === 'permanent') {
        idcard_expiry_type = 1;
      } else if (this.formData.id_card_valid_type === 'date') {
        idcard_expiry_type = 2;
      }
      
      let idcard_expiry = '';
      if (this.formData.id_card_start_date) {
        const startDate = this.formatDateForBackend(this.formData.id_card_start_date);
        if (this.formData.id_card_valid_type === 'permanent') {
          idcard_expiry = `${startDate} ——        `;
        } else if (this.formData.id_card_end_date) {
          const endDate = this.formatDateForBackend(this.formData.id_card_end_date);
          idcard_expiry = `${startDate} —— ${endDate}`;
        }
      }

      // 服务区域直接传递数组格式
      let serversRegionArray = this.formData.service_area || [];

      return {
        head_photo: this.formData.head_photo,
        name: this.formData.real_name,
        account: this.formData.phone,
        second_phone: this.formData.backup_phone,
        idcard_num: this.formData.id_card,
        idcard_expiry_type: idcard_expiry_type,
        idcard_expiry: idcard_expiry,
        idcard_positive: this.formData.id_card_front,
        idcard_negative: this.formData.id_card_back,
        idcard_hands: this.formData.id_card_handheld,
        dependency: this.formData.region,
        dependency_code: this.formData.dependency_code,
        dependency_province: this.formData.dependency_province,
        dependency_city: this.formData.dependency_city,
        address: this.formData.detail_address,
        longitude: this.formData.longitude,
        latitude: this.formData.latitude,
        servers_kill: this.formData.service_skills,
        service_area: this.serviceAreaDisplayText, // 显示文本
        servers_region: serversRegionArray, // 数组格式
        service_time: this.formData.service_time,
        detail: this.formData.introduction,
        get_msg_method: this.formData.get_message_method,
        invite_code_other: this.formData.invite_code,
        major: this.formData.professional_experience,
        work_state: this.formData.work_status
      };
    },

    // 预加载提示弹窗图片
    preloadTipImages() {
      const images = [
        'https://mrrplus.oss-cn-beijing.aliyuncs.com/photo/system/ab410a5d-5819-47f2-a0fc-3fd6b90d6770', // 弹窗背景
        'https://mrrplus.oss-cn-beijing.aliyuncs.com/photo/system/2af00609-f9f5-4fa7-8013-ef92f15bbea3', // 工装头像提示
      ];
      
      console.log('开始预加载提示弹窗图片...');
      
      // 使用 Promise.all 确保所有图片都加载完成
      const loadPromises = images.map(src => this.loadImage(src));
      
      Promise.all(loadPromises)
        .then(() => {
          console.log('所有提示弹窗图片预加载完成');
          this.tipImagesPreloaded = true;
        })
        .catch(error => {
          console.warn('部分图片预加载失败:', error);
          this.tipImagesPreloaded = true;
        });
    },

    // 加载单个图片
    loadImage(src) {
      return new Promise((resolve) => {
        const img = new Image();
        img.onload = () => {
          console.log('图片加载成功:', src);
          resolve();
        };
        img.onerror = () => {
          console.warn('图片加载失败:', src);
          resolve();
        };
        img.src = src;
      });
    },

    // 显示提示弹窗
    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;
        if (this.tipImagesPreloaded) {
          this.showTipPopupFlag = true;
        } else {
          this.loadImage(this.tipImage).then(() => {
            this.showTipPopupFlag = true;
          }).catch(() => {
            this.showTipPopupFlag = true;
          });
        }
      }
    },
    
    // 隐藏提示弹窗
    hideTipPopup() {
      this.showTipPopupFlag = false;
    },

    // 设置身份证有效期类型
    setIdCardValidType(type) {
      this.formData.id_card_valid_type = type;
      if (type === 'permanent') {
        this.formData.id_card_end_date = '长久有效';
      } else {
        if (this.formData.id_card_end_date === '长久有效') {
          this.formData.id_card_end_date = '';
        }
        // 如果已有开始日期，可以自动计算一个结束日期（可选）
        if (this.formData.id_card_start_date && !this.formData.id_card_end_date) {
          const match = this.formData.id_card_start_date.match(/(\d+)年(\d+)月(\d+)日/);
          if (match) {
            const year = parseInt(match[1]) + 20;
            const month = match[2];
            const day = match[3];
            this.formData.id_card_end_date = `${year}年${month}月${day}日`;
          }
        }
      }
      this.saveFormDataToLocal();
    },

    // 日期格式化方法
    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 'permanent';
      
      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.formData[field]) {
        const dateStr = this.formData[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.formData[relatedEndField] && this.formData[relatedEndField] !== '长久有效') {
          const endDateStr = this.formData[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;
            }
          }
        }
        
        if (this.currentDateField === 'id_card_start_date') {
          // 如果是"长久有效"类型，不自动设置结束日期
          if (this.formData.id_card_valid_type === 'date') {
            const endYear = year + 20;
            const endDateStr = `${endYear}年${month}月${day}日`;
            this.formData.id_card_end_date = endDateStr;
          } else if (this.formData.id_card_valid_type === 'permanent') {
            // 如果是"长久有效"类型，保持结束日期为"长久有效"
            this.formData.id_card_end_date = '长久有效';
          }
        }

      } else if (this.currentDateField.endsWith('_end_date')) {
        const relatedStartField = this.currentDateField.replace('_end_date', '_start_date');
        if (this.formData[relatedStartField]) {
          const startDateStr = this.formData[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.formData[this.currentDateField] = dateStr;
      this.saveFormDataToLocal();
      this.hideDatePicker();
    },

    // 所在地选择方法
    showLocationPopup() {
      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.formData.region = province + '-' + city + '-' + area;

      // 清空详细地址，因为所在地已经改变
      this.formData.detail_address = '';
      this.formData.longitude = '';
      this.formData.latitude = '';

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

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

      this.saveFormDataToLocal();
      this.hideLocationPopup();
    },

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

    // 服务技能相关方法
    async loadServiceSkills() {
      try {
        console.log('开始加载服务技能...');
        const res = await request.post('/user/firstclass');
        console.log('服务技能接口响应:', res);
        
        if (res.data && res.data.length > 0) {
          this.serviceList = res.data.map(item => ({
            ...item,
            checked: this.formData.service_skills.includes(item.id)
          }));
          console.log('服务技能加载成功:', this.serviceList.length, '个技能');
          this.updateSelectedServicesText();
        } else {
          console.warn('服务技能数据为空');
          this.serviceList = [];
        }
      } catch (error) {
        console.error('加载服务技能失败:', error);
        this.serviceList = [];
      }
    },

    async showServicePopup() {
      await this.loadServiceSkills();
      this.showServicePopupFlag = true;
    },

    hideServicePopup() {
      this.showServicePopupFlag = false;
    },

    toggleServiceSelect(index) {
      this.$set(this.serviceList[index], 'checked', !this.serviceList[index].checked);
    },

    confirmServiceSelect() {
      const selectedServices = this.serviceList
        .filter(item => item.checked)
        .map(item => item.title);
      const selectedServicesId = this.serviceList
        .filter(item => item.checked)
        .map(item => item.id);

      if (selectedServices.length === 0) {
        uni.showToast({
          title: '请至少选择一个服务技能',
          icon: 'none'
        });
        return;
      }

      this.formData.service_skills = selectedServicesId;
      this.selectedServicesText = selectedServices.join('、');

      console.log('保存的服务技能ID:', this.formData.service_skills);
      console.log('显示的服务技能文本:', this.selectedServicesText);

      this.saveFormDataToLocal();
      this.hideServicePopup();
    },

    // 服务时间选择器方法
    openTimePicker() {
      this.showTimePicker = true;
    },

    hideTimePopup() {
      this.showTimePicker = false;
    },

    switchTimeType(type) {
      this.timeType = type;
    },

    handleTimeChange(e) {
      const values = e.detail.value;
      this.pickerValue = values;
    },

    // 格式化时间显示
    formatTime(time) {
      return `${time.hour}:${time.minute}`;
    },

    confirmTime() {
      this.formData.service_time = `${this.formatTime(this.startTime)}-${this.formatTime(this.endTime)}`;
      this.saveFormDataToLocal();
      this.hideTimePopup();
    },

    // 其他选择器方法
    openMessageMethodPicker() {
      uni.showActionSheet({
        itemList: ['朋友圈', '抖音', '地推', '朋友介绍', '微博'],
        success: (res) => {
          const methods = ['朋友圈', '抖音', '地推', '朋友介绍', '微博'];
          this.formData.get_message_method = res.tapIndex + 1;
          this.messageMethodText = methods[res.tapIndex];
          this.saveFormDataToLocal();
        }
      });
    },

    openExperiencePicker() {
      uni.showActionSheet({
        itemList: ['实习', '1-3年', '3-5年', '5-10年', '10年以上'],
        success: (res) => {
          const experiences = ['实习', '1-3年', '3-5年', '5-10年', '10年以上'];
          this.formData.professional_experience = res.tapIndex + 1;
          this.experienceText = experiences[res.tapIndex];
          this.saveFormDataToLocal();
        }
      });
    },

    openWorkStatusPicker() {
      uni.showActionSheet({
        itemList: ['在职', '离职', '自由职业', '在校学生', '其他'],
        success: (res) => {
          const statusList = ['在职', '离职', '自由职业', '在校学生', '其他'];
          this.formData.work_status = res.tapIndex + 1;
          this.workStatusText = statusList[res.tapIndex];
          this.saveFormDataToLocal();
        }
      });
    },

    // 图片上传方法
    async chooseImage(type) {
      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);
        
        uni.hideLoading();

        if (result) {
          this.formData[type] = result;
          
          // 上传成功后自动识别身份证
          if (type === 'id_card_front') {
            await this.recognizeIdCardFront(result);
          } else if (type === 'id_card_back') {
            await this.recognizeIdCardBack(result);
          }
          
          this.saveFormDataToLocal();
        }
      } 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;
      }
    },
    
    // 识别身份证正面
    async recognizeIdCardFront(imageUrl) {
      try {
        this.isRecognizing = true;
        this.recognizeType = 'id_card_front';
        
        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;
        }
        
        // 填充身份证正面信息
        if (result.name) {
          this.formData.real_name = result.name;
        }
        
        if (result.id_number) {
          this.formData.id_card = result.id_number;
        }
        
        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();
      }
    },

    // 检查身份证正面识别结果是否有效
    checkIdCardFrontRecognition(result) {
      return (result.name && result.name.trim()) || (result.id_number && result.id_number.trim());
    },
    
    // 新增：识别身份证反面（复用商家代码逻辑）
    async recognizeIdCardBack(imageUrl) {
      try {
        this.isRecognizing = true;
        this.recognizeType = 'id_card_back';
        
        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.formData.id_card_start_date = validPeriod.startDate;
        }
        
        if (validPeriod.isPermanent) {
          this.formData.id_card_valid_type = 'permanent';
          this.formData.id_card_end_date = '长久有效';
        } else if (validPeriod.endDate) {
          this.formData.id_card_valid_type = 'date';
          this.formData.id_card_end_date = validPeriod.endDate;
        }
        
        // 如果是长期有效，自动选择对应的选项
        if (validPeriod.isPermanent) {
          this.setIdCardValidType('permanent');
        } else {
          this.setIdCardValidType('date');
        }
        
        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());
    },

    // 验证表单
    validateForm() {
      const validationRules = [
        { field: 'head_photo', message: '请上传头像' },
        { field: 'id_card_front', message: '请上传身份证正面照片' },
        { field: 'id_card_back', message: '请上传身份证反面照片' },
        { field: 'real_name', message: '请输入真实姓名' },
        { field: 'phone', message: '请输入联系方式' },
        { field: 'backup_phone', message: '请输入备用联系方式' },
        { field: 'id_card', message: '请输入身份证号' },
        { 
          condition: () => !this.formData.id_card_valid_type, 
          message: '请选择身份证有效期类型' 
        },
       // 开始日期始终必填
        { 
          condition: () => !this.formData.id_card_start_date, 
          message: '请选择身份证开始日期' 
        },
        // 根据有效期类型验证结束日期
        { 
          condition: () => {
            // 如果选择"指定日期有效"，则结束日期必填
            if (this.formData.id_card_valid_type === 'date' && !this.formData.id_card_end_date) {
              return true; // 触发验证失败
            }
            // 如果选择"长久有效"，则不需要验证结束日期
            return false;
          }, 
          message: '请选择身份证结束日期' 
        },
        { field: 'introduction', message: '请输入个人介绍' },
        { field: 'region', message: '请选择所在地' },
        // { field: 'detail_address', message: '请选择详细地址' },
        { 
          condition: () => this.formData.service_skills.length === 0, 
          message: '请选择服务技能' 
        },
        { 
          condition: () => !this.formData.service_area || this.formData.service_area.length === 0, 
          message: '请选择服务区域' 
        },
        { field: 'service_time', message: '请选择服务时间' },
        { field: 'get_message_method', message: '请选择获取消息方式' },
        { field: 'invite_code', message: '请输入邀请码' },
        { field: 'professional_experience', message: '请选择专业经验' },
        { field: 'work_status', message: '请选择目前工作状态' }
      ];

      for (let rule of validationRules) {
        let isValid = true;
        
        if (rule.field) {
          if (!this.formData[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.formData.phone && !/^1[3-9]\d{9}$/.test(this.formData.phone)) {
        uni.showToast({
          title: '请输入正确的手机号码',
          icon: 'none'
        });
        return false;
      }
      
      if (this.formData.backup_phone && !/^1[3-9]\d{9}$/.test(this.formData.backup_phone)) {
        uni.showToast({
          title: '请输入正确的备用手机号码',
          icon: 'none'
        });
        return false;
      }
      
      // 身份证格式验证
      if (!/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(this.formData.id_card)) {
        uni.showToast({
          title: '请输入正确的身份证号码',
          icon: 'none'
        });
        return false;
      }
      
      // 验证备用手机号不能和联系方式一样
      if (this.formData.phone === this.formData.backup_phone) {
        uni.showToast({
          title: '备用手机号不能和联系方式一样',
          icon: 'none'
        });
        return false;
      }
      
      // 邀请码有效性验证
      if (this.inviteCodeValidating) {
        uni.showToast({ title: '邀请码验证中，请稍候', icon: 'none' });
        return false;
      }
      
      // 特殊邀请码13131313直接通过
      if (this.formData.invite_code === '13131313') {
        // 直接通过
      } else if (this.inviteCodeError || !this.inviterInfo) {
        // 邀请码无效，触发抖动效果
        this.triggerInviteErrorShake();
        return false;
      }
      
      return true;
    },

    // 保存表单数据（在进入下一步时调用）
    async saveFormData() {
      console.log('手艺人个人信息页面：开始验证表单');
      
      // 1. 先进行常规表单验证（同步）
      if (!this.validateForm()) {
        console.log('常规表单验证失败');
        return false;
      }
      
      console.log('常规表单验证通过，开始身份证验证');
      
      // 2. 验证姓名与身份证是否匹配（异步）
      const isValid = await this.validateIdcardAndName();
      if (!isValid) {
        console.log('身份证验证失败');
        return false;
      }
      
      console.log('身份证验证通过');
      
      // 3. 验证通过，保存数据到全局
      getApp().globalData.personalInfoData = this.formData;
      console.log('数据已保存到全局');
      return true;
    },

    // 验证姓名与身份证匹配度
    async validateIdcardAndName() {
      console.log('开始身份证姓名匹配验证');
      console.log('姓名:', this.formData.real_name);
      console.log('身份证号:', this.formData.id_card);

      // 清理姓名：去除两端空格
      const cleanedName = this.formData.real_name ? this.formData.real_name.trim() : '';
      const cleanedIdCard = this.formData.id_card ? this.formData.id_card.trim() : '';
      
      if (!cleanedName || !cleanedIdCard) {
        console.log('姓名或身份证号为空');
        uni.showToast({
          title: '请填写姓名和身份证号',
          icon: 'none'
        });
        return false;
      }
      
      try {
        uni.showLoading({
          title: '验证身份信息...'
        });
        
        console.log('调用身份验证接口');
        const checkRes = await request.post('/user/check', {
          name: this.formData.real_name,
          idcard: this.formData.id_card
        });
        
        uni.hideLoading();
        
        console.log('身份验证接口返回');
        console.log('完整响应:', checkRes);
        console.log('Code:', checkRes.Code);
        console.log('ResultObject:', checkRes.ResultObject);
        
        // 根据参考代码的验证逻辑
        if (checkRes.Code == '401') {
          console.log('Code 401 验证失败');
          uni.showToast({
            title: '您的身份证号与姓名不匹配',
            icon: 'none',
            duration: 3000
          });
          return false;
        }
        
        if (checkRes.ResultObject && checkRes.ResultObject.BizCode != '1') {
          console.log('BizCode 验证失败 ');
          uni.showToast({
            title: '您的身份证号与姓名不匹配',
            icon: 'none',
            duration: 3000
          });
          return false;
        }
        
        console.log('身份证验证通过');
        return true;
        
      } catch (error) {
        uni.hideLoading();
        console.error('身份证验证接口调用失败');
        console.error('错误信息:', error);
        
        uni.showToast({
          title: '身份验证失败，请稍后重试',
          icon: 'none',
          duration: 3000
        });
        return false;
      }
    },

    // 服务区域选择相关方法
    
    // 显示服务区域选择弹出框
    showRegionPopup() {
      // 重置选择器状态
      this.currentTab = 0;
      this.cityList = [];
      this.districtList = [];
      this.selectedProvince = null;
      this.selectedCity = null;
      this.currentSelectedCity = '';
      
      this.showRegionPopupFlag = true;
    },

    // 隐藏服务区域选择弹出框
    hideRegionPopup() {
      this.showRegionPopupFlag = false;
    },

    // 切换标签页
    switchTab(index) {
      if (index < this.currentTab) {
        this.currentTab = index;
      }
    },

    // 选择省份
    selectProvince(province, index) {
      this.selectedProvince = province.province;
      this.currentTab = 1;
      // 获取城市列表
      this.cityList = this.ChinaCitys[index].citys || [];
      // 重置当前选择的城市
      this.currentSelectedCity = '';
    },

    // 选择城市
    selectCity(city, index) {
      // 检查是否已经有选中的城市
      if (this.currentSelectedCity && city.city !== this.currentSelectedCity) {
        // 如果切换城市，需要清空已选区域
        uni.showModal({
          title: '提示',
          content: '切换城市将清空已选区域，是否继续？',
          success: (res) => {
            if (res.confirm) {
              // 清空已选区域
              this.formData.service_area = [];
              this.currentSelectedCity = city.city;
              this.selectedCity = city.city;
              this.currentTab = 2;
              // 获取区县列表并初始化选中状态
              this.districtList = (city.areas || []).map(item => ({
                ...item,
                checked: false
              }));
            }
          }
        });
      } else {
        // 第一次选择城市或选择同一城市
        this.currentSelectedCity = city.city;
        this.selectedCity = city.city;
        this.currentTab = 2;
        // 获取区县列表并初始化选中状态
        this.districtList = (city.areas || []).map(item => ({
          ...item,
          checked: this.formData.service_area.includes(`${this.selectedProvince}-${this.selectedCity}-${item.area}`)
        }));
      }
    },

    // 切换区县选择状态
    toggleDistrictSelect(index) {
      this.$set(this.districtList[index], 'checked', !this.districtList[index].checked);
    },

    // 确认地区选择
    confirmRegionSelect() {
      const selectedDistricts = this.districtList
        .filter(item => item.checked)
        .map(item => `${this.selectedProvince}-${this.selectedCity}-${item.area}`);

      if (selectedDistricts.length === 0) {
        uni.showToast({
          title: '请至少选择一个区县',
          icon: 'none'
        });
        return;
      }

      // 更新选中的区域
      this.formData.service_area = selectedDistricts;
      // 更新显示文本
      this.updateServiceAreaDisplayText();
      this.saveFormDataToLocal();
      this.hideRegionPopup();

      console.log('选中的区域:', this.formData.service_area);
    }
  }
}
</script>

<style scoped>

.personal-info-page {
  padding: 15rpx 0;
}

.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;
}

.section-title text {
  font-size: 32rpx;
  color: #1D2129;
  font-weight: 500;
}

.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: 8rpx;
  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-container {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.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;
}

.idcard-front {
  background-size: cover;
}

.idcard-back {
  background-size: cover;
}

.idcard-handheld {
  background-size: cover;
}

.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: 48rpx;
}

.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;
  flex-shrink: 0;
}

.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: 608rpx;
  align-items: center;
  font-size: 28rpx;
  color: #333333;
  line-height: 1.5;
  background: #F8F9FD;
  border-radius: 20rpx;
  padding: 20rpx 24rpx;
}

.textarea-counter {
  text-align: right;
  font-size: 24rpx;
  color: #999;
  margin-top: 10rpx;
}

.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;
}

.form-item-one-yqr {
  flex-direction: column;
  align-items: stretch;
  padding: 0;
}

.invite-code-top {
  display: flex;
  align-items: center;
  padding: 24rpx;
  width: 100%;
  box-sizing: border-box;
}

.divider {
  height: 1rpx;
  background-color: #00000013;
  width: 100%;
}

.invite-tip-box {
  padding: 20rpx 24rpx;
  width: 100%;
  box-sizing: border-box;
}

.invite-tip {
  font-family: PingFangSC, PingFang SC;
  font-weight: 400;
  font-size: 24rpx;
  color: #666666;
  line-height: 28rpx;
  text-align: left;
  font-style: normal;
}

.checkbox-list {
  display: flex;
  flex-wrap: wrap;
}

.checkbox-item {
  width: 50%;
  padding: 14rpx;
  display: flex;
  align-items: center;
}

.checkbox {
  width: 40rpx;
  height: 40rpx;
  border: 2rpx solid #DDDDDD;
  border-radius: 8rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16rpx;
}

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

.check-icon {
  width: 42rpx;
  height: 42rpx;
}

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

/* 邀请码相关样式 */
.invite-info-container {
  padding: 20rpx 24rpx;
  width: 100%;
  box-sizing: border-box;
  min-height: 60rpx;
}

.invite-tip {
  font-family: PingFangSC, PingFang SC;
  font-weight: 400;
  font-size: 20rpx;
  color: #666666;
  line-height: 28rpx;
  text-align: left;
  font-style: normal;
}

.invite-validating {
  font-size: 20rpx;
  color: #999999;
}

.invite-error {
  font-size: 24rpx;
  color: #E8101E;
}

.inviter-info {
  display: flex;
  align-items: center;
  font-size: 20rpx;
}

.inviter-label {
  color: #666666;
}

.inviter-name {
  color: #333333;
  font-weight: 500;
}

.inviter-divider {
  color: #666666;
  margin: 0 5rpx;
}

.inviter-phone {
  color: #666666;
}

/* 添加抖动动画样式 */
@keyframes shake {
  0%, 100% { transform: translateX(0); }
  10%, 30%, 50%, 70%, 90% { transform: translateX(-7rpx); }
  20%, 40%, 60%, 80% { transform: translateX(7rpx); }
}

.shake-animation {
  animation: shake 0.5s ease-in-out;
  color: #E8101E; /* 保持红色 */
}

/* 区域选择器样式 */
.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);
}

/* 确保服务区域选择弹出框的底部按钮显示正确 */
.region-popup {
  height: 80vh !important;
  max-height: 80vh !important;
  display: flex;
  flex-direction: column;
  padding: 0;
}

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

.region-tabs {
  display: flex;
  border-bottom: 1rpx solid #EEEEEE;
  margin-bottom: 20rpx;
  padding: 0 32rpx;
  flex-shrink: 0;
}

.region-body {
  flex: 1;
  overflow: hidden;
  height: 0; /* 重要：让flex布局计算高度 */
}

.region-scroll {
  height: 100%;
  padding: 0 32rpx;
}

.popup-footer {
  display: flex;
  margin-top: auto;
  padding: 32rpx;
  flex-shrink: 0;
  border-top: 1rpx solid #EEEEEE;
}

.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;
}


/* 服务时间选择器样式 */
.time-range {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 32rpx;
  background: #F8F9FC;
}

.time-block {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  background: #FFFFFF;
  border-radius: 12rpx;
  padding: 24rpx 0;
  transition: all 0.3s ease;
}

.time-block.active {
  background: #ECF2FF;
}

.time-label {
  font-size: 26rpx;
  color: #999999;
  margin-top: 8rpx;
}

.time-value {
  font-size: 40rpx;
  color: #333333;
  font-weight: 500;
}

.time-block.active .time-value {
  color: #E8101E;
}

.time-separator {
  font-size: 28rpx;
  color: #999999;
  margin: 0 24rpx;
}

.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;
}

/* 服务区域选择器样式 */
.region-tabs {
  display: flex;
  border-bottom: 1rpx solid #EEEEEE;
  margin-bottom: 20rpx;
  padding: 0 32rpx;
}

.region-tab {
  flex: 1;
  text-align: center;
  padding: 20rpx 0;
  font-size: 28rpx;
  color: #666666;
  position: relative;
}

.region-tab.active {
  color: #E8101E;
  font-weight: 500;
}

.region-tab.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 40rpx;
  height: 4rpx;
  background-color: #E8101E;
  border-radius: 2rpx;
}

.region-scroll {
  height: 100%;
  padding: 0 32rpx;
}

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

.region-item.checkbox-item {
  padding: 20rpx 0;
  width: 100%;
  justify-content: flex-start;
}

/* 提示弹窗样式 */
.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 {
  /* margin: 0 20rpx 0 30rpx; */
  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>