import request from '../../utils/request.js';
import { STAFF_API, applyStaffFromLoginData } from '../../utils/staff-api.js';
import { enterLockedRole, lockPrimaryRole } from '../../utils/primary-role.js';

const app = getApp();

Page({
  data: {
    inviteCode: '',
    loading: false,
  },

  onLoad(options) {
    const code = options.code || options.inviteCode || '';
    if (code) this.setData({ inviteCode: decodeURIComponent(code) });
  },

  onInput(e) {
    this.setData({ inviteCode: (e.detail.value || '').trim() });
  },

  async onBind() {
    const inviteCode = this.data.inviteCode;
    if (!inviteCode) {
      wx.showToast({ title: '请输入邀请码', icon: 'none' });
      return;
    }
    this.setData({ loading: true });
    try {
      const res = await request({
        url: STAFF_API.bind,
        method: 'POST',
        data: { inviteCode },
      });
      const d = res.data || {};
      if (d.code === 0 && d.data && d.data.staff_context) {
        applyStaffFromLoginData({
          staffstatus: 1,
          staff_context: d.data.staff_context,
        });
        lockPrimaryRole('shangjia', app);
        wx.showToast({ title: '绑定成功', icon: 'success' });
        setTimeout(() => {
          enterLockedRole('shangjia', app);
        }, 800);
      } else {
        wx.showToast({ title: d.msg || '绑定失败', icon: 'none' });
      }
    } catch (e) {
      wx.showToast({ title: '网络错误', icon: 'none' });
    } finally {
      this.setData({ loading: false });
    }
  },
});
