// pages/eldercare-apply/eldercare-apply.js
// 智慧养老申请页面
const api = require('../../utils/api')

Page({
    data: {
    statusBarHeight: 44,
    navBarHeight: 44,
    totalNavHeight: 88,
    showForm: true,
    applyStatus: 'none',
    statusTitle: '',
    statusDesc: '',
    isReapply: false,
    agreed: false,
    formData: {
      realName: '',
      city: '',
      phone: '',
      remarks: ''
    },
    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
    }

    try {
      const res = await api.request('/eldercare/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('获取申请状态失败:', err)
      this.setData({ applyStatus: 'none' })
    }
  },

  reapply() {
    this.setData({ isReapply: true, applyStatus: 'none' })
  },

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

  toggleAgreement() {
    this.setData({ agreed: !this.data.agreed })
    this.checkCanSubmit()
  },

  viewAgreement() {
    wx.navigateTo({ url: '/pages/agreement/agreement?code=cooperation_service' })
  },

  checkCanSubmit() {
    const { formData, agreed } = this.data
    
    const canSubmit = 
      formData.realName &&
      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
    }

    wx.showLoading({ title: '提交中...' })
    try {
      const res = await api.request('/eldercare/apply', {
        method: 'POST',
        data: {
          realName: formData.realName,
          city: formData.city,
          phone: formData.phone,
          remarks: formData.remarks
        }
      })

      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) {
      if (err.code === 404) {
        wx.showModal({
          title: '提示',
          content: '该服务申请即将开放，敬请期待！',
          showCancel: false,
          confirmColor: '#b06ab3'
        })
      } else {
        wx.showToast({ title: err.message || '提交失败', icon: 'none' })
      }
    } finally {
      wx.hideLoading()
    }
  }
})
