// pages/housekeeping-apply/housekeeping-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: {
      avatar: '',
      realName: '',
      gender: '',
      age: '',
      idCard: '',
      city: '',
      serviceArea: '',
      serviceTypes: [],
      workYears: '',
      healthCert: '',
      idFront: '',
      idBack: '',
      skillCert: '',
      introduction: '',
      phone: ''
    },
    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('/housekeeping/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' })
  },

  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 {
          const uploadRes = await api.uploadFile(tempFilePath, 'housekeeping')
          if (uploadRes.success) {
            const fieldMap = {
              'avatar': 'formData.avatar',
              'health': 'formData.healthCert',
              'idFront': 'formData.idFront',
              'idBack': 'formData.idBack',
              'skill': 'formData.skillCert'
            }
            this.setData({ [fieldMap[field]]: uploadRes.data.url })
            this.checkCanSubmit()
          }
        } catch (err) {
          wx.showToast({ title: '上传失败', icon: 'none' })
        } finally {
          wx.hideLoading()
        }
      }
    })
  },

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

  selectGender(e) {
    this.setData({ 'formData.gender': e.currentTarget.dataset.gender })
    this.checkCanSubmit()
  },

  toggleServiceType(e) {
    const type = e.currentTarget.dataset.type
    const serviceTypes = [...this.data.formData.serviceTypes]
    const index = serviceTypes.indexOf(type)
    if (index > -1) {
      serviceTypes.splice(index, 1)
    } else {
      serviceTypes.push(type)
    }
    this.setData({ 'formData.serviceTypes': serviceTypes })
    this.checkCanSubmit()
  },

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

  viewAgreement() {
    wx.navigateTo({ url: '/pages/agreement/agreement?code=housekeeping_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.serviceArea &&
      formData.serviceTypes.length > 0 &&
      formData.workYears &&
      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
    }

    wx.showLoading({ title: '提交中...' })
    try {
      const res = await api.request('/housekeeping/apply', {
        method: 'POST',
        data: {
          avatar: formData.avatar,
          realName: formData.realName,
          gender: formData.gender,
          age: age,
          idCard: formData.idCard,
          city: formData.city,
          serviceArea: formData.serviceArea,
          serviceTypes: formData.serviceTypes,
          workYears: parseInt(formData.workYears),
          healthCert: formData.healthCert,
          idFront: formData.idFront,
          idBack: formData.idBack,
          skillCert: formData.skillCert,
          introduction: formData.introduction,
          phone: formData.phone
        }
      })

      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()
    }
  }
})
