const app = getApp();
Page({
  data: {
    images: {
      background: '/static_file/background.png',
      water: '/static_file/water.png'
    },
    userInfo: {
      name: app.globalData.currentAccountInfo.username,
      id:  app.globalData.currentAccountInfo.usernumber,
      address: app.globalData.currentAccountInfo.address
    },
    showKeyboard: false,
    selectedAmount: null,
    customAmount: '',
    inputFocus: false,
    address: '',
    paymentList: [],
    showYearPicker: false,
    years: [],
    yearPickerValue: [0],
    selectedYear: '',
    originalBillList: [], // 存储原始账单数据
  },
  onShow: function() {
    this.updateUserInfo();
  },
  
  // 更新用户信息的方法
  updateUserInfo: function() {
    this.setData({
      userInfo: {
        name: app.globalData.currentAccountInfo.username,
        id: app.globalData.currentAccountInfo.usernumber,
        address: app.globalData.currentAccountInfo.address
      }
    });
  },
  
  onLoad: function(options) {
    // 确保图片资源正确加载
    this.setData({
      images: {
        background: '/static_file/background.png',
        water: '/static_file/water.png'
      },
      isInvoic: app.globalData.waterCompanys.filter(data=>data.id==app.globalData.currentAccountInfo.dsKey)[0].swCompanyInfo.supportonlineinvoice=="1"
    });
    // 生成近20年的年份数据
    this.generateYears();
    // 获取缴费记录列表
    this.getBillList().then(data => {
      this.setData({
        paymentList: data,
        originalBillList: data
      });
    });
    this.updateUserInfo();
  },

  // 添加日期格式化函数
  formatDateTime: function(dateString) {
    if (!dateString) return '';
    const date = new Date(dateString);
    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    const day = date.getDate().toString().padStart(2, '0');
    const hours = date.getHours().toString().padStart(2, '0');
    const minutes = date.getMinutes().toString().padStart(2, '0');
    return `${year}-${month}-${day} ${hours}:${minutes}`;
  },

  getBillList: function() {
    const _this = this;
    return new Promise((resolve, reject) => {
      wx.showLoading({
        title: '获取中...',
        mask: true,
      });
      wx.request({
        url: app.globalData.interfaceUrls.paymentList,
        method: 'POST',
        data: {
          accountNum: app.globalData.currentAccountInfo.usernumber,
          year: new Date().getFullYear()
        },
        header: {
          'content-type': 'application/json',
          'token': app.globalData.userWxInfo.token,
          'source': "wc",
          '!SAAS_LOGIN_TOKEN_!': app.globalData.currentAccountInfo.dsKey
        },
        
        success(res) {
          wx.hideLoading();
          let apiReturnData = res.data;
          // 格式化日期
          if (apiReturnData.data && Array.isArray(apiReturnData.data)) {
            apiReturnData.data = apiReturnData.data.map(item => ({
              ...item,
              chargedate: _this.formatDateTime(item.chargedate)
            }));
          }
          _this.setData({
            paymentList: apiReturnData.data,
          });
          resolve(apiReturnData.data);
        },
        fail(error) {
          wx.hideLoading();
          utils.simleInfo('获取账单失败，请稍后再试');
          reject(error);
        }
      });
    });
  },

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


  // 切换到首页
  goToHome: function() {
    wx.switchTab({
      url: '/pages/homepage/homepage',
    });
  },

  // 切换到我的页面
  goToMine: function() {
    wx.switchTab({
      url: '/pages/mine/mine',
    });
  },

  navigateToHome() {
    wx.switchTab({
      url: '/pages/index/index'
    })
  },

  navigateToMine() {
    wx.switchTab({
      url: '/pages/mine/mine'
    })
  },

  // 跳转到账单详情页面
  goToDetail: function(e) {
    const billDetail = e.currentTarget.dataset.bill || {};
    // 使用JSON.stringify传递完整账单数据
    wx.navigateTo({
      url: `/pages/jiaofeixiangqing/jiaofeixiangqing?billInfo=${encodeURIComponent(JSON.stringify(billDetail))}`
    });
  },

  // 生成近20年的年份数据
  generateYears: function() {
    const currentYear = new Date().getFullYear();
    let years = ['全部']; // 添加"全部"选项
    
    for (let i = 0; i < 20; i++) {
      years.push(String(currentYear - i));
    }
    
    this.setData({
      years: years,
      yearPickerValue: [0] // 默认选中"全部"
    });
  },
  
  // 显示年份选择器
  showYearPicker: function() {
    this.setData({
      showYearPicker: true
    });
  },
  
  // 隐藏年份选择器
  hideYearPicker: function() {
    this.setData({
      showYearPicker: false
    });
  },
  
  // 防止点击选择器内部时关闭选择器
  preventBubble: function() {
    return;
  },
  
  // 年份选择改变
  onYearChange: function(e) {
    const index = e.detail.value[0];
    this.setData({
      yearPickerValue: [index]
    });
  },
  
  // 确认年份选择
  confirmYearSelection: function() {
    const selectedIndex = this.data.yearPickerValue[0];
    const selectedYear = this.data.years[selectedIndex];
    
    this.setData({
      selectedYear: selectedYear === '全部' ? '' : selectedYear,
      showYearPicker: false
    });
    
    // 根据选择的年份筛选账单
    this.filterBillsByYear();
  },
  
  // 修改年份筛选功能
  filterBillsByYear: function() {
    const { selectedYear, originalBillList } = this.data;
    
    if (!selectedYear) {
      // 重新获取所有数据
      this.getBillList();
      return;
    }
    
    // 通过接口重新获取指定年份的数据
    wx.showLoading({
      title: '获取中...',
      mask: true,
    });
    wx.request({
      url: app.globalData.interfaceUrls.paymentList,
      method: 'POST',
      data: {
        accountNum: app.globalData.currentAccountInfo.usernumber,
        year: selectedYear
      },
      header: {
        'content-type': 'application/json',
        'token': app.globalData.userWxInfo.token,
        'source': "wc",
        '!SAAS_LOGIN_TOKEN_!': app.globalData.currentAccountInfo.dsKey
      },
      success: (res) => {
        wx.hideLoading();
        let apiReturnData = res.data;
        if (apiReturnData.data && Array.isArray(apiReturnData.data)) {
          apiReturnData.data = apiReturnData.data.map(item => ({
            ...item,
            chargedate: this.formatDateTime(item.chargedate)
          }));
        }
        this.setData({
          paymentList: apiReturnData.data
        });
      },
      fail: () => {
        wx.hideLoading();
        wx.showToast({
          title: '获取数据失败',
          icon: 'none'
        });
      }
    });
  }
})
