/**
 * 分销中心
 * 概况 / 团队 / 佣金 / 提现 / 推广链接 / 绑定上级
 * 对齐后端 /api/distribution/*
 */
const api = require('../../utils/api');

Page({
  data: {
    loading: true,
    info: null,
    stat: { today: 0, month: 0, total: 0 },
    team: [],
    commission: [],
    withdrawList: [],
    levels: [],
    qrcode: null,
    parentId: '',
    hasBind: false,
    // 提现表单
    showWithdraw: false,
    withdrawAmount: '',
    accountType: 'wechat',
    accountInfo: '',
    activeTab: 'stat', // stat | team | commission | withdraw
    distStatus: {} // 🩹分销开通状态
  },

  onLoad(options) {
    this.setData({ inviteParent: (options && options.parent_id) ? options.parent_id : '' });
    this.loadAll();
  },

  switchTab(e) {
    this.setData({ activeTab: e.currentTarget.dataset.tab });
    if (e.currentTarget.dataset.tab === 'team' && this.data.team.length === 0) this.loadTeam();
    if (e.currentTarget.dataset.tab === 'commission' && this.data.commission.length === 0) this.loadCommission();
    if (e.currentTarget.dataset.tab === 'withdraw' && this.data.withdrawList.length === 0) this.loadWithdrawList();
  },

  async loadAll() {
    this.setData({ loading: true });
    try {
      const [info, stat, qrcode, userMe, distStatus] = await Promise.all([
        api.getDistributionInfo().catch(() => null),
        api.getCommissionStat().catch(() => ({})),
        api.getDistributionQrcode().catch(() => null),
        api.getUserInfo().catch(() => null),
        api.getDistributionStatus().catch(() => null)
      ]);
      const parentId = (userMe && userMe.parent_id) ? String(userMe.parent_id) : '';
      const inviteParent = this.data.inviteParent;
      this.setData({
        info, stat, qrcode, distStatus: distStatus || {},
        team: this.data.team,
        parentId,
        hasBind: !!parentId
      });
      // 若带上级ID参数则自动填入绑定框
      if (inviteParent && !parentId) {
        this.setData({ parentId: String(inviteParent) });
      }
    } catch (e) {
      console.error('分销加载失败', e);
    } finally {
      this.setData({ loading: false });
    }
  },

  async loadTeam() {
    const res = await api.getDistributionTeam({ page: 1, pageSize: 50 }).catch(() => []);
    this.setData({ team: (res && res.list) || res || [] });
  },

  async loadCommission() {
    const res = await api.getCommissionRecords({ page: 1, pageSize: 50 }).catch(() => []);
    this.setData({ commission: (res && res.list) || res || [] });
  },

  async loadWithdrawList() {
    const res = await api.getWithdrawList({ page: 1, pageSize: 50 }).catch(() => []);
    this.setData({ withdrawList: (res && res.list) || res || [] });
  },

  openWithdraw() {
    this.setData({ showWithdraw: true });
  },
  closeWithdraw() {
    this.setData({ showWithdraw: false });
  },

  onAmountInput(e) {
    this.setData({ withdrawAmount: e.detail.value });
  },
  onAccountType(e) {
    this.setData({ accountType: e.currentTarget.dataset.type });
  },
  onAccountInfo(e) {
    this.setData({ accountInfo: e.detail.value });
  },

  async submitWithdraw() {
    const amount = Number(this.data.withdrawAmount);
    if (!amount || amount <= 0) {
      wx.showToast({ title: '请输入正确金额', icon: 'none' });
      return;
    }
    try {
      await api.applyWithdraw({
        amount,
        account_type: this.data.accountType,
        account_info: this.data.accountInfo
      });
      this.setData({ showWithdraw: false, withdrawAmount: '', accountInfo: '' });
      wx.showToast({ title: '申请成功', icon: 'success' });
      this.loadAll();
    } catch (e) { /* 内部已 toast */ }
  },

  copyLink() {
    if (!this.data.qrcode || !this.data.qrcode.url) return;
    wx.setClipboardData({
      data: this.data.qrcode.url,
      success: () => wx.showToast({ title: '链接已复制', icon: 'success' })
    });
  },

  onParentInput(e) {
    this.setData({ parentId: e.detail.value });
  },

  async bindParent() {
    const pid = Number(this.data.parentId);
    if (!pid || pid <= 0) {
      wx.showToast({ title: '请输入上级ID', icon: 'none' });
      return;
    }
    try {
      await api.bindParent(pid);
      wx.showToast({ title: '绑定成功', icon: 'success' });
      this.setData({ hasBind: true });
      this.loadAll();
    } catch (e) { /* 内部已 toast */ }
  },

  async applyDist() {
    const st = this.data.distStatus || {};
    if (st.status === 'active') {
      wx.showToast({ title: '您已开通分销', icon: 'none' });
      return;
    }
    if (st.agent_apply_enabled === false && st.dist_mode === 'designated') {
      wx.showToast({ title: '当前暂不开放分销申请', icon: 'none' });
      return;
    }
    wx.showModal({
      title: '申请开通分销',
      content: st.paid_member ? '您已是付费会员，将直接开通分销权限' : '申请成为分销商后可推广赚佣金，确认申请？',
      success: async (res) => {
        if (!res.confirm) return;
        try {
          const r = await api.applyDistribution({ reason: '申请分销' });
          wx.showToast({ title: (r && r.message) || '申请成功', icon: 'none' });
          if (r && r.data && r.data.status === 'active') this.loadAll();
        } catch (e) { /* 内部已 toast */ }
      }
    });
  },

  noop() {}
});
