// pages/medical-apply/medical-apply.js
// 陪诊就医申请页面
const api = require('../../utils/api')

Page({
  data: {
    statusBarHeight: 44,
    navBarHeight: 44,
    totalNavHeight: 88,
    showForm: true,
    applyStatus: 'none', // none, pending, approved, rejected
    statusTitle: '',
    statusDesc: '',
    isReapply: false,
    agreed: false,
    formData: {
      avatar: '',
      realName: '',
      gender: '',
      age: '',
      idCard: '',
      city: '',
      hospital: '',
      healthCert: '',
      idFront: '',
      idBack: '',
      otherCert: '',
      introduction: '',
      phone: '',
      emergencyContact: '',
      emergencyPhone: ''
    },
    canSubmit: false
  },

  onLoad(options) {
    // 获取系统信息设置导航栏高度
    const systemInfo = wx.getSystemInfoSync()
    const statusBarHeight = systemInfo.statusBarHeight || 44
    const menuButton = wx.getMenuButtonBoundingClientRect()
    const navBarHeight = menuButton.height + (menuButton.top - statusBarHeight) * 2
    const totalNavHeight = statusBarHeight + navBarHeight
    
    this.setData({
      statusBarHeight,
      navBarHeight,
      totalNavHeight,
      isReapply: options.isReapply === 'true'
    })

    this.checkApplyStatus()
  },

  // 返回上一页
  goBack() {
    wx.navigateBack()
  },

  // 检查申请状态
  async checkApplyStatus() {
    const token = wx.getStorageSync('auth_token')
    if (!token) {
      this.setData({ applyStatus: 'none' })
      return
    }

    wx.showLoading({ title: '加载中...' })
    try {
      // 调用陪诊就医申请状态API（如果后端已实现）
      const res = await api.request('/medical/apply')
      
      if (res.success && res.data) {
        const data = res.data
        if (data.status === 'approved') {
          this.setData({
            applyStatus: 'approved',
            statusTitle: '申请已通过',
            statusDesc: '恭喜您成为陪诊师！'
          })
        } else if (data.status === 'pending') {
          this.setData({
            applyStatus: 'pending',
            statusTitle: '审核中',
            statusDesc: '您的申请正在审核中，请耐心等待'
          })
        } else if (data.status === 'rejected') {
          this.setData({
            applyStatus: 'rejected',
            statusTitle: '申请未通过',
            statusDesc: data.rejectReason || '很抱歉，您的申请未通过审核'
          })
        }
      }
    } catch (err) {
      console.log('获取申请状态失败，可能API未实现:', err)
      this.setData({ applyStatus: 'none' })
    } finally {
      wx.hideLoading()
    }
  },

  // 重新申请
  reapply() {
    this.setData({ 
      isReapply: true,
      applyStatus: 'none'
    })
  },

  // 选择头像
  chooseAvatar() {
    this.doChooseMedia('avatar')
  },

  // 上传证书
  uploadCert(e) {
    const type = e.currentTarget.dataset.type
    this.doChooseMedia(type)
  },

  // 选择媒体文件
  doChooseMedia(field) {
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sourceType: ['album', 'camera'],
      success: async (res) => {
        const tempFilePath = res.tempFiles[0].tempFilePath
        wx.showLoading({ title: '上传中...' })
        
        try {
          // 1. 自动压缩图片
          const compressed = await wx.compressImage({
            src: tempFilePath,
            quality: 80
          }).catch(err => {
            console.warn('压缩图片失败:', err)
            return { tempFilePath }
          })

          // 2. 上传到服务器，使用允许的目录 'image'
          const uploadRes = await api.uploadFile(compressed.tempFilePath, 'image')
          
          if (uploadRes.success && uploadRes.data) {
            const fieldMap = {
              'avatar': 'formData.avatar',
              'idFront': 'formData.idFront',
              'idBack': 'formData.idBack',
              'healthCert': 'formData.healthCert',
              'otherCert': 'formData.otherCert'
            }
            
            this.setData({ 
              [fieldMap[field]]: uploadRes.data.url 
            })
            this.checkCanSubmit()
            
            wx.showToast({ title: '上传成功', icon: 'success' })
          } else {
            wx.showToast({ 
              title: uploadRes.message || '上传失败', 
              icon: 'none' 
            })
          }
        } catch (err) {
          console.error('上传过程出错:', err)
          wx.showToast({ 
            title: err.message || '上传出错', 
            icon: 'none' 
          })
        } finally {
          wx.hideLoading()
        }
      }
    })
  },

  // 输入变化
  onInputChange(e) {
    const field = e.currentTarget.dataset.field
    const value = e.detail.value
    this.setData({
      [`formData.${field}`]: value
    })
    this.checkCanSubmit()
  },

  // 选择性别
  selectGender(e) {
    const gender = e.currentTarget.dataset.gender
    this.setData({
      'formData.gender': gender
    })
    this.checkCanSubmit()
  },

  // 切换协议同意状态
  toggleAgreement() {
    this.setData({
      agreed: !this.data.agreed
    })
    this.checkCanSubmit()
  },

  // 查看协议
  viewAgreement() {
    wx.navigateTo({
      url: '/pages/agreement/agreement?code=medical_service'
    })
  },

  // 检查是否可以提交
  checkCanSubmit() {
    const { formData, agreed } = this.data
    
    // 验证身份证号格式
    const idCardValid = /^[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]$/.test(formData.idCard)
    
    const canSubmit = 
      formData.realName &&
      formData.gender &&
      formData.age &&
      formData.idCard && idCardValid &&
      formData.city &&
      formData.hospital &&
      formData.healthCert &&
      formData.idFront &&
      formData.idBack &&
      formData.introduction &&
      formData.introduction.length >= 50 &&
      formData.phone &&
      formData.phone.length === 11 &&
      agreed
    
    this.setData({ canSubmit })
  },

  // 提交申请
  async submitApply() {
    if (!this.data.canSubmit) return

    const { formData } = this.data

    // 验证手机号
    if (!/^1[3-9]\d{9}$/.test(formData.phone)) {
      wx.showToast({ title: '请输入正确的手机号', icon: 'none' })
      return
    }

    // 验证年龄
    const age = parseInt(formData.age)
    if (age < 18 || age > 60) {
      wx.showToast({ title: '年龄需在18-60岁之间', icon: 'none' })
      return
    }

    // 验证身份证号
    if (!/^[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]$/.test(formData.idCard)) {
      wx.showToast({ title: '请输入正确的身份证号', icon: 'none' })
      return
    }

    wx.showLoading({ title: '提交中...' })
    try {
      const res = await api.request('/medical/apply', {
        method: 'POST',
        data: {
          avatar: formData.avatar,
          realName: formData.realName,
          gender: formData.gender,
          age: age,
          idCard: formData.idCard,
          city: formData.city,
          hospital: formData.hospital,
          healthCert: formData.healthCert,
          idFront: formData.idFront,
          idBack: formData.idBack,
          otherCert: formData.otherCert,
          introduction: formData.introduction,
          phone: formData.phone,
          emergencyContact: formData.emergencyContact,
          emergencyPhone: formData.emergencyPhone
        }
      })

      if (res.success || res.code === 0) {
        wx.showToast({ title: '申请已提交', icon: 'success' })
        this.setData({
          applyStatus: 'pending',
          statusTitle: '审核中',
          statusDesc: '您的申请正在审核中，请耐心等待',
          isReapply: false
        })
      } else {
        wx.showToast({ title: res.message || '提交失败', icon: 'none' })
      }
    } catch (err) {
      console.error('提交申请失败:', err)
      // 如果API未实现，显示提示
      if (err.code === 404 || err.message?.includes('not found')) {
        wx.showModal({
          title: '提示',
          content: '陪诊就医服务即将开放，敬请期待！',
          showCancel: false,
          confirmText: '我知道了',
          confirmColor: '#b06ab3'
        })
      } else {
        wx.showToast({ title: err.message || '提交失败', icon: 'none' })
      }
    } finally {
      wx.hideLoading()
    }
  }
})
