// components/fakuan-list/fakuan-pay/fakuan-pay.js
import request from '../../../../utils/request.js';  // 路径保持您原来的样子

Component({
  properties: {
    visible: { type: Boolean, value: false, observer: 'onVisibleChange' },
    fadan: { type: Object, value: null }  // { id, fakuanjine }
  },

  data: {
    step: 'method',          // method / balance / confirm / loading
    balanceOptions: [],
    selectedBalance: null,
    loadingText: '',
    payLoading: false,
    dingdanid: ''            // 微信支付内部订单ID
  },

  methods: {
    onVisibleChange(val) {
      if (val) {
        // 每次打开重置为支付方式选择
        this.setData({ step: 'method', balanceOptions: [], selectedBalance: null });
      }
    },

    close() {
      this.setData({ visible: false });
      this.triggerEvent('close');
    },

    // 选择支付方式
    async chooseMethod(e) {
      const method = e.currentTarget.dataset.method;
      if (method === 'wx') {
        this.wxPay();
      } else if (method === 'balance') {
        this.fetchBalanceOptions();
      }
    },

    // ========== 微信支付流程 ==========
    async wxPay() {
      this.setData({ step: 'loading', loadingText: '发起支付中...' });
      try {
        const res = await request({
          url: '/yonghu/fkjn',
          method: 'POST',
          data: { fadan_id: this.properties.fadan.id }
        });
        if (res.data.code !== 200) throw new Error(res.data.msg || '下单失败');

        // 🔥 唯一修改点：后端返回格式 { code:200, payParams:{...}, dingdanid:'...' }
        const payParams = res.data.payParams;
        const dingdanid = res.data.dingdanid;

        this.setData({ dingdanid });
        await this.requestWxPayment(payParams);
      } catch (e) {
        this.setData({ step: 'method' });
        wx.showToast({ title: e.message, icon: 'none' });
      }
    },

    async requestWxPayment(payParams) {
      return new Promise((resolve, reject) => {
        if (!payParams || !payParams.timeStamp || !payParams.paySign) {
          wx.showToast({ title: '支付参数错误', icon: 'none' });
          reject(new Error('支付参数错误'));
          return;
        }
        wx.requestPayment({
          timeStamp: payParams.timeStamp,
          nonceStr: payParams.nonceStr,
          package: payParams.package,
          signType: payParams.signType || 'MD5',
          paySign: payParams.paySign,
          success: () => {
            this.pollPayStatus();
            resolve();
          },
          fail: (err) => {
            this.setData({ step: 'method' });
            this.notifyPayFail();
            reject(err);
          }
        });
      });
    },

    async pollPayStatus() {
      this.setData({ step: 'loading', loadingText: '确认支付结果...' });
      for (let i = 0; i < 10; i++) {
        try {
          const res = await request({
            url: '/yonghu/fkzffc',
            method: 'POST',
            data: { dingdanid: this.data.dingdanid }
          });
          if (res.data.code === 200) {
            this.triggerEvent('success');
            this.close();
            wx.showToast({ title: '缴纳成功', icon: 'success' });
            return;
          }
        } catch (e) {}
        await new Promise(r => setTimeout(r, 2000));
      }
      this.setData({ step: 'method' });
      wx.showToast({ title: '支付确认超时', icon: 'none' });
    },

    async notifyPayFail() {
      try {
        await request({
          url: '/yonghu/fkzfsb',
          method: 'POST',
          data: { dingdanid: this.data.dingdanid }
        });
      } catch (e) {}
    },

    // ========== 佣金抵扣流程 ==========
    async fetchBalanceOptions() {
      this.setData({ step: 'loading', loadingText: '获取可抵扣身份...' });
      try {
        const res = await request({
          url: '/shangpin/czhqdy',
          method: 'POST',
          data: {
            leixing: 4,
            fadan_id: this.properties.fadan.id,
            jine: this.properties.fadan.fakuanjine
          }
        });
        if (res.data.code !== 200) throw new Error(res.data.msg || '获取失败');
        this.setData({ balanceOptions: res.data.data, step: 'balance' });
      } catch (e) {
        this.setData({ step: 'method' });
        wx.showToast({ title: e.message, icon: 'none' });
      }
    },

    selectBalance(e) {
      const id = e.currentTarget.dataset.id;
      const info = this.data.balanceOptions.find(opt => opt.id === id);
      if (!info) return;
      this.setData({ selectedBalance: info, step: 'confirm' });
    },

    backToMethod() {
      this.setData({ step: 'method' });
    },

    async confirmBalance() {
      if (!this.data.selectedBalance) return;
      this.setData({ step: 'loading', loadingText: '抵扣扣款中...' });
      try {
        const res = await request({
          url: '/shangpin/dsqrgmdh',
          method: 'POST',
          data: {
            leixing: 4,
            shenfen_id: this.data.selectedBalance.id,
            fadan_id: this.properties.fadan.id
          }
        });
        if (res.data.code !== 200) throw new Error(res.data.msg || '抵扣失败');
        this.triggerEvent('success');
        this.close();
        wx.showToast({ title: '缴纳成功', icon: 'success' });
      } catch (e) {
        this.setData({ step: 'method' });
        wx.showToast({ title: e.message, icon: 'none' });
      }
    }
  }
});