// pages/application/application.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 产品ID
    productId: '',
    
    // 产品信息
    productInfo: {},
    
    // 表单数据
    formData: {
      insuredName: '',
      idCard: '',
      phone: '',
      gender: '',
      birthDate: '',
      beneficiaryRelationIndex: 0,
      beneficiaryName: '',
      coverageAmount: 10,
      paymentMethod: 'annual',
      healthAnswers: []
    },
    
    // 受益人关系选项
    beneficiaryRelations: [
      '本人',
      '配偶',
      '子女',
      '父母',
      '兄弟姐妹',
      '其他'
    ],
    
    // 保险金额选项
    coverageAmounts: [10, 20, 30, 50, 100],
    
    // 健康告知问题
    healthQuestions: [
      {
        question: '您是否患有或曾经患有恶性肿瘤、白血病、淋巴瘤等恶性疾病？'
      },
      {
        question: '您是否患有或曾经患有心脏病、心肌梗塞、冠心病、高血压等心血管疾病？'
      },
      {
        question: '您是否患有或曾经患有糖尿病、甲状腺疾病、肾病等内分泌或代谢疾病？'
      },
      {
        question: '您是否患有或曾经患有肝炎、肝硬化、肝癌等肝脏疾病？'
      },
      {
        question: '您是否患有或曾经患有精神疾病、癫痫、帕金森病等神经系统疾病？'
      }
    ],
    
    // 计算出的保费
    calculatedPremium: 0,
    
    // 是否同意协议
    agreeTerms: false,
    
    // 是否可以提交
    canSubmit: false,
    
    // 加载状态
    loading: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log('投保申请页加载', options)
    const { productId } = options
    if (productId) {
      this.setData({ productId })
      this.loadProductInfo(productId)
    } else {
      wx.showToast({
        title: '产品ID不能为空',
        icon: 'none'
      })
      setTimeout(() => {
        wx.navigateBack()
      }, 1500)
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    console.log('投保申请页渲染完成')
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    console.log('投保申请页显示')
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    console.log('投保申请页隐藏')
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    console.log('投保申请页卸载')
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    console.log('下拉刷新')
    this.loadProductInfo(this.data.productId)
    wx.stopPullDownRefresh()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    console.log('上拉触底')
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    return {
      title: '保险投保申请',
      path: `/pages/application/application?productId=${this.data.productId}`,
      imageUrl: '/static/images/share-application.jpg'
    }
  },

  /**
   * 加载产品信息
   */
  loadProductInfo(productId) {
    console.log('加载产品信息:', productId)
    
    // 模拟产品信息
    const mockProduct = {
      id: productId,
      name: '综合意外伤害保险',
      subtitle: '全面保障，安心出行',
      image: '/static/images/product-1.jpg',
      minPremium: 99,
      insurancePeriod: '1年'
    }
    
    this.setData({ productInfo: mockProduct })
    this.calculatePremium()
  },

  /**
   * 被保险人姓名输入
   */
  onInsuredNameInput(e) {
    this.setData({
      'formData.insuredName': e.detail.value
    })
    this.validateForm()
  },

  /**
   * 身份证号输入
   */
  onIdCardInput(e) {
    this.setData({
      'formData.idCard': e.detail.value
    })
    this.validateForm()
  },

  /**
   * 手机号输入
   */
  onPhoneInput(e) {
    this.setData({
      'formData.phone': e.detail.value
    })
    this.validateForm()
  },

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

  /**
   * 出生日期选择
   */
  onBirthDateChange(e) {
    this.setData({
      'formData.birthDate': e.detail.value
    })
    this.validateForm()
  },

  /**
   * 受益人关系选择
   */
  onBeneficiaryRelationChange(e) {
    this.setData({
      'formData.beneficiaryRelationIndex': e.detail.value
    })
  },

  /**
   * 受益人姓名输入
   */
  onBeneficiaryNameInput(e) {
    this.setData({
      'formData.beneficiaryName': e.detail.value
    })
  },

  /**
   * 选择保险金额
   */
  selectCoverageAmount(e) {
    const amount = parseInt(e.currentTarget.dataset.amount)
    this.setData({
      'formData.coverageAmount': amount
    })
    this.calculatePremium()
  },

  /**
   * 选择缴费方式
   */
  selectPaymentMethod(e) {
    const method = e.currentTarget.dataset.method
    this.setData({
      'formData.paymentMethod': method
    })
    this.calculatePremium()
  },

  /**
   * 选择健康告知答案
   */
  selectHealthAnswer(e) {
    const { index, answer } = e.currentTarget.dataset
    const healthAnswers = [...this.data.formData.healthAnswers]
    healthAnswers[index] = answer
    
    this.setData({
      'formData.healthAnswers': healthAnswers
    })
    this.validateForm()
  },

  /**
   * 协议同意状态改变
   */
  onAgreeTermsChange(e) {
    this.setData({
      agreeTerms: e.detail.value
    })
    this.validateForm()
  },

  /**
   * 计算保费
   */
  calculatePremium() {
    const { coverageAmount, paymentMethod } = this.data.formData
    const { minPremium } = this.data.productInfo
    
    // 简单的保费计算逻辑
    let basePremium = minPremium * (coverageAmount / 10)
    if (paymentMethod === 'monthly') {
      basePremium = basePremium / 12
    }
    
    this.setData({
      calculatedPremium: Math.round(basePremium)
    })
  },

  /**
   * 验证表单
   */
  validateForm() {
    const { formData } = this.data
    const { agreeTerms } = this.data
    
    // 验证必填字段
    const requiredFields = [
      formData.insuredName,
      formData.idCard,
      formData.phone,
      formData.gender,
      formData.birthDate
    ]
    
    const isFormValid = requiredFields.every(field => field && field.trim() !== '')
    
    // 验证健康告知是否全部回答
    const healthAnswersComplete = this.data.healthQuestions.length === formData.healthAnswers.length &&
      formData.healthAnswers.every(answer => answer !== undefined && answer !== '')
    
    // 验证身份证号格式
    const idCardValid = /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/.test(formData.idCard)
    
    // 验证手机号格式
    const phoneValid = /^1[3-9]\d{9}$/.test(formData.phone)
    
    const canSubmit = isFormValid && healthAnswersComplete && idCardValid && phoneValid && agreeTerms
    
    this.setData({ canSubmit })
  },

  /**
   * 提交投保申请
   */
  submitApplication() {
    const { canSubmit, loading } = this.data
    
    if (!canSubmit || loading) return
    
    this.setData({ loading: true })
    
    console.log('提交投保申请:', this.data.formData)
    
    // 模拟提交申请
    setTimeout(() => {
      this.setData({ loading: false })
      
      wx.showToast({
        title: '申请提交成功',
        icon: 'success'
      })
      
      // 跳转到申请结果页面
      setTimeout(() => {
        wx.redirectTo({
          url: `/pages/application-result/application-result?productId=${this.data.productId}&status=success`
        })
      }, 1500)
      
    }, 2000)
  },

  /**
   * 跳转到条款页面
   */
  goToTerms() {
    console.log('跳转到条款页面')
    wx.navigateTo({
      url: '/pages/terms/terms'
    })
  },

  /**
   * 跳转到隐私政策页面
   */
  goToPrivacy() {
    console.log('跳转到隐私政策页面')
    wx.navigateTo({
      url: '/pages/privacy/privacy'
    })
  }
})