<template>
  <view class="qualification-page">
    <!-- 顶部导航栏 -->
    <custom-navbar :title="navTitle" :showBack="true"></custom-navbar>
    <!-- 变更提示 -->
    <view class="change-tip" v-if="editable">
      <text>请变更您需要变更的信息</text>
    </view>
    <!-- 页面内容容器 -->
    <view class="content-area" :style="{ paddingBottom: buttonAreaHeight + 'px' }">
      

      <!-- 所属门店 -->
      <view class="section">
        <view class="section-title">
          <view class="title-bar"></view>
          <text class="title-text">所属门店</text>
        </view>

        <!-- 资质照片、营业执照和门头照 -->
        <view class="box-cont">
          <view class="form-item">
            <text class="label required">门店资质照片</text>
            <view class="upload-tip">请保证照片上的文字清晰、无遮挡、证件边角可见。</view>
            <view class="idcard-upload-vertical-container">
              <!--营业执照-->
              <view class="idcard-upload-vertical-item">
                <view class="upload-box" @click="editable ? chooseImage('uscc_photo') : null">
                  <view class="upload-camera idcard-front">
                    <image v-if="displayData.uscc_photo" :src="displayData.uscc_photo" mode="aspectFill" class="preview-image"></image>
                    <image v-else src="https://mrrplus.oss-cn-beijing.aliyuncs.com/photo/system/92bd4268-b4d7-4725-8664-9e44f828c7d9" mode="aspectFit" class="camera-icon"></image>

                  </view>
                </view>
                <text class="upload-label required">请上传营业执照原件</text>
              </view>

              <!--门头照-->
              <view class="idcard-upload-vertical-item">
                <view class="upload-box" @click="editable ? chooseImage('shop_photo') : null">
                  <view class="upload-camera idcard-front">
                    <image v-if="displayData.shop_photo" :src="displayData.shop_photo" mode="aspectFill" class="preview-image"></image>
                    <image v-else src="https://mrrplus.oss-cn-beijing.aliyuncs.com/photo/system/60cdf929-bf63-4d56-a05d-467ae9903060" mode="aspectFit" class="camera-icon"></image>
                  </view>
                </view>
                <text class="upload-label required">请上传门头照</text>
              </view>
            </view>
          </view>
        </view>

        <view class="form-item-one box-cont">
          <view class="label-wrapper">
            <text class="label required">门店类型</text>
          </view>
          <input type="text" v-model="displayData.uscc_type" placeholder="请输入门店类型" 
                 :disabled="!editable" placeholder-class="placeholder" class="input" />
        </view>
      </view>

      <!-- 证照号码 -->
      <view class="section">
        <view class="form-item-one 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('uscc_num')"></image>
          </view>
          <input type="text" v-model="displayData.uscc_num" placeholder="请输入营业执照的证件号码" 
                 :disabled="!editable" placeholder-class="placeholder" class="input" />
        </view>

        <view class="form-item-one 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('uscc_name')"></image>
          </view>
          <input type="text" v-model="displayData.uscc_name" placeholder="请输入营业执照的企业名称" 
                 :disabled="!editable" placeholder-class="placeholder" class="input" />
        </view>

        <view class="form-item-one 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('for_shop')"></image>
          </view>
          <input type="text" v-model="displayData.for_shop" placeholder="请输入营业执照的店铺名称" 
                 :disabled="!editable" placeholder-class="placeholder" class="input" />
        </view>
      </view>

      <!-- 底部安全间距 -->
      <view class="safe-bottom"></view>
    </view>

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

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

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

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

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

    <!-- 日期选择器 -->
    <view 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="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="currentTipField" :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';
