Page({
  data:{
    photoPath: '',
    livenessSteps: ['请正对镜头', '请张张嘴', '请左右摇头', '请眨眨眼'],
    stepIndex: 0,
    isCapturing: false,
    isUploading: false
  },
  onLoad(){
    // 页面加载时检查并申请摄像头权限
    this.checkCameraPermission();
  },
  async checkCameraPermission(){
    try{
      const setting = await new Promise((resolve) => {
        wx.getSetting({ success: resolve, fail: () => resolve({}) });
      });
      // 检查是否已授权
      if(!setting.authSetting || !setting.authSetting['scope.camera']){
        // 未授权，主动申请
        const result = await new Promise((resolve) => {
          wx.authorize({
            scope: 'scope.camera',
            success: () => resolve({ granted: true }),
            fail: () => resolve({ granted: false })
          });
        });
        if(!result.granted){
          // 用户拒绝了授权，需要引导去设置页
          wx.showModal({
            title: '需要摄像头权限',
            content: '为了完成实名认证，需要访问您的摄像头。请在设置中开启摄像头权限。',
            confirmText: '去设置',
            success: (res) => {
              if(res.confirm){
                wx.openSetting({
                  success: (settingRes) => {
                    if(settingRes.authSetting && settingRes.authSetting['scope.camera']){
                      wx.showToast({ title: '授权成功', icon: 'success' });
                    } else {
                      wx.showToast({ title: '授权失败，无法使用摄像头', icon: 'none' });
                    }
                  }
                });
              }
            }
          });
        }
      }
    }catch(err){
      console.error('检查摄像头权限失败:', err);
    }
  },
  onCameraError(e){
    console.error('camera error', e);
    let msg = '摄像头打开失败';
    if(e.detail && e.detail.errMsg){
      if(e.detail.errMsg.includes('permission')){
        msg = '摄像头权限被拒绝，请前往设置开启';
      } else if(e.detail.errMsg.includes('not available')){
        msg = '摄像头不可用，请检查设备';
      }
    }
    wx.showModal({
      title: '摄像头错误',
      content: msg,
      confirmText: '去设置',
      success: (res) => {
        if(res.confirm){
          wx.openSetting();
        }
      }
    });
  },
  get currentHint(){
    const { livenessSteps, stepIndex } = this.data;
    return livenessSteps[Math.min(stepIndex, livenessSteps.length - 1)] || '';
  },
  canCapture(){
    const { stepIndex, livenessSteps } = this.data;
    return stepIndex >= livenessSteps.length;
  },
  onNextAction(){
    const { stepIndex, livenessSteps } = this.data;
    if (stepIndex < livenessSteps.length) {
      const nextIndex = stepIndex + 1;
      this.setData({ stepIndex: nextIndex }, () => {
        // 若所有动作完成，自动拍照
        if (nextIndex >= livenessSteps.length) {
          setTimeout(() => {
            this.onCapture();
          }, 600);
        }
      });
    }
  },
  async onCapture(){
    if (!this.canCapture()){
      wx.showToast({ title: '请先完成动作提示', icon: 'none' });
      return;
    }
    if(this.data.isCapturing){
      return; // 防止重复点击
    }
    this.setData({ isCapturing: true });
    wx.showLoading({ title: '拍照中...', mask: true });
    try{
      const ctx = wx.createCameraContext();
      const res = await new Promise((resolve, reject)=>{
        ctx.takePhoto({ 
          quality: 'high', 
          success: resolve, 
          fail: reject 
        });
      });
      // 临时文件需要及时处理，这里先保存路径
      // 注意：tempImagePath 仅在当前会话有效，需要尽快上传
      this.setData({ 
        photoPath: res.tempImagePath,
        isCapturing: false 
      });
      wx.hideLoading();
      wx.showToast({ title: '拍照成功', icon: 'success', duration: 1500 });
    }catch(err){
      this.setData({ isCapturing: false });
      wx.hideLoading();
      console.error('拍照失败:', err);
      let msg = '拍照失败，请重试';
      if(err.errMsg){
        if(err.errMsg.includes('permission')){
          msg = '摄像头权限被拒绝，请前往设置开启';
        } else if(err.errMsg.includes('not available')){
          msg = '摄像头不可用';
        }
      }
      wx.showToast({ title: msg, icon: 'none', duration: 2000 });
    }
  },
  onRetake(){
    this.setData({ photoPath: '' });
  },
  onSubmit(){
    if(!this.data.photoPath){
      wx.showToast({ title: '请先拍照', icon: 'none' });
      return;
    }
    // TODO: 上传并提交认证
    wx.showToast({ title: '已提交', icon: 'success' });
  }
});


