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: '',
    billList: [],
    // 是否可以开票
    isInvoic:false,
    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({
        billList: data,
        originalBillList: data
      });
    });
    this.updateUserInfo();
  },

  getBillList: function() {
    const _this = this;
    return new Promise((resolve, reject) => {
      wx.showLoading({
        title: '获取中...',
        mask: true,
      });
      wx.request({
        url: app.globalData.interfaceUrls.billList,
        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;
          _this.setData({
            billList: apiReturnData.data,
          });
          resolve(apiReturnData.data);
        },
        fail(error) {
          wx.hideLoading();
          utils.simleInfo('获取账单失败，请稍后再试');
          reject(error);
        }
      });
    });
  },

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

  // 点击开发票按钮
  openInvoice: function(e) {
    const index = e.currentTarget.dataset.index;
    const bill = this.data.billList[index];

    wx.showToast({
      title: '开发票功能开发中',
      icon: 'none'
    });
  },

  // 切换到首页
  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'
    })
  },

  // 跳转到账单详情页面
  goToBillDetail: function(e) {
    const bill = e.currentTarget.dataset.bill;
    wx.navigateTo({
      url: '/pages/zhangdanxiangqing/zdxiangqing?billInfo=' + JSON.stringify(bill)
    });
  },

  // 获取发票
  getInvoice: function(e) {
    wx.showToast({
      title: '暂不支持!',
      icon: 'none'
    });
    return;
    // 阻止事件冒泡，避免触发goToBillDetail
    e.stopPropagation();
    const bill = e.currentTarget.dataset.bill;
    wx.navigateTo({
      url: '/pages/invoice/invoice?billInfo=' + JSON.stringify(bill)
    });
  },

  // 生成近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.setData({
        billList: originalBillList
      });
      return;
    }
    
    // 根据年份筛选账单
    const filteredBills = originalBillList.filter(bill => {
      // 假设 billDate 格式为 "YYYY/MM/DD" 或 "YYYY-MM-DD"
      return bill.billDate.startsWith(selectedYear) || bill.billDate.startsWith(selectedYear + '-');
    });
    
    this.setData({
      billList: filteredBills
    });
  }
})