// 添加OCR识别相关导入（100%复用商家代码）
import { recognizeBusinessLicense } 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);
    
    return {
      // 页面状态
      editable: false,
      buttonType: 'change', // change-变更信息, edit-取消/提交, view-查看我的变更, reject-重新提交
      showAuditTip: false,
      auditStatus: null, // 审核状态: null-无申请, 1-审核中, 2-审核通过, 3-审核驳回
      applyId: null,
      showPendingData: false, // 是否显示待审核数据
      navTitle: '所属门店',
      buttonAreaHeight: 120,
      backText: '', // 驳回原因
      hasResubmitted: false,
      
      // 数据管理
      originalData: {}, // 老数据（当前生效的）
      pendingData: {}, // 新数据（待审核的）
      displayData: {}, // 当前显示的数据

      // 用户信息
      userId: null,
      identity: null,
      applyType: 6, // 所属门店变更

      // 表单相关
      showStoreTypePickerFlag: false,
      showDatePickerFlag: false,
      showTipPopupFlag: false,
      tipTitle: '',
      tipImage: '',
      currentDateField: '',
      currentTipField: '',
      // 门店类型列表更新为字符串值
      storeTypeList: [
        { label: '个体工商户营业执照', value: '个体工商户营业执照' },
        { label: '企业法人营业执照', value: '企业法人营业执照' },
      ],
      years,
      months,
      days,
      dateValue: [currentYear - 1970, currentDate.getMonth(), currentDate.getDate() - 1],
      indicatorStyle: 'height: 68rpx;',
      userInfo: null,
      artisanInfo: null,
      
      // 添加营业执照识别相关状态
      isRecognizing: false,
      recognizeType: '', // 'uscc_photo'
    }
  },
  computed: {
    storeTypeText() {
      // 直接返回字符串值
      return this.displayData.uscc_type || '';
    },
    shouldShowRejectReason() {
      return this.auditStatus === 3 && !this.showPendingData && this.backText;
    }
  },
  onLoad(options) {
    this.initPage();
  },
  onReady() {
    this.getButtonAreaHeight();
  },
  onShow() { 
    // 只有在非编辑状态下才重新加载数据
    if (!this.editable) {
      console.log('非编辑状态，刷新数据');
      this.loadApplyDetails();
      
      if (this.auditStatus !== 3) {
        this.backText = '';
        this.hasResubmitted = false;
      }
    } else {
      console.log('编辑状态，保持当前状态不刷新');
    }
  },
  methods: {
    // 初始化页面
    async initPage() {
      try {
        // 获取用户ID
        await this.getUserInfo();
        this.identity = getApp().globalData.artisanType;
        
        // 获取用户详细信息
        await this.getUserDetailInfo();
        
        // 加载申请详情
        await this.loadApplyDetails();
        
        // 恢复保存的数据（如果有）
        this.restoreData();
      } catch (error) {
        console.error('页面初始化失败:', error);
        uni.showToast({
          title: '页面加载失败',
          icon: 'none'
        });
      }
    },

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

    // 获取用户详细信息（包括门店信息）
    async getUserDetailInfo() {
      try {
        // 直接获取手艺人信息，type=2
        const artisanResult = await request.post('/user/getuser', { type: 2 });
        if (artisanResult.state === 1) {
          this.artisanInfo = artisanResult.data;
          console.log('手艺人信息原始数据:', JSON.parse(JSON.stringify(this.artisanInfo)));
          
          // 重新填充表单数据
          this.fillFormWithExistingData();
          
          // 如果是审核通过后调用，确保显示最新数据
          if (this.auditStatus === 2) {
            this.displayData = { ...this.originalData };
          }
        }
      } catch (error) {
        console.error('获取手艺人信息失败:', error);
      }
    },

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

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

          // 更新pendingData
          if (this.auditStatus === 1 || this.auditStatus === 3) {
            this.pendingData = {
              uscc_type: detail.uscc_type || this.originalData.uscc_type,
              uscc_photo: detail.uscc_photo || this.originalData.uscc_photo,
              shop_photo: detail.shop_photo || this.originalData.shop_photo,
              uscc_num: detail.uscc_num || this.originalData.uscc_num,
              uscc_name: detail.uscc_name || this.originalData.uscc_name,
              for_shop: detail.for_shop || this.originalData.for_shop,
              uscc_expiry_type: detail.uscc_expiry_type || this.originalData.uscc_expiry_type,
              license_start_date: '',
              license_end_date: ''
            };

            // 处理营业执照有效期
            if (detail.uscc_expiry) {
              this.parseExpiryDate(detail.uscc_expiry, 'license', this.pendingData);
            }
          }
          
          // 审核通过时同步数据
          if (this.auditStatus === 2) {
            console.log('审核通过，开始同步最新数据...');
            // 重新获取最新的手艺人信息来更新数据
            await this.getUserDetailInfo();
            
            // 清空pendingData，因为变更已生效
            this.pendingData = { ...this.originalData };
            
            // 重置申请相关状态
            this.applyId = null;
            this.backText = '';
          }
          
          this.updatePageStatus();
          
        } else {
          console.log('申请详情返回数据为空或code不为200:', res);
          this.backText = '';
          this.updatePageStatus();
        }
        
      } catch (error) {
        console.error('加载申请详情失败:', error);
        this.backText = '';
        this.updatePageStatus();
      }
    },

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

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

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

      this.updateNavTitle();
    },

    // 更新导航栏标题
    updateNavTitle() {
      if (this.editable || this.showPendingData) {
        this.navTitle = '所属门店变更';
      } else {
        this.navTitle = '所属门店';
      }
    },

    // 用现有数据填充表单
    fillFormWithExistingData() {
      if (!this.artisanInfo) return;
      
      console.log('开始填充表单数据，门店信息:', this.artisanInfo);
      
      // 初始化老数据
      this.originalData = {
        uscc_type: '',
        uscc_photo: '',
        shop_photo: '',
        uscc_num: '',
        uscc_name: '',
        for_shop: '',
        uscc_expiry_type: '',
        license_start_date: '',
        license_end_date: ''
      };
      
      // 门店类型
      if (this.artisanInfo.uscc_type) {
        // 如果uscc_type是数字，转换为对应的字符串
        if (this.artisanInfo.uscc_type === 1) {
          this.originalData.uscc_type = '个体工商户营业执照';
        } else if (this.artisanInfo.uscc_type === 2) {
          this.originalData.uscc_type = '企业法人营业执照';
        } else {
          this.originalData.uscc_type = this.artisanInfo.uscc_type;
        }
      }
      
      // 营业执照照片
      if (this.artisanInfo.uscc_photo) {
        this.originalData.uscc_photo = this.artisanInfo.uscc_photo;
      }
      
      // 门头照
      if (this.artisanInfo.shop_photo) {
        this.originalData.shop_photo = this.artisanInfo.shop_photo;
      } else {
        console.log('未找到门头照字段，当前数据中的图片字段:', Object.keys(this.artisanInfo).filter(key => key.includes('photo') || key.includes('img')));
        this.originalData.shop_photo = '';
      }
      
      // 证件号码
      if (this.artisanInfo.uscc_num) {
        this.originalData.uscc_num = this.artisanInfo.uscc_num;
      }
      
      // 企业名称
      if (this.artisanInfo.uscc_name) {
        this.originalData.uscc_name = this.artisanInfo.uscc_name;
      }
      
      // 店铺名称
      if (this.artisanInfo.for_shop) {
        this.originalData.for_shop = this.artisanInfo.for_shop;
      }
      
      // 营业执照有效期类型
      if (this.artisanInfo.uscc_expiry_type) {
        this.originalData.uscc_expiry_type = this.artisanInfo.uscc_expiry_type;
      }
      
      // 营业执照有效期
      if (this.artisanInfo.uscc_expiry) {
        this.parseExpiryDate(this.artisanInfo.uscc_expiry, 'license', this.originalData);
      }
      
      // 初始化pendingData和displayData
      this.pendingData = { ...this.originalData };
      this.displayData = { ...this.originalData };
      
      console.log('数据初始化完成:', {
        originalData: this.originalData,
        pendingData: this.pendingData,
        displayData: this.displayData
      });
    },

    // 解析有效期字符串
    parseExpiryDate(expiryStr, type, targetData) {
      if (!expiryStr) return;
      
      const parts = expiryStr.split('——').map(part => part.trim());
      if (parts.length >= 1) {
        const startDate = parts[0];
        if (startDate) {
          if (type === 'license') {
            targetData.license_start_date = this.formatDateFromBackend(startDate);
          }
        }
        
        if (parts.length >= 2 && parts[1]) {
          const endDate = parts[1];
          if (type === 'license') {
            targetData.license_end_date = this.formatDateFromBackend(endDate);
          }
        } else {
          // 如果没有结束日期，设置为长久有效
          if (type === 'license') {
            targetData.uscc_expiry_type = 1;
            targetData.license_end_date = '长久有效';
          }
        }
      }
    },

    // 从后端格式转换到显示格式
    formatDateFromBackend(dateStr) {
      if (!dateStr) return '';
      
      // 如果是 YYYY-MM-DD 格式
      if (dateStr.match(/^\d{4}-\d{2}-\d{2}$/)) {
        const [year, month, day] = dateStr.split('-');
        return `${year}年${parseInt(month)}月${parseInt(day)}日`;
      }
      
      return dateStr;
    },

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

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

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

    // 准备提交数据
    prepareSubmitData() {
      // 提交前确保uscc_type是字符串类型
      const submitUsccType = typeof this.displayData.uscc_type === 'number' 
        ? (this.displayData.uscc_type === 1 ? '个体工商户营业执照' : '企业法人营业执照')
        : this.displayData.uscc_type;
      
      const submitData = {
        apply_type: this.applyType, // 所属门店变更
        uscc_type: submitUsccType,
        uscc_photo: this.displayData.uscc_photo,
        shop_photo: this.displayData.shop_photo,
        uscc_num: this.displayData.uscc_num,
        uscc_name: this.displayData.uscc_name,
        for_shop: this.displayData.for_shop,
        uscc_expiry_type: this.displayData.uscc_expiry_type,
        uscc_expiry: this.formatLicenseExpiry()
      };
      
      console.log('提交数据:', submitData);
      return submitData;
    },

    // 格式化营业执照有效期
    formatLicenseExpiry() {
      if (!this.displayData.license_start_date) return '';
      
      const startDate = this.formatDateForBackend(this.displayData.license_start_date);
      
      if (this.displayData.uscc_expiry_type === 1) {
        return `${startDate} ——        `;
      } else if (this.displayData.license_end_date) {
        const endDate = this.formatDateForBackend(this.displayData.license_end_date);
        return `${startDate} —— ${endDate}`;
      }
      
      return '';
    },

    // 显示提示弹窗
    showTipPopup(field) {
      const tipConfig = {
        'uscc_num': {
          title: '如何找到证件号码',
          image: 'https://mrrplus.oss-cn-beijing.aliyuncs.com/photo/system/72856aac-f0ac-49a1-a7f1-be3220ecb314'
        },
        'uscc_name': {
          title: '如何找到企业名称',
          image: 'https://mrrplus.oss-cn-beijing.aliyuncs.com/photo/system/4fb3e0a2-4c1a-4433-a181-b7a1dfefd030'
        },
        'for_shop': {
          title: '如何找到店铺名称',
          image: 'https://mrrplus.oss-cn-beijing.aliyuncs.com/photo/system/151b2238-099a-4b94-9376-03197d994101'
        }
      };
      
      if (tipConfig[field]) {
        this.tipTitle = tipConfig[field].title;
        this.tipImage = tipConfig[field].image;
        this.currentTipField = field;
        this.showTipPopupFlag = true;
      }
    },
    
    hideTipPopup() {
      this.showTipPopupFlag = false;
      setTimeout(() => {
        this.currentTipField = '';
      }, 300);
    },

    // 日期显示格式化
    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;
    },

    // 设置营业执照有效期类型
    setLicenseValidType(type) {
      this.displayData.uscc_expiry_type = type === 'permanent' ? 1 : 2;
      if (type === 'permanent') {
        this.displayData.license_end_date = '长久有效';
      } else {
        if (this.displayData.license_end_date === '长久有效') {
          this.displayData.license_end_date = '';
        }
      }
    },

    // 门店类型选择
    showStoreTypePicker() {
      if (!this.editable) return;
      this.showStoreTypePickerFlag = true;
    },
    
    hideStoreTypePicker() {
      this.showStoreTypePickerFlag = false;
    },
    
    selectStoreType(item) {
      this.displayData.uscc_type = item.value;
    },
    
    confirmStoreType() {
      this.hideStoreTypePicker();
    },

    // 日期选择
    openDatePicker(field) {
      if (!this.editable) return;
      
      this.currentDateField = field;
      
      const currentDate = new Date();
      let initialDate = currentDate;
      
      if (this.displayData[field]) {
        const dateStr = this.displayData[field];
        const match = dateStr.match(/(\d+)年(\d+)月(\d+)日/);
        if (match) {
          initialDate = new Date(parseInt(match[1]), parseInt(match[2]) - 1, parseInt(match[3]));
        }
      }
      
      const yearIndex = this.years.indexOf(initialDate.getFullYear());
      const monthIndex = initialDate.getMonth();
      const dayIndex = initialDate.getDate() - 1;
      
      this.dateValue = [
        yearIndex >= 0 ? yearIndex : 0,
        monthIndex,
        dayIndex
      ];
      
      this.showDatePickerFlag = true;
    },
    
    hideDatePicker() {
      this.showDatePickerFlag = false;
    },
    
    bindDateChange(e) {
      this.dateValue = e.detail.value;
    },

    confirmDate() {
      const [yearIndex, monthIndex, dayIndex] = this.dateValue;
      const year = this.years[yearIndex];
      const month = this.months[monthIndex];
      const day = this.days[dayIndex];
      const dateStr = `${year}年${month}月${day}日`;
      
      this.displayData[this.currentDateField] = dateStr;
      this.hideDatePicker();
    },

    // 图片上传 - 添加自动识别功能（100%复用商家代码）
    async chooseImage(type) {
      if (!this.editable) return;
      
      try {
        if (!this.userId) {
          await this.getUserInfo();
        }

        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) {
          return;
        }

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

        const result = await this.directUpload(file, this.userId, this.identity + 1);
        
        if (result) {
          this.displayData[type] = result;
          
          // 上传成功后自动识别营业执照（100%复用商家代码）
          if (type === 'uscc_photo') {
            await this.recognizeBusinessLicense(result);
          }
        }
      } catch (err) {
        console.log('上传图片错误:', err);
        uni.showToast({
          title: '图片上传失败',
          icon: 'none'
        });
      }
    },

    /**
     * 识别营业执照（100%复用商家代码）
     */
    async recognizeBusinessLicense(imageUrl) {
      try {
        this.isRecognizing = true;
        this.recognizeType = 'uscc_photo';
        
        uni.showLoading({
          title: '正在识别营业执照...',
          mask: true
        });
        
        // 调用OCR接口
        const result = await recognizeBusinessLicense(imageUrl);
        console.log('营业执照识别结果:', result);

        const hasRecognizedData = this.checkBusinessLicenseRecognition(result);
        if (!hasRecognizedData) {
          uni.hideLoading();
          uni.showToast({
            title: '未识别到营业执照信息，请手动填写或重新拍摄',
            icon: 'none',
            duration: 3000
          });
          this.isRecognizing = false;
          return;
        }
        
        // 填充营业执照信息
        let recognizedFields = 0;

        // 门店类型：直接使用OCR返回的字符串值
        if (result.uscc_type && result.uscc_type.trim()) {
          this.displayData.uscc_type = result.uscc_type.trim();
          recognizedFields++;
        }

        // 企业名称：如果识别结果为"无"，就设置为空字符串
        if (result.uscc_name && result.uscc_name.trim() && result.uscc_name !== '无') {
          this.displayData.uscc_name = result.uscc_name;
          recognizedFields++;
        } else {
          // 如果是"无"或空值，设置为空字符串
          this.displayData.uscc_name = '';
        }
        
        if (result.uscc_num && result.uscc_num.trim()) {
          this.displayData.uscc_num = result.uscc_num.trim();
          recognizedFields++;
        }
        
        // 如果店铺名称为空，使用企业名称填充（100%复用商家代码逻辑）
        if (result.uscc_name && result.uscc_name.trim()) {
          this.displayData.for_shop = result.uscc_name.trim();
        }

        uni.hideLoading();
        
        // 根据识别的字段数量给出不同的提示（100%复用商家代码逻辑）
        if (recognizedFields > 0) {
          uni.showToast({
            title: '营业执照识别成功',
            icon: 'none',
            duration: 2000
          });
        } else {
          uni.showToast({
            title: '识别完成，但未获取到有效信息',
            icon: 'none',
            duration: 3000
          });
        }
        
      } catch (error) {
        console.error('营业执照识别失败:', error);
        uni.hideLoading();
        uni.showToast({
          title: error.message || '识别失败，请手动填写',
          icon: 'none',
          duration: 3000
        });
      } finally {
        this.isRecognizing = false;
      }
    },

    // 检查营业执照识别结果是否有效（100%复用商家代码逻辑）
    checkBusinessLicenseRecognition(result) {
      const requiredFields = ['uscc_num', 'uscc_name', 'uscc_type'];
      
      for (const field of requiredFields) {
        if (result[field] && result[field].trim()) {
          return true;
        }
      }
      
      return false;
    },

    // 直接上传方法
    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;
      }
    },

    // 表单验证
    validateForm() {
      const validationRules = [
        { field: 'uscc_photo', message: '请上传营业执照原件' },
        { field: 'shop_photo', message: '请上传门头照' },
        { field: 'uscc_type', message: '请输入门店类型' },
        { field: 'uscc_num', message: '请输入营业执照的证件号码' },
        { field: 'uscc_name', message: '请输入营业执照的企业名称' },
        { field: 'for_shop', message: '请输入营业执照的店铺名称' },
      ];

      for (let rule of validationRules) {
        let isValid = true;
        
        if (rule.field) {
          // 简单字段验证
          if (!this.displayData[rule.field]) {
            isValid = false;
          }
        } else if (rule.condition) {
          // 复杂条件验证
          if (rule.condition()) {
            isValid = false;
          }
        }
        
        if (!isValid) {
          uni.showToast({
            title: rule.message,
            icon: 'none'
          });
          return false;
        }
      }
      
      return true;
    },
    // 提交变更
    async submitChange() {
      console.log('开始提交变更...');
      
      if (!this.validateForm()) {
        return;
      }

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

        const submitData = this.prepareSubmitData();
        
        // 调用申请接口
        const result = await request.post('/syr/userSyrAuth/apply', submitData);
        
        uni.hideLoading();

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

    // 从全局恢复数据  
    restoreData() {
      const savedData = getApp().globalData.storeData;
      if (savedData) {
        // 恢复数据到表单
        Object.keys(this.displayData).forEach(key => {
          if (savedData[key] !== undefined) {
            this.displayData[key] = savedData[key];
          }
        });
        console.log('门店信息数据已恢复:', this.displayData);
      }
    },

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

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

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

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

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

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

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

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

}

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

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

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

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

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

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

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

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

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

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

