<template>
  <view class="auth-container">
    <!-- 导航栏 -->
    <view class="nav-bar">
      <view class="back-btn" @click="navigateBack">
        <image src="/src/static/pic/mark/more-left.png" mode="aspectFit"></image>
      </view>
      <view class="title">{{ $t('realauth.realauthtitle') }}</view>
      <view class="right-placeholder"></view>
    </view>

    <!-- 表单区域 -->
    <view class="form-container">
      <!-- 姓名输入 -->
      <view class="form-item">
        <text class="label">{{ $t('realauth.realname') }}</text>
        <input 
          class="input" 
          type="text" 
          v-model="realName" 
          :placeholder="$t('realauth.realnameplaceholder')" 
          placeholder-class="placeholder"
        />
      </view>

      <!-- 身份证号输入 -->
      <view class="form-item">
        <text class="label">{{ $t('realauth.IDcardnum') }}</text>
        <input 
          class="input" 
          type="idcard" 
          v-model="idCardNumber" 
          :placeholder="$t('realauth.IDcardnumplaceholder')" 
          placeholder-class="placeholder"
          maxlength="18"
          @input="formatIdCard"
        />
      </view>

      <!-- 身份证正面 -->
      <view class="form-item">
        <text class="label">{{ $t('realauth.IDcardfront') }}</text>
        <view class="upload-area" @click="chooseImage('front')">
          <image 
            v-if="idCardFront" 
            :src="idCardFront" 
            class="id-card-image"
            mode="aspectFill"
          ></image>
          <view v-else class="upload-placeholder">
            <image src="/static/images/camera.png" class="camera-icon"></image>
            <text class="upload-text">{{ $t('realauth.uploadIDcardfront') }}</text>
            <text class="upload-tip">{{ $t('realauth.uploadIDcardfronttips') }}</text>
          </view>
        </view>
      </view>

      <!-- 身份证反面 -->
      <view class="form-item">
        <text class="label">{{ $t('realauth.IDcardback') }}</text>
        <view class="upload-area" @click="chooseImage('back')">
          <image 
            v-if="idCardBack" 
            :src="idCardBack" 
            class="id-card-image"
            mode="aspectFill"
          ></image>
          <view v-else class="upload-placeholder">
            <image src="/static/images/camera.png" class="camera-icon"></image>
            <text class="upload-text">{{ $t('realauth.uploadIDcardback') }}</text>
            <text class="upload-tip">{{ $t('realauth.uploadIDcardbacktips') }}</text>
          </view>
        </view>
      </view>

      <!-- 手持身份证照片 -->
      <view class="form-item">
        <text class="label">{{ $t('realauth.handleIDcardphoto') }}</text>
        <view class="upload-area" @click="chooseImage('handheld')">
          <image 
            v-if="handheldPhoto" 
            :src="handheldPhoto" 
            class="id-card-image"
            mode="aspectFill"
          ></image>
          <view v-else class="upload-placeholder">
            <image src="/static/images/camera.png" class="camera-icon"></image>
            <text class="upload-text">{{ $t('realauth.uploadIDcardhandle') }}</text>
            <text class="upload-tip">{{ $t('realauth.uploadIDcardhandletips') }}</text>
          </view>
        </view>
      </view>

      <!-- 错误提示 -->
      <view class="error-message" v-if="errorMessage">
        {{ errorMessage }}
      </view>

      <!-- 提交按钮 -->
      <button 
        class="submit-btn" 
        @click="submitAuth" 
        :disabled="isSubmitting"
      >
        <text v-if="!isSubmitting">{{$t('realauth.submitrealauth')}}</text>
        <text v-else>{{$t('realauth.submitting')}}</text>
      </button>

      <!-- 认证提示 -->
      <view class="auth-tips">
        <text class="tip-title">{{$t('realauth.realauthtips')}}</text>
        <text class="tip-item">{{$t('realauth.firsttips')}}</text>
        <text class="tip-item">{{$t('realauth.secondtips')}}</text>
        <text class="tip-item">{{$t('realauth.thirdtips')}}</text>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      realName: '',
      idCardNumber: '',
      idCardFront: '',
      idCardBack: '',
      handheldPhoto: '',
      errorMessage: '',
      isSubmitting: false
    }
  },
  methods: {
    navigateBack() {
      uni.navigateBack()
    },
    
    // 格式化身份证输入（自动转换小写x为大写X）
    formatIdCard() {
      if (this.idCardNumber && this.idCardNumber.length > 0) {
        const lastChar = this.idCardNumber.slice(-1)
        if (lastChar === 'x') {
          this.idCardNumber = this.idCardNumber.slice(0, -1) + 'X'
        }
      }
    },
    
    // 选择图片
    chooseImage(type) {
      uni.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          const tempFilePath = res.tempFilePaths[0]
          
          // 这里可以添加图片压缩处理
          this.compressImage(tempFilePath).then(compressedPath => {
            switch(type) {
              case 'front':
                this.idCardFront = compressedPath
                break
              case 'back':
                this.idCardBack = compressedPath
                break
              case 'handheld':
                this.handheldPhoto = compressedPath
                break
            }
          })
        },
        fail: (err) => {
          console.error('选择图片失败:', err)
          uni.showToast({
            title: this.$t('IDcard.selectpicfailed'),
            icon: 'none'
          })
        }
      })
    },
    
    // 图片压缩
    compressImage(tempFilePath) {
      return new Promise((resolve) => {
        // 实际项目中可以使用uni.compressImage API
        // 这里简单返回原路径模拟压缩
        resolve(tempFilePath)
        
        /* 实际压缩代码示例：
        uni.compressImage({
          src: tempFilePath,
          quality: 80,
          success: res => {
            resolve(res.tempFilePath)
          },
          fail: () => {
            resolve(tempFilePath) // 压缩失败返回原图
          }
        })
        */
      })
    },
    
    // 验证表单
    validateForm() {
      if (!this.realName || this.realName.trim() === '') {
        this.errorMessage = this.$t('realauth.inputrealname')
        return false
      }
      
      if (!this.idCardNumber || this.idCardNumber.trim() === '') {
        this.errorMessage = this.$t('realauth.inputnumber')
        return false
      }
      
      const idReg = /^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dXx]$/
      if (!idReg.test(this.idCardNumber)) {
        this.errorMessage = this.$t('realauth.errors.invalidIdCard')
        return false
      }
      
      if (!this.idCardFront) {
        this.errorMessage = this.$t('realauth.errors.idCardFront')
        return false
      }
      
      if (!this.idCardBack) {
        this.errorMessage = this.$t('realauth.errors.idCardBack')
        return false
      }
      
      if (!this.handheldPhoto) {
        this.errorMessage = this.$t('realauth.errors.handheldPhoto')
        return false
      }
      
      this.errorMessage = ''
      return true
    },
    
    // 提交认证
    submitAuth() {
      if (!this.validateForm()) return
      
      this.isSubmitting = true
      
      // 模拟API请求
      setTimeout(() => {
        uni.showToast({
          title: '实名认证提交成功',
          icon: 'success'
        })
        
        setTimeout(() => {
          uni.navigateBack()
        }, 1500)
        
        this.isSubmitting = false
      }, 2000)
      
      /* 
      实际项目中应该这样上传：
      const uploadTasks = [
        this.uploadFile(this.idCardFront, 'front'),
        this.uploadFile(this.idCardBack, 'back'),
        this.uploadFile(this.handheldPhoto, 'handheld')
      ]
      
      Promise.all(uploadTasks).then(results => {
        const [frontUrl, backUrl, handheldUrl] = results
        
        uni.request({
          url: '/api/user/realAuth',
          method: 'POST',
          data: {
            realName: this.realName,
            idCardNumber: this.idCardNumber,
            idCardFront: frontUrl,
            idCardBack: backUrl,
            handheldPhoto: handheldUrl
          },
          success: (res) => {
            if (res.data.code === 200) {
              uni.showToast({ title: '认证成功' })
              // 跳转或返回
            } else {
              this.errorMessage = res.data.message || '认证失败'
            }
          },
          fail: (err) => {
            this.errorMessage = '网络错误，请重试'
          },
          complete: () => {
            this.isSubmitting = false
          }
        })
      }).catch(err => {
        this.errorMessage = '图片上传失败'
        this.isSubmitting = false
      })
      */
    },
    
    // 实际文件上传方法
    uploadFile(filePath, type) {
      return new Promise((resolve, reject) => {
        uni.uploadFile({
          url: '/api/upload',
          filePath,
          name: 'file',
          formData: { type },
          success: (res) => {
            const data = JSON.parse(res.data)
            if (data.code === 200) {
              resolve(data.data.url)
            } else {
              reject(new Error(data.message))
            }
          },
          fail: (err) => {
            reject(err)
          }
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.auth-container {
  padding: 0;
  min-height: 100vh;
  background-color: #f5f5f5;
}

/* 导航栏样式 */
.nav-bar {
  display: flex;
  align-items: center;
  height: 100rpx;
  padding: 0 30rpx;
  padding-top: var(--status-bar-height);
  position: relative;
  background-color: #fff;
  border-bottom: 1rpx solid #f0f0f0;
  
  .back-btn {
    width: 40rpx;
    height: 40rpx;
    display: flex;
    align-items: center;
    justify-content: flex-start;
    position: relative;
    
    image {
      width: 100%;
      height: 100%;
      filter: invert(1);
    }
  }
  
  .title {
    position: absolute;
    left: 0;
    right: 0;
    text-align: center;
    font-size: 36rpx;
    font-weight: bold;
    color: #333;
    line-height: 88rpx;
    z-index: 1;
    pointer-events: none;
  }
  
  .right-placeholder {
    width: 40rpx;
    margin-left: auto;
  }
}

.form-container {
  padding: 30rpx;
}

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

.label {
  display: block;
  font-size: 28rpx;
  color: #333;
  margin-bottom: 20rpx;
  font-weight: 500;
}

.input {
  height: 80rpx;
  background-color: #fff;
  border-radius: 8rpx;
  padding: 0 20rpx;
  font-size: 28rpx;
  border: 1rpx solid #eee;
}

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

/* 上传区域样式 */
.upload-area {
  height: 300rpx;
  background-color: #fff;
  border-radius: 8rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1rpx dashed #ccc;
  overflow: hidden;
  
  .id-card-image {
    width: 100%;
    height: 100%;
  }
}

.upload-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  
  .camera-icon {
    width: 80rpx;
    height: 80rpx;
    margin-bottom: 20rpx;
  }
  
  .upload-text {
    font-size: 28rpx;
    color: #333;
    margin-bottom: 10rpx;
  }
  
  .upload-tip {
    font-size: 24rpx;
    color: #999;
  }
}

.error-message {
  color: #ff4d4f;
  font-size: 26rpx;
  margin-bottom: 30rpx;
  text-align: center;
}

.submit-btn {
  margin-top: 60rpx;
  background-color: #007aff;
  color: #fff;
  height: 88rpx;
  line-height: 88rpx;
  border-radius: 44rpx;
  font-size: 32rpx;
  
  &:disabled {
    background-color: #b3d4fc;
  }
}

/* 认证提示 */
.auth-tips {
  margin-top: 60rpx;
  padding: 30rpx;
  background-color: #f9f9f9;
  border-radius: 8rpx;
  
  .tip-title {
    display: block;
    font-size: 28rpx;
    color: #333;
    font-weight: bold;
    margin-bottom: 20rpx;
  }
  
  .tip-item {
    display: block;
    font-size: 24rpx;
    color: #666;
    margin-bottom: 15rpx;
    line-height: 1.6;
    
    &:before {
      content: "•";
      margin-right: 10rpx;
    }
  }
}
</style>