const app = getApp();
Page({
  data: {
    images: {
      logo: '',
      background: '',
      card: '',
      tzd: "",
      phone: "",
      yl: "",
      jcsfcjtzd: ""
    },
    userInfo: {
      name: '',
      id: '',
      address: ''
    },
    billInfo: {}, // 存储从首页传递过来的账单信息
    quickAmounts: [10, 30, 50, 100, 200, 500],
    showKeyboard: false,
    selectedAmount: 0,
    customAmount: '',
    inputFocus: false,
    zdId:"",
    amount: 0,
    actualAmount: 0,
    balance: 0
  },
  onLoad(options) {
    const _this=this;
    // 更新用户信息
    this.updateUserInfo();
    
    debugger
    wx.request({
      url: app.globalData.interfaceUrls.pendingBill + app.globalData.currentAccountInfo.usernumber,
      method: 'POST',
      header: {
        'content-type': 'application/json',
        'token': app.globalData.userWxInfo.token,
        'source': "wc",
        '!SAAS_LOGIN_TOKEN_!': app.globalData.currentAccountInfo.dsKey
      },
      success(res) {
        debugger
        wx.hideLoading();
        let apiReturnData = res.data;
        _this.setData({
          actualAmount: apiReturnData.data.yj, // 设置应缴金额
          balance: apiReturnData.data.ye,   //余额
          zdId: apiReturnData.data.zdId  // 对应的账单记录
        });
        // 计算默认实缴金额
        _this.calculateDefaultAmount();
      },
      fail(error) {
        wx.hideLoading();
        wx.showToast({
          title: '数据加载失败，请稍后再试',
          icon: 'none',
          duration: 2000
        });
      }
    });

    this.setData({
      images: {
        logo:'/static_file/logo.png',
        background:'/static_file/background.png',
        card:'/static_file/card.png',
        tzd:'/static_file/backgrountzdd.png',
        phone:'/static_file/phone.png',
        yl:'/static_file/background.yl',
        jcsfcjtzd:'/static_file/jcsfcjtzd.png',
        kapiantubiao:'/static_file/kapiantubiao.png'

      }
    })
    // 获取状态栏高度
    const systemInfo = wx.getSystemInfoSync();
    this.setData({
      statusBarHeight: systemInfo.statusBarHeight
    });
    this.fetchPaymentData();
  },

  onShow() {
    // 每次页面显示时更新用户信息
    this.updateUserInfo();
  },

  // 更新用户信息的方法
  updateUserInfo() {
    this.setData({
      'userInfo.name': app.globalData.currentAccountInfo.username,
      'userInfo.id': app.globalData.currentAccountInfo.usernumber,
      'userInfo.address': app.globalData.currentAccountInfo.address
    });
  },

  // 计算默认实缴金额
  calculateDefaultAmount: function() {
    const { actualAmount, balance } = this.data;
    const difference = (actualAmount - balance).toFixed(2);
    
    if (difference <= 0) {
      this.setData({
        amount: 0
      });
    } else {
      this.setData({
        amount: parseFloat(difference)
      });
    }
  },

  // 验证实缴金额
  validateAmount: function(amount) {
    const { actualAmount, balance } = this.data;
    const difference = actualAmount - balance;
    
    if (difference <= 0) {
      return amount > 0;
    } else {
      return amount >= difference;
    }
  },

  // 选择快捷金额
  selectAmount: function(e) {
    const amount = parseFloat(e.currentTarget.dataset.amount);
    this.setData({
      selectedAmount: amount,
      amount: amount,
      customAmount: ''
    });
  },

  // 立即缴费
  payNow: function() {
    const { amount, actualAmount, balance } = this.data;
    
    if (amount <= 0) {
      wx.showToast({
        title: '请输入缴费金额',
        icon: 'none'
      });
      return;
    }

    if (actualAmount > 0 && amount + balance < actualAmount) {
      const minPayment = (actualAmount - balance).toFixed(2);
      wx.showToast({
        title: '最低缴费金额：'+ minPayment + '元',
        icon: 'none'
      });
      return;
    }

    wx.showLoading({
      title: '处理中',
    });
    wx.request({
      url: app.globalData.interfaceUrls.prepayOrder,
      method: 'POST',
      header: {
        'content-type': 'application/json',
        'token': app.globalData.userWxInfo.token,
        'source': "wc",
        '!SAAS_LOGIN_TOKEN_!': app.globalData.currentAccountInfo.dsKey
      },
      data: {
        openId: app.globalData.userWxInfo.openid,
        totalAmount: this.data.amount*100,
        dskey: app.globalData.currentAccountInfo.dsKey
      },
      success: res => {
        if(res.data.code === '200'){
          wx.hideLoading();
          console.log('预下单', res);
          let orderNo=res.data.data.orderNo;
          wx.requestPayment({
            timeStamp: res.data.data.paymentSign.timeStamp,
            nonceStr: res.data.data.paymentSign.nonceStr,
            package: res.data.data.paymentSign.packageVal,
            signType: 'RSA',
            paySign: res.data.data.paymentSign.paySign,
            success: res => {
              console.log('支付结果', res);
              this.createWeChatPayMentRecord(orderNo,this.data.amount);
            },
            fail (res) {
              console.log("fail",res);
            },
            complete: () => {
            }
          })
        }else if(res.data.code === '500'){
          // 支付失败处理
          if (res.data.msg && res.data.msg.includes("系统维护中，请稍后缴费")) {
            const parts = res.data.msg.split("|");
            const errorMessage = parts[0]; // "不允许在线缴费" 
            // const payStatus = parts[1];  
            wx.showToast({
              title: errorMessage,
              icon: 'none',  
              duration: 2000  // 持续2秒
          });
          }
        }
      }
    })
  },

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

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

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

  // 添加切换水表的方法
  switchMeter: function() {
    wx.navigateTo({
      url: '/pages/switchMeter/switchMeter',
    })
  },

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

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

  // 显示键盘 - 使用微信内置键盘
  showCustomAmountInput: function() {
    // 使用微信内置的输入框
    wx.showModal({
      title: '请输入金额',
      placeholderText: '请输入缴费金额',
      editable: true,
      success: (res) => {
        if (res.confirm && res.content) {
          // 验证输入是否为有效数字
          const inputAmount = parseFloat(res.content);
          if (!isNaN(inputAmount) && inputAmount > 0) {
            this.setData({
              amount: inputAmount
            });
          } else {
            wx.showToast({
              title: '请输入有效金额',
              icon: 'none'
            });
          }
        }
      }
    });
  },

  // 自定义金额输入
  onCustomAmountInput: function(e) {
    let value = e.detail.value;
    
    // 只允许输入数字和小数点
    value = value.replace(/[^\d.]/g, '');
    
    // 处理前导零
    if (value.startsWith('0')) {
      // 如果只有一个0，保持不变
      if (value.length === 1) {
        // 保持原样
      } else if (value.startsWith('0.')) {
        // 如果是0.开头，保持原样
      } else {
        // 移除前导零，但保留单个0
        value = value.replace(/^0+/, '');
        if (value === '') value = '0';
      }
    }
    
    // 处理小数点
    if (value.includes('.')) {
      const parts = value.split('.');
      // 只保留第一个小数点
      if (parts.length > 2) {
        value = parts[0] + '.' + parts.slice(1).join('');
      }
      // 限制小数点后两位
      if (parts[1].length > 2) {
        value = parts[0] + '.' + parts[1].substring(0, 2);
      }
    }
    
    const amount = parseFloat(value) || 0;
    
    this.setData({
      customAmount: value,
      amount: amount,
      selectedAmount: 0
    });
  },

  // 输入数字
  inputNumber: function(e) {
    const number = e.currentTarget.dataset.number;
    let customAmount = this.data.customAmount;

    // 处理小数点
    if (number === '.') {
      if (customAmount.includes('.')) {
        return; // 已经有小数点了，不能再输入
      }
      if (customAmount === '') {
        customAmount = '0.'; // 如果直接输入小数点，前面补0
      } else {
        customAmount += '.';
      }
    } else {
      // 处理首位为0的情况
      if (customAmount === '0' && number !== '.') {
        customAmount = number;
      } else {
        // 限制小数点后两位
        if (customAmount.includes('.')) {
          const parts = customAmount.split('.');
          if (parts[1].length >= 2) {
            return; // 小数点后已经有两位了，不能再输入
          }
        }
        customAmount += number;
      }
    }

    // 更新金额
    this.setData({
      customAmount: customAmount,
      amount: parseFloat(customAmount) || 0
    });
  },

  // 删除数字
  deleteNumber: function() {
    let customAmount = this.data.customAmount;
    if (customAmount.length <= 1) {
      this.setData({
        customAmount: '',
        amount: 0
      });
    } else {
      customAmount = customAmount.substring(0, customAmount.length - 1);
      this.setData({
        customAmount: customAmount,
        amount: parseFloat(customAmount) || 0
      });
    }
  },

  // 确认输入
  confirmInput: function() {
    this.setData({
      showKeyboard: false,
      inputFocus: false
    });
  },

  // 输入框获得焦点
  onInputFocus: function() {
    this.setData({
      inputFocus: true,
      selectedAmount: null // 取消快捷金额的选中状态
    });
  },

  // 输入框失去焦点
  onInputBlur: function() {
    this.setData({
      inputFocus: false
    });
  },
  // 创建微信付款记录
  createWeChatPayMentRecord:function(orderNo,paymentAmount){
    wx.request({
      url: app.globalData.interfaceUrls.createPaymentRecord,
      method: 'POST',
      header: {
        'content-type': 'application/json',
        'token': app.globalData.userWxInfo.token,
        'source': "wc",
        '!SAAS_LOGIN_TOKEN_!': app.globalData.currentAccountInfo.dsKey
      },
      data: {
        orderNo: orderNo,
        paymentAmount: paymentAmount,
        zdId: this.data.zdId,
        userNumber: app.globalData.currentAccountInfo.usernumber,
        dsKey: app.globalData.currentAccountInfo.dsKey
      },
      success(res) {
        wx.hideLoading();
        wx.navigateTo({
          url: '/pages/jiaofeiSuccess/jiaofeiSuccess',
        });
      },
      fail(error) {
        wx.hideLoading();
        wx.showToast({
          title: '数据加载失败，请稍后再试',
          icon: 'none',
          duration: 2000
        });
      }
    });
  },

  // 从接口获取支付数据
  fetchPaymentData: function() {
    // 这里是模拟数据，实际应用中应该调用真实接口
    // wx.request({
    //   url: 'your-api-endpoint',
    //   success: (res) => {
    //     this.setData({
    //       amountDue: res.data.amountDue,
    //       balance: res.data.balance
    //     });
    //   }
    // });
    
    // this.setData({
    //   amountDue: 150.00,
    //   balance: 200.50
    // });
  },
}) 