// pages/guanshizhongxin/guanshizhongxin.js
import {
  createPage, request, isRoleStatusActive, syncRoleStatuses, syncProfileFields,
  syncGroupFields, ensureRoleOnCenterPage, refreshTabBar, parseSceneOptions,
  isApiSuccess, getApiMsg, extractUserData
} from '../../utils/base-page.js';
import { buildInviterPeerId } from '../../utils/im-user.js';

Page(createPage({
  data: {
    // 图片路径对象
    imgUrls: {},

    isGuanshi: false,
    inviteCode: '',
    uid: '',
    nicheng: '',
    avatarUrl: '',

    // 管事信息
    gszhstatus: '',
    yaoqingzongshu: 0,
    fenyongzonge: '0.00',
    fenyongtixian: '0.00',
    yichongzhiDashou: 0,
    zhuanhualv: 0,

    // 称号列表
    chenghaoList: [],

    // 邀请人缓存
    inviterCache: null,
  },

  onLoad(options) {
    let url = '/pages/fighter/fighter?registerType=guanshi';
    const parsed = parseSceneOptions(options);
    if (parsed.inviteCode) {
      url += '&inviteCode=' + encodeURIComponent(parsed.inviteCode);
    }
    wx.redirectTo({ url });
    return;
    // 以下保留供恢复参考
    // 拼接所有图片完整路径
    const app = getApp();
    const ossImageUrl = app.globalData.ossImageUrl || '';
    const imgBase = ossImageUrl + 'beijing/guanshiduan/';
    this.setData({
      imgUrls: this.initImageUrls({
        pageBg: imgBase + 'page-bg.jpg',
        topDecor: imgBase + 'top-decor.png',
        cardBg1: imgBase + 'card-bg1.png',
        cardBg2: imgBase + 'card-bg2.png',
        iconRefresh: imgBase + 'icon-refresh.png',
        iconCopy: imgBase + 'icon-copy.png',
        avatarDefault: ossImageUrl + 'avatar/default.jpg',
        iconInvite: imgBase + 'icon-invite.png',
        iconSub: imgBase + 'icon-sub.png',
        iconRecord: imgBase + 'icon-record.png',
        iconRank: imgBase + 'icon-rank.png',
        iconPoster: imgBase + 'icon-poster.png',
        iconWithdraw: imgBase + 'icon-withdraw.png',
        iconContact: imgBase + 'icon-contact.png',
        iconArrow: imgBase + 'icon-arrow.png',
      })
    });

    this.checkRoleStatus();

    const inviteCode = parsed.inviteCode;
    if (inviteCode) {
      this.setData({ inviteCode });
      setTimeout(() => {
        this.handleInviteCodeWithLoginCheck({
          inviteCode,
          role: 'dashou',
          statusKey: 'guanshistatus',
          alreadyMsg: '已是管事',
          onNeedLogin: (code) => this.loginAndRegisterWithInviteCode({
            inviteCode: code,
            onLoginSuccess: (wxCode, invCode) => this.callLoginRegisterApi(wxCode, invCode),
          }),
          onAlreadyRegistered: () => this._enterRegisteredGuanshiState('您已是管事'),
        });
      }, 500);
    }

    this.checkColdStartPopup('guanshiduan');
  },

  onShow() {
    const inviterCache = wx.getStorageSync('inviterCache') || null;
    this.setData({ inviterCache });

    this.registerNotificationComponent();

    if (this._isGuanshiPageActive()) {
      if (!this.data.isGuanshi) {
        this.setData({ isGuanshi: true });
      }
      ensureRoleOnCenterPage(this, 'guanshi');
      setTimeout(() => {
        this.getGuanshiInfo();
        this.fetchChenghaoList();
      }, 300);
    }

    const pages = getCurrentPages();
    const currentPage = pages[pages.length - 1];
    const options = currentPage.options || {};
    if (options.inviteCode && !this._isGuanshiPageActive()) {
      setTimeout(() => {
        this.handleInviteCodeWithLoginCheck({
          inviteCode: options.inviteCode,
          role: 'dashou',
          statusKey: 'guanshistatus',
          alreadyMsg: '已是管事',
          onNeedLogin: (code) => this.loginAndRegisterWithInviteCode({
            inviteCode: code,
            onLoginSuccess: (wxCode, invCode) => this.callLoginRegisterApi(wxCode, invCode),
          }),
          onAlreadyRegistered: () => this._enterRegisteredGuanshiState('您已是管事'),
        });
      }, 300);
    }
  },

  // 称号列表
  async fetchChenghaoList() {
    try {
      const res = await request({
        url: '/dengji/chenghao',
        method: 'POST',
        data: { role: 'guanshi' }
      });
      if (res && res.data.code === 0 && res.data.data) {
        this.setData({ chenghaoList: res.data.data.chenghao_list || [] });
      }
    } catch (e) {
      console.error('获取称号失败', e);
    }
  },

  // 联系组长
  async contactInviter() {
    wx.showLoading({ title: '获取组长信息...', mask: true });
    try {
      const res = await request({
        url: '/yonghu/guanshi_contact',
        method: 'POST'
      });

      if (res && res.data.code === 200 && res.data.data) {
        const inviter = res.data.data;
        const ossImageUrl = getApp().globalData.ossImageUrl || '';
        const fullAvatar = inviter.touxiang
          ? (inviter.touxiang.startsWith('http') ? inviter.touxiang : ossImageUrl + inviter.touxiang)
          : '';

        // 缓存邀请人信息
        const cacheData = {
          uid: inviter.uid,
          nicheng: inviter.nicheng || '',
          avatar: fullAvatar
        };
        wx.setStorageSync('inviterCache', cacheData);
        this.setData({ inviterCache: cacheData });

        // 联系邀请人
        const param = {
          toUserId: buildInviterPeerId(inviter.uid),
          toName: inviter.nicheng || '邀请人',
          toAvatar: fullAvatar
        };
        wx.navigateTo({
          url: '/pages/chat/chat?data=' + encodeURIComponent(JSON.stringify(param))
        });
      } else {
        wx.showToast({ title: '未绑定邀请人', icon: 'none' });
      }
    } catch (e) {
      wx.showToast({ title: '网络错误', icon: 'none' });
    } finally {
      wx.hideLoading();
    }
  },

  // 管事状态辅助
  _isAlreadyGuanshiMsg(msg) {
    if (!msg || typeof msg !== 'string') return false;
    return msg.includes('已是管事') || msg.includes('已经是管事');
  },

  _syncGuanshiCache() {
    const app = getApp();
    wx.setStorageSync('guanshistatus', 1);
    app.globalData.guanshistatus = 1;
  },

  // 后端若返回打手详情字段则写入 globalData
  _syncDashouGlobalData(data) {
    const app = getApp();
    const map = {
      dashouNicheng: data.dashounicheng,
      zhanghaoStatus: data.zhanghaostatus,
      yongjin: data.yongjin,
      zonge: data.zonge,
      yajin: data.yajin,
      chenghao: data.chenghao,
      jinfen: data.jinfen,
      clumber: data.clumber,
      chengjiaoliang: data.chengjiaoliang,
      zaixianZhuangtai: data.zaixianzhuangtai,
      dashouzhuangtai: data.dashouzhuangtai,
    };
    Object.keys(map).forEach(key => {
      if (map[key] !== undefined) {
        app.globalData[key] = map[key];
      }
    });
  },

  _isGuanshiPageActive() {
    return this.data.isGuanshi || isRoleStatusActive(wx.getStorageSync('guanshistatus'));
  },

  _applyRegisterSuccess(userData, toastMsg) {
    const app = getApp();
    const data = userData || {};
    if (data.token) wx.setStorageSync('token', data.token);
    if (data.token) app.globalData.token = data.token;

    syncProfileFields(data);
    syncRoleStatuses(data);

    if (!Object.prototype.hasOwnProperty.call(data, 'guanshistatus') &&
        !isRoleStatusActive(wx.getStorageSync('guanshistatus'))) {
      this._syncGuanshiCache();
    }
    this._syncDashouGlobalData(data);

    syncGroupFields(data);

    const guanshiData = {
      gszhstatus: data.gszhstatus ?? '',
      yaoqingzongshu: data.yaoqingzongshu ?? 0,
      fenyongzonge: data.fenyongzonge ?? '0.00',
      fenyongtixian: data.fenyongtixian ?? '0.00',
      yichongzhiDashou: data.yichongzhiDashou ?? 0
    };
    if (!app.globalData.guanshi) app.globalData.guanshi = {};
    Object.assign(app.globalData.guanshi, guanshiData);

    const zhuanhualv = guanshiData.yaoqingzongshu > 0
      ? (guanshiData.yichongzhiDashou / guanshiData.yaoqingzongshu * 100).toFixed(1)
      : 0;

    this.setData({
      isGuanshi: true,
      uid: data.uid || wx.getStorageSync('uid') || '',
      nicheng: data.nicheng || app.globalData.nicheng || wx.getStorageSync('nicheng') || '',
      ...guanshiData,
      zhuanhualv,
      isLoading: false
    });
    this.loadUserInfo();
    this.switchToGuanshiRole();
    wx.hideLoading();
    if (toastMsg) {
      wx.showToast({ title: toastMsg, icon: 'success', duration: 2000 });
    }
  },

  _enterRegisteredGuanshiState(toastMsg, userData) {
    if (userData && typeof userData === 'object') {
      this._applyRegisterSuccess(userData, toastMsg);
      return;
    }
    this._syncGuanshiCache();
    this.setData({ isGuanshi: true, isLoading: false });
    this.loadUserInfo();
    this.switchToGuanshiRole();
    this.getGuanshiInfo(false);
    this.fetchChenghaoList();
    wx.hideLoading();
    if (toastMsg) {
      wx.showToast({ title: toastMsg, icon: 'success', duration: 2000 });
    }
  },

  callLoginRegisterApi(code, inviteCode) {
    const that = this;
    const app = getApp();
    const apiBaseUrl = app.globalData.apiBaseUrl;
    if (!apiBaseUrl) {
      wx.hideLoading();
      wx.showToast({ title: '服务器配置错误', icon: 'none' });
      return;
    }
    wx.request({
      url: apiBaseUrl + '/yonghu/zuzhangyqmzc',
      method: 'POST',
      data: { code: code, inviteCode: inviteCode },
      header: { 'content-type': 'application/json' },
      success: (res) => {
        const body = res.data || {};
        if (res.statusCode === 200 && isApiSuccess(body)) {
          const userData = extractUserData(body);
          const toastMsg = that._isAlreadyGuanshiMsg(getApiMsg(body))
            ? getApiMsg(body)
            : '注册成功！';
          that._applyRegisterSuccess(userData, toastMsg);
        } else if (res.statusCode === 200 && that._isAlreadyGuanshiMsg(getApiMsg(body))) {
          that._enterRegisteredGuanshiState(getApiMsg(body) || '您已是管事', extractUserData(body));
        } else {
          wx.hideLoading();
          that.setData({ isLoading: false });
          wx.showToast({ title: getApiMsg(body) || '注册失败', icon: 'none' });
        }
      },
      fail: () => {
        wx.hideLoading();
        wx.showToast({ title: '网络请求失败', icon: 'none' });
      }
    });
  },

  async callRegisterApi(inviteCode) {
    try {
      const res = await request({
        url: '/yonghu/guanshizhuce',
        method: 'POST',
        data: { inviteCode }
      });
      const body = res?.data || {};
      if (res && isApiSuccess(body)) {
        const userData = extractUserData(body);
        const toastMsg = this._isAlreadyGuanshiMsg(getApiMsg(body))
          ? getApiMsg(body)
          : '注册成功！';
        this._applyRegisterSuccess(userData, toastMsg);
      } else if (this._isAlreadyGuanshiMsg(getApiMsg(body))) {
        this._enterRegisteredGuanshiState(getApiMsg(body) || '您已是管事', extractUserData(body));
      } else {
        wx.hideLoading();
        this.setData({ isLoading: false });
        wx.showToast({ title: getApiMsg(body) || '注册失败', icon: 'none' });
      }
    } catch (e) {
      console.error('注册失败:', e);
      wx.hideLoading();
      this.setData({ isLoading: false });
      wx.showToast({ title: e.message || '注册失败', icon: 'error' });
    }
  },

  switchToGuanshiRole() {
    ensureRoleOnCenterPage(this, 'guanshi');
  },

  checkGlobalData() {
    const app = getApp();
    const gd = app.globalData.guanshi || {};
    const needRefresh = !gd.yaoqingzongshu && !gd.fenyongzonge && !gd.fenyongtixian;
    if (needRefresh) {
      this.getGuanshiInfo();
    } else {
      this.setDataFromGlobalData();
    }
  },

  setDataFromGlobalData() {
    const gd = getApp().globalData.guanshi || {};
    const zhuanhualv = gd.yaoqingzongshu > 0
      ? (gd.yichongzhiDashou / gd.yaoqingzongshu * 100).toFixed(1)
      : 0;
    this.setData({
      gszhstatus: gd.gszhstatus || '',
      yaoqingzongshu: gd.yaoqingzongshu || 0,
      fenyongzonge: gd.fenyongzonge || '0.00',
      fenyongtixian: gd.fenyongtixian || '0.00',
      yichongzhiDashou: gd.yichongzhiDashou || 0,
      zhuanhualv,
      isLoading: false
    });
  },

  async getGuanshiInfo(showToast = true) {
    this.setData({ isLoading: true });
    try {
      const res = await request({
        url: '/yonghu/guanshixinxi',
        method: 'POST'
      });
      if (res && isApiSuccess(res.data)) {
        const data = extractUserData(res.data);
        const app = getApp();
        this._syncGuanshiCache();
        if (!app.globalData.guanshi) app.globalData.guanshi = {};
        const updateData = {
          gszhstatus: data.gszhstatus || '',
          yaoqingzongshu: data.yaoqingzongshu || 0,
          fenyongzonge: data.fenyongzonge || '0.00',
          fenyongtixian: data.fenyongtixian || '0.00',
          yichongzhiDashou: data.yichongzhiDashou || 0
        };
        Object.assign(app.globalData.guanshi, updateData);
        const zhuanhualv = updateData.yaoqingzongshu > 0
          ? (updateData.yichongzhiDashou / updateData.yaoqingzongshu * 100).toFixed(1)
          : 0;
        this.setData({
          isGuanshi: true,
          ...updateData,
          zhuanhualv,
          isLoading: false
        });
        if (showToast) {
          wx.showToast({ title: '信息已更新', icon: 'success', duration: 1500 });
        }
      } else {
        this.setData({ isLoading: false });
        if (showToast) {
          wx.showToast({ title: getApiMsg(res?.data) || '获取失败', icon: 'none' });
        }
      }
    } catch (e) {
      this.setData({ isLoading: false });
      if (showToast) {
        wx.showToast({ title: e.message || '获取失败', icon: 'error' });
      }
    }
  },

  refreshGuanshiInfo() {
    this.throttledRefresh(() => {
      this.getGuanshiInfo();
      this.fetchChenghaoList();
    });
  },

  onInviteCodeInput(e) {
    this.setData({ inviteCode: e.detail.value.trim() });
  },

  async onRegister() {
    const { inviteCode } = this.data;
    if (!inviteCode) {
      wx.showToast({ title: '请输入邀请码', icon: 'none' });
      return;
    }
    if (inviteCode.length > 100) {
      wx.showToast({ title: '邀请码过长', icon: 'none' });
      return;
    }
    this.setData({ isLoading: true });
    try {
      const res = await request({
        url: '/yonghu/guanshizhuce',
        method: 'POST',
        data: { inviteCode }
      });
      const body = res?.data || {};
      if (res && isApiSuccess(body)) {
        const userData = extractUserData(body);
        const toastMsg = this._isAlreadyGuanshiMsg(getApiMsg(body))
          ? getApiMsg(body)
          : '注册成功！';
        this._applyRegisterSuccess(userData, toastMsg);
      } else if (this._isAlreadyGuanshiMsg(getApiMsg(body))) {
        this._enterRegisteredGuanshiState(getApiMsg(body) || '您已是管事', extractUserData(body));
      } else {
        this.setData({ isLoading: false });
        wx.showToast({ title: getApiMsg(body) || '注册失败', icon: 'none' });
      }
    } catch (e) {
      this.setData({ isLoading: false });
      wx.showToast({ title: e.message || '注册失败', icon: 'error' });
    }
  },

  // 页面跳转
  goToWithdraw() { wx.navigateTo({ url: '/pages/withdraw/withdraw' }); },
  goToInviteUser() { wx.navigateTo({ url: '/pages/invite-fighter/invite-fighter' }); },
  goToMySubordinate() { wx.navigateTo({ url: '/pages/my-fighter/my-fighter' }); },
  goToRechargeRecord() { wx.navigateTo({ url: '/pages/recharge-log/recharge-log' }); },
  goToGuanshiRanking() { wx.navigateTo({ url: '/pages/manager-rank/manager-rank' }); },
  goToPromoPoster() { wx.navigateTo({ url: '/pages/poster/poster' }); }
}, {
  roleConfig: {
    role: 'dashou',
    statusKey: 'guanshistatus',
    dataFlag: 'isGuanshi',
    pageId: 'guanshiduan',
    apiUrl: '/yonghu/guanshixinxi'
  }
}));
