// pages/policies/policies.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 当前激活的标签
    activeTab: 'all',
    
    // 保单列表
    policiesList: [],
    
    // 过滤后的保单列表
    filteredPolicies: [],
    
    // 统计数据
    stats: {
      totalPolicies: 0,
      activePolicies: 0,
      expiringPolicies: 0
    },
    
    // 加载状态
    loading: false,
    
    // 是否有更多数据
    hasMore: true,
    
    // 当前页码
    currentPage: 1
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log('我的保单页加载', options)
    this.loadPoliciesList()
  },

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

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    console.log('我的保单页显示')
    this.loadPoliciesList()
  },

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

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

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    console.log('下拉刷新')
    this.setData({
      currentPage: 1,
      hasMore: true
    })
    this.loadPoliciesList()
    wx.stopPullDownRefresh()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    console.log('上拉触底')
    if (this.data.hasMore && !this.data.loading) {
      this.loadMore()
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    return {
      title: '我的保单',
      path: '/pages/policies/policies',
      imageUrl: '/static/images/share-policies.jpg'
    }
  },

  /**
   * 加载保单列表
   */
  loadPoliciesList() {
    this.setData({ loading: true })
    
    console.log('加载保单列表')
    
    // 模拟API调用
    setTimeout(() => {
      const mockPolicies = this.getMockPolicies()
      this.setData({
        policiesList: mockPolicies,
        filteredPolicies: this.filterPolicies(mockPolicies, this.data.activeTab),
        stats: this.calculateStats(mockPolicies),
        loading: false
      })
    }, 1000)
  },

  /**
   * 获取模拟保单数据
   */
  getMockPolicies() {
    return [
      {
        id: '1',
        name: '综合意外伤害保险',
        description: '全面保障，安心出行',
        status: 'active',
        statusText: '有效',
        policyNo: 'POL20240115001',
        coverageAmount: 50,
        premium: 299,
        effectiveDate: '2024-01-15',
        expiryDate: '2025-01-15'
      },
      {
        id: '2',
        name: '重大疾病保险',
        description: '重疾保障，守护健康',
        status: 'active',
        statusText: '有效',
        policyNo: 'POL20240110002',
        coverageAmount: 30,
        premium: 1200,
        effectiveDate: '2024-01-10',
        expiryDate: '2025-01-10'
      },
      {
        id: '3',
        name: '定期寿险',
        description: '家庭保障，责任担当',
        status: 'expiring',
        statusText: '即将到期',
        policyNo: 'POL20231201003',
        coverageAmount: 100,
        premium: 800,
        effectiveDate: '2023-12-01',
        expiryDate: '2024-12-01'
      },
      {
        id: '4',
        name: '医疗保险',
        description: '医疗费用，安心报销',
        status: 'expired',
        statusText: '已过期',
        policyNo: 'POL20221101004',
        coverageAmount: 20,
        premium: 500,
        effectiveDate: '2022-11-01',
        expiryDate: '2023-11-01'
      },
      {
        id: '5',
        name: '车险',
        description: '车辆保障，出行无忧',
        status: 'active',
        statusText: '有效',
        policyNo: 'POL20240120005',
        coverageAmount: 200,
        premium: 3000,
        effectiveDate: '2024-01-20',
        expiryDate: '2025-01-20'
      }
    ]
  },

  /**
   * 过滤保单列表
   */
  filterPolicies(policies, status) {
    if (status === 'all') {
      return policies
    }
    return policies.filter(policy => policy.status === status)
  },

  /**
   * 计算统计数据
   */
  calculateStats(policies) {
    const totalPolicies = policies.length
    const activePolicies = policies.filter(policy => policy.status === 'active').length
    const expiringPolicies = policies.filter(policy => policy.status === 'expiring').length
    
    return {
      totalPolicies,
      activePolicies,
      expiringPolicies
    }
  },

  /**
   * 切换标签
   */
  switchTab(e) {
    const tab = e.currentTarget.dataset.tab
    console.log('切换标签:', tab)
    
    this.setData({
      activeTab: tab,
      filteredPolicies: this.filterPolicies(this.data.policiesList, tab)
    })
  },

  /**
   * 跳转到保单详情
   */
  goToPolicyDetail(e) {
    const policyId = e.currentTarget.dataset.id
    console.log('跳转到保单详情:', policyId)
    wx.navigateTo({
      url: `/pages/policy-detail/policy-detail?id=${policyId}`
    })
  },

  /**
   * 跳转到新保单投保
   */
  goToNewPolicy() {
    console.log('跳转到新保单投保')
    wx.switchTab({
      url: '/pages/products/products'
    })
  },

  /**
   * 跳转到续保
   */
  goToRenewal(e) {
    const policyId = e.currentTarget.dataset.id
    console.log('跳转到续保:', policyId)
    wx.navigateTo({
      url: `/pages/renewal/renewal?policyId=${policyId}`
    })
  },

  /**
   * 跳转到理赔申请
   */
  goToClaim(e) {
    const policyId = e.currentTarget.dataset.id
    console.log('跳转到理赔申请:', policyId)
    wx.navigateTo({
      url: `/pages/claims/claims?policyId=${policyId}`
    })
  },

  /**
   * 加载更多
   */
  loadMore() {
    if (this.data.loading || !this.data.hasMore) return
    
    this.setData({ loading: true })
    
    console.log('加载更多保单数据')
    
    // 模拟加载更多数据
    setTimeout(() => {
      const newPolicies = this.getMockPolicies().map((policy, index) => ({
        ...policy,
        id: (this.data.policiesList.length + index + 1).toString(),
        policyNo: 'POL' + (Date.now() + index),
        effectiveDate: this.formatDate(new Date(Date.now() - Math.random() * 365 * 24 * 60 * 60 * 1000)),
        expiryDate: this.formatDate(new Date(Date.now() + Math.random() * 365 * 24 * 60 * 60 * 1000))
      }))
      
      const updatedPolicies = [...this.data.policiesList, ...newPolicies]
      
      this.setData({
        policiesList: updatedPolicies,
        filteredPolicies: this.filterPolicies(updatedPolicies, this.data.activeTab),
        stats: this.calculateStats(updatedPolicies),
        loading: false,
        hasMore: updatedPolicies.length < 20 // 模拟最多20条数据
      })
    }, 1000)
  },

  /**
   * 格式化日期
   */
  formatDate(date) {
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    
    return `${year}-${month}-${day}`
  }
})