/**
 * 砍价（好友助力裂变）
 * 对齐后端 /api/bargain/*
 * 视图：list(活动列表) / detail(活动详情+发起) / mysess(我的砍价单) / sess(砍价单详情+帮砍/下单)
 * 三端对齐版：帮砍/下单/支付走真实支付链；支付入口在 H5
 */
const api = require('../../utils/api');

Page({
  data: {
    view: 'list',        // list | detail | mysess | sess
    loading: true,
    list: [],
    detail: {},
    sessions: [],
    session: {},
    myUserId: 0,
    submitting: false,
    isOwner: false
  },

  onLoad() {
    this.loadList();
  },

  onShow() {
    this.loadMyUserId();
    if (this.data.view === 'mysess') this.loadSessions();
  },

  loadMyUserId() {
    try {
      const t = wx.getStorageSync('token');
      if (t) {
        const p = t.split('.')[1];
        if (p) {
          const d = JSON.parse(decodeURIComponent(escape(atob(p.replace(/-/g, '+').replace(/_/g, '/')))));
          if (d && d.userId) this.setData({ myUserId: Number(d.userId) });
        }
      }
    } catch (e) {}
  },

  async loadList() {
    this.setData({ loading: true });
    const res = await api.getBargainList({ page: 1, pageSize: 50 }).catch(() => []);
    this.setData({ list: (res && res.list) || res || [], loading: false });
  },

  async loadSessions() {
    const t = wx.getStorageSync('token');
    if (!t) return;
    const res = await api.getBargainSessions({ page: 1, pageSize: 50 }).catch(() => []);
    this.setData({ sessions: (res && res.list) || res || [] });
  },

  switchView(e) {
    const v = e.currentTarget.dataset.view;
    this.setData({ view: v, session: {}, isOwner: false });
    if (v === 'list') this.loadList();
    if (v === 'mysess') this.loadSessions();
  },

  async openDetail(e) {
    const id = e.currentTarget.dataset.id;
    this.setData({ loading: true, view: 'detail' });
    try {
      const d = await api.getBargainDetail(id);
      if (d && d.id) {
        this.setData({ detail: d });
      } else {
        wx.showToast({ title: '获取详情失败', icon: 'none' });
        this.setData({ view: 'list' });
      }
    } catch (err) {
      wx.showToast({ title: '获取详情失败', icon: 'none' });
      this.setData({ view: 'list' });
    }
    this.setData({ loading: false });
  },

  backToList() {
    this.setData({ view: 'list' });
  },

  async startBargain() {
    const t = wx.getStorageSync('token');
    if (!t) {
      wx.navigateTo({ url: '/pages/login/login' });
      return;
    }
    if (!this.data.detail.id) {
      wx.showToast({ title: '请先选择砍价活动', icon: 'none' });
      return;
    }
    if (this.data.submitting) return;
    this.setData({ submitting: true });
    try {
      const res = await api.startBargain({ activity_id: this.data.detail.id, quantity: 1 });
      const s = res && res.session;
      if (s && s.session_no) {
        wx.showModal({
          title: '砍价单已创建',
          content: `单号 ${s.session_no}，当前价 ¥${Number(s.current_price).toFixed(2)}。邀请好友帮砍，砍到底价即可用低价下单！`,
          confirmText: '去分享',
          cancelText: '我的砍价',
          success: (m) => {
            if (m.confirm) {
              const s2 = s;
              const o = Number(s2.original_price) || 0, fl = Number(s2.floor_price) || 0, c = Number(s2.current_price) || 0;
              this.setData({ view: 'sess', session: Object.assign({}, s2, { progress: o > fl ? Math.min(100, Math.max(0, Math.round((o - c) / (o - fl) * 100))) : 0, cut_amount: (o - c).toFixed(2) }), isOwner: true });
            } else {
              this.setData({ view: 'mysess' });
              this.loadSessions();
            }
          }
        });
      } else {
        wx.showToast({ title: (res && res.message) || '发起失败', icon: 'none', duration: 2500 });
      }
    } catch (e) {
      wx.showToast({ title: '发起失败', icon: 'none' });
    }
    this.setData({ submitting: false });
  },

  async openSession(e) {
    const no = e.currentTarget.dataset.no;
    await this.loadSessionDetail(no);
  },

  async loadSessionDetail(no) {
    this.setData({ loading: true, view: 'sess' });
    try {
      const s = await api.getBargainSessionDetail(no);
      if (s && s.session_no) {
        const orig = Number(s.original_price) || 0;
        const floor = Number(s.floor_price) || 0;
        const cur = Number(s.current_price) || 0;
        const pct = orig > floor ? Math.min(100, Math.max(0, Math.round((orig - cur) / (orig - floor) * 100))) : 0;
        this.setData({
          session: Object.assign({}, s, {
            progress: pct,
            cut_amount: (orig - cur).toFixed(2)
          }),
          isOwner: Number(s.user_id) === this.data.myUserId
        });
      } else {
        wx.showToast({ title: '砍价单不存在', icon: 'none' });
        this.setData({ view: 'mysess' });
      }
    } catch (e) {
      wx.showToast({ title: '获取失败', icon: 'none' });
      this.setData({ view: 'mysess' });
    }
    this.setData({ loading: false });
  },

  backToMySessions() {
    this.setData({ view: 'mysess' });
    this.loadSessions();
  },

  async helpBargain() {
    const t = wx.getStorageSync('token');
    if (!t) {
      wx.navigateTo({ url: '/pages/login/login' });
      return;
    }
    if (!this.data.session.session_no) return;
    if (this.data.submitting) return;
    this.setData({ submitting: true });
    try {
      const res = await api.helpBargain({ session_no: this.data.session.session_no });
      if (res && res.amount !== undefined) {
        wx.showToast({
          title: `帮 TA 砍了 ¥${Number(res.amount).toFixed(2)}，当前 ¥${Number(res.current_price).toFixed(2)}`,
          icon: 'none',
          duration: 2200
        });
        this.loadSessionDetail(this.data.session.session_no);
      } else {
        wx.showToast({ title: (res && res.message) || '帮砍失败', icon: 'none', duration: 2500 });
      }
    } catch (e) {
      wx.showToast({ title: '帮砍失败', icon: 'none' });
    }
    this.setData({ submitting: false });
  },

  shareBargain() {
    wx.showModal({
      title: '分享砍价',
      content: '复制链接发给好友帮砍，好友可帮你随机砍一刀！',
      confirmText: '复制链接',
      cancelText: '知道了',
      success: (m) => {
        if (m.confirm) {
          const base = getApp().globalData.baseUrl || 'https://ssypco.com';
          const url = base + '/mobile/?p=bargain#/bargain?session_no=' + this.data.session.session_no;
          wx.setClipboardData({
            data: url,
            success: () => wx.showToast({ title: '链接已复制', icon: 'success' })
          });
        }
      }
    });
  },

  async orderBargain(e) {
    const no = e.currentTarget.dataset.no || this.data.session.session_no;
    const t = wx.getStorageSync('token');
    if (!t) {
      wx.navigateTo({ url: '/pages/login/login' });
      return;
    }
    if (!no) return;
    if (this.data.submitting) return;
    this.setData({ submitting: true });
    try {
      const naturalPay = require('../../utils/native-pay');
      const res = await api.bargainOrder({ session_no: no, payment_method: 'wechat' });
      const amt = res && res.amount;
      if (amt === undefined) {
        this.setData({ submitting: false });
        wx.showToast({ title: (res && res.message) || '下单失败', icon: 'none', duration: 2500 });
        return;
      }
      const oNo = (res && res.order_no) || no;
      const base = getApp().globalData.baseUrl || 'https://ssypco.com';
      // P1：优先小程序原生拉起支付；失败/未配置则回退 H5 webview
      this.setData({ submitting: false });
      try {
        const p = await naturalPay.nativePay({ order_no: oNo, amount: amt, subject: '砍价商品' });
        if (p.mode === 'jsapi' && !p.completed) {
          wx.showToast({ title: '已下单，可在订单中继续支付', icon: 'none', duration: 2200 });
        }
        this.setData({ view: 'mysess' });
        this.loadSessions();
      } catch (payErr) {
        wx.navigateTo({ url: '/pages/webview/webview?url=' + encodeURIComponent(base + '/mobile/#/bargain?session_no=' + no + '&order_no=' + oNo) });
      }
    } catch (e) {
      this.setData({ submitting: false });
      wx.showToast({ title: (e && e.message) || '下单失败', icon: 'none' });
    }
  },

  statusLabel(s) {
    const m = { bargaining: '砍价中', can_order: '可下单', ordered: '已下单', expired: '已过期' };
    return m[s] || s || '';
  }
});