.cancel-text {
  color: #666666;
}

.section {
  margin-bottom: 30rpx;
}

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

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

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

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

.form-item {
  padding: 24rpx 22rpx;
}

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

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

.upload-label {
  font-family: Helvetica;
  font-size: 28rpx;
  color: #999;
  line-height: 40rpx;
  text-align: left;
  font-style: normal;
  margin-top: 24rpx;
}

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

.upload-tip {
  font-size: 26rpx;
  color: #999;
  margin: 5rpx 0 24rpx 0;
  font-weight: 400;
  font-family: PingFangSC, PingFang SC;
  text-align: left;
  font-style: normal;
}

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

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

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

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

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

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

/* 识别状态遮罩*/
.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;
}

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

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

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

.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-value {
  font-size: 28rpx;
  color: #333;
}

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

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

/* 日期选择框置灰状态 */
.date-picker-box.disabled {
  border: 2rpx solid #F3F3F3;
}

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

/* 置灰状态下的竖线 */
.date-picker-box.disabled .date-divider {
  background-color: #F3F3F3;
}

/* 确保日期文字区域可以自动扩展 */
.date-picker-box text {
  flex: 1;
}

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

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

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

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

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

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

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

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

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

.popup-body {
  max-height: 400rpx;
  overflow-y: auto;
}

.radio-list .radio-item {
  margin-bottom: 32rpx;
}

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

.popup-btn {
  height: 88rpx;
  border-radius: 44rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(180deg, #f52540 0%, #e8101e 100%);
}

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

.cancel-text, .confirm-text {
  font-size: 32rpx;
  padding: 16rpx;
}

.cancel-text {
  color: #666666;
}

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

.picker-scroll {
  height: 400rpx;
}

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

/* 提示弹窗样式 */
.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;
  flex-direction: column;
  padding: 80rpx 20rpx 40rpx 20rpx;
  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 {
  align-items: center;
  justify-content: center;
  margin-bottom: 50rpx;
}

 .tip-image {
  width: 521rpx;
  height: 327rpx;
  margin-left: 30rpx; 
}

/* 店铺名称图片的特殊样式 */
.tip-image.for_shop {
  width: 627rpx;
  height: 327rpx;
  margin-left: 13rpx;
}

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

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

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

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

.tip-btn .btn-text {
  color: inherit;
}

.safe-bottom {
  height: 150rpx;
}
</style>