// pages/guanshizhongxin/guanshizhongxin.js
import request from '../../utils/request.js';
import popupService from '../../services/popupService.js';

Page({
  data: {
    // 图片路径对象（逻辑层拼接完整URL）
    imgUrls: {},

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

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

    // 称号列表
    chenghaoList: [],

    // 邀请人（组长）缓存
    inviterCache: null,
  },

  onLoad(options) {
    // 拼接所有图片完整路径
    const app = getApp();
    const ossImageUrl = app.globalData.ossImageUrl || '';
    const imgBase = ossImageUrl + 'beijing/guanshiduan/';
    this.setData({
      imgUrls: {
        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',
      }
    });

    // 处理扫码 scene
    if (options.scene) {
      try {
        const scene = decodeURIComponent(options.scene);
        options.inviteCode = scene;
      } catch (e) {
        console.error('scene解码失败', e);
      }
    }

    this.checkGuanshiStatus();

    const { inviteCode } = options || {};
    if (inviteCode) {
      this.setData({ inviteCode });
      setTimeout(() => {
        this.handleInviteCodeWithLoginCheck(inviteCode);
      }, 500);
    }

    if (!app.globalData.hasShownPopupOnColdStart) {
      app.globalData.hasShownPopupOnColdStart = true;
      setTimeout(() => {
        popupService.checkAndShow(this, 'guanshiduan');
      }, 300);
    }
  },

  onHide() {
    const popupComp = this.selectComponent('#popupNotice');
    if (popupComp && popupComp.cleanup) {
      popupComp.cleanup();
    }
  },

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

    this.registerNotificationComponent();

    if (this.data.isGuanshi) {
      setTimeout(() => {
        this.getGuanshiInfo();
        this.fetchChenghaoList();
      }, 300);
    }

    const pages = getCurrentPages();
    const currentPage = pages[pages.length - 1];
    const options = currentPage.options || {};
    if (options.inviteCode && !this.data.isGuanshi) {
      setTimeout(() => {
        this.handleInviteCodeWithLoginCheck(options.inviteCode);
      }, 300);
    }
  },

  // ========== 全局通知注册 ==========
  registerNotificationComponent() {
    const app = getApp();
    const comp = this.selectComponent('#global-notification');
    if (comp && comp.showNotification) {
      app.globalData.globalNotification = {
        show: (data) => comp.showNotification(data),
        hide: () => comp.hideNotification()
      };
    }
  },

  // ========== 称号列表（新接口，区分管事） ==========
  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 });

            // 跳转聊天（组长前缀请确认，默认 'Zz'）
            const param = {
                toUserId: 'Zz' + inviter.uid,
                toName: inviter.nicheng || '组长',
                toAvatar: fullAvatar
            };
            wx.navigateTo({
                url: '/pages/liaotian/liaotian?data=' + encodeURIComponent(JSON.stringify(param))
            });
        } else {
            wx.showToast({ title: '未绑定邀请人', icon: 'none' });
        }
    } catch (e) {
        wx.showToast({ title: '网络错误', icon: 'none' });
    } finally {
        wx.hideLoading();
    }
},
  // ========== 邀请码处理（完全照搬打手端） ==========
  handleInviteCodeWithLoginCheck(inviteCode) {
    const token = wx.getStorageSync('token');
    const uid = wx.getStorageSync('uid');
    if (!token || !uid) {
      this.loginAndRegisterWithInviteCode(inviteCode);
    } else {
      if (!this.data.isGuanshi) {
        wx.showLoading({ title: '自动注册中...', mask: true });
        this.callRegisterApi(inviteCode);
      } else {
        wx.showToast({ title: '您已是管事', icon: 'success' });
      }
    }
  },

  loginAndRegisterWithInviteCode(inviteCode) {
    const that = this;
    wx.showLoading({ title: '登录注册中...', mask: true });
    wx.login({
      success: (loginRes) => {
        if (loginRes.code) {
          that.callLoginRegisterApi(loginRes.code, inviteCode);
        } else {
          wx.hideLoading();
          wx.showToast({ title: '微信登录失败', icon: 'none' });
        }
      },
      fail: () => {
        wx.hideLoading();
        wx.reLaunch({ url: '/pages/gerenzhongxin/gerenzhongxin' });
      }
    });
  },

  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) => {
        if (res.statusCode === 200 && res.data && res.data.code === 200 && res.data.data) {
          const userData = res.data.data;
          if (userData.token) wx.setStorageSync('token', userData.token);
          const identityFields = ['nicheng', 'uid', 'touxiang', 'dashoustatus', 'guanshistatus', 'shangjiastatus', 'zuzhangstatus'];
          identityFields.forEach(field => {
            if (userData[field] !== undefined) {
              wx.setStorageSync(field, userData[field]);
              app.globalData[field] = userData[field];
            }
          });
          if (userData.guanshistatus === undefined) {
            wx.setStorageSync('guanshistatus', 1);
            app.globalData.guanshistatus = 1;
          }
          const groupFields = ['dashouqun', 'dashouqunid', 'guanshiqun', 'guanshiqunid'];
          groupFields.forEach(field => {
            if (userData[field] !== undefined) {
              wx.setStorageSync(field, userData[field]);
              app.globalData[field] = userData[field];
            }
          });
          const guanshiData = {
            gszhstatus: userData.gszhstatus || '',
            yaoqingzongshu: userData.yaoqingzongshu || 0,
            fenyongzonge: userData.fenyongzonge || '0.00',
            fenyongtixian: userData.fenyongtixian || '0.00',
            yichongzhiDashou: userData.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;
          that.setData({
            isGuanshi: true,
            uid: userData.uid || '',
            nicheng: userData.nicheng || '',
            ...guanshiData,
            zhuanhualv,
            isLoading: false
          });
          that.loadUserInfo();
          that.switchToGuanshiRole();
          wx.hideLoading();
          wx.showToast({ title: '注册成功！', icon: 'success', duration: 2000 });
        } else {
          wx.hideLoading();
          wx.showToast({ title: (res.data && res.data.msg) || '注册失败', 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 }
      });
      if (res && res.data.code === 200 && res.data.data) {
        const userData = res.data.data;
        const identityFields = ['nicheng', 'uid', 'touxiang', 'dashoustatus', 'guanshistatus', 'shangjiastatus', 'zuzhangstatus'];
        const app = getApp();
        identityFields.forEach(field => {
          if (userData[field] !== undefined) {
            wx.setStorageSync(field, userData[field]);
            app.globalData[field] = userData[field];
          }
        });
        if (userData.guanshistatus === undefined) {
          wx.setStorageSync('guanshistatus', 1);
          app.globalData.guanshistatus = 1;
        }
        const guanshiData = {
          gszhstatus: userData.gszhstatus || '',
          yaoqingzongshu: userData.yaoqingzongshu || 0,
          fenyongzonge: userData.fenyongzonge || '0.00',
          fenyongtixian: userData.fenyongtixian || '0.00',
          yichongzhiDashou: userData.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: userData.uid || '',
          nicheng: userData.nicheng || '',
          ...guanshiData,
          zhuanhualv,
          isLoading: false
        });
        this.loadUserInfo();
        this.switchToGuanshiRole();
        wx.hideLoading();
        wx.showToast({ title: '注册成功！', icon: 'success', duration: 2000 });
      } else {
        wx.hideLoading();
        wx.showToast({ title: res?.data?.msg || '注册失败', icon: 'none' });
      }
    } catch (e) {
      console.error('注册失败:', e);
      wx.hideLoading();
      wx.showToast({ title: e.message || '注册失败', icon: 'error' });
    }
  },

  switchToGuanshiRole() {
    const app = getApp();
    app.globalData.currentRole = 'guanshi';
    wx.setStorageSync('currentRole', 'guanshi');
    const tabBar = this.getTabBar();
    if (tabBar && tabBar.refresh) tabBar.refresh();
    if (app.connectForCurrentRole) {
      app.connectForCurrentRole();
    } else if (app.ensureConnection) {
      app.ensureConnection();
    }
  },

  checkGuanshiStatus() {
    try {
      const status = wx.getStorageSync('guanshistatus');
      if (status === 1) {
        this.setData({ isGuanshi: true });
        this.loadUserInfo();
        this.checkGlobalData();
      } else {
        this.setData({ isGuanshi: false });
      }
    } catch (e) {
      this.setData({ isGuanshi: false });
    }
  },

  loadUserInfo() {
    const app = getApp();
    const globalData = app.globalData || {};
    const touxiang = wx.getStorageSync('touxiang');
    const ossImageUrl = globalData.ossImageUrl || '';
    const morentouxiang = 'avatar/default.jpg';
    let avatarUrl = '';
    if (touxiang) {
      avatarUrl = ossImageUrl + (touxiang.startsWith('/') ? touxiang : '/' + touxiang);
    } else {
      avatarUrl = ossImageUrl + (morentouxiang.startsWith('/') ? morentouxiang : '/' + morentouxiang);
    }
    this.setData({
      avatarUrl,
      uid: wx.getStorageSync('uid') || '',
      nicheng: globalData.nicheng || ''
    });
  },

  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() {
    this.setData({ isLoading: true });
    try {
      const res = await request({
        url: '/yonghu/guanshixinxi',
        method: 'POST'
      });
      if (res && res.data.code === 200) {
        const data = res.data.data;
        const app = getApp();
        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({
          ...updateData,
          zhuanhualv,
          isLoading: false
        });
        wx.showToast({ title: '信息已更新', icon: 'success', duration: 1500 });
      }
    } catch (e) {
      this.setData({ isLoading: false });
      wx.showToast({ title: e.message || '获取失败', icon: 'error' });
    }
  },

  refreshGuanshiInfo() {
    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 }
      });
      if (res && res.data.code === 200) {
        const userData = res.data.data;
        const identityFields = ['dashoustatus', 'guanshistatus', 'shangjiastatus', 'zuzhangstatus'];
        const app = getApp();
        identityFields.forEach(field => {
          if (userData[field] !== undefined) {
            wx.setStorageSync(field, userData[field]);
            app.globalData[field] = userData[field];
          }
        });
        if (userData.guanshistatus === undefined) {
          wx.setStorageSync('guanshistatus', 1);
          app.globalData.guanshistatus = 1;
        }
        if (!app.globalData.guanshi) app.globalData.guanshi = {};
        const updateData = {
          gszhstatus: userData.gszhstatus || '',
          yaoqingzongshu: userData.yaoqingzongshu || 0,
          fenyongzonge: userData.fenyongzonge || '0.00',
          fenyongtixian: userData.fenyongtixian || '0.00',
          yichongzhiDashou: userData.yichongzhiDashou || 0
        };
        Object.assign(app.globalData.guanshi, updateData);
        this.setData({
          isGuanshi: true,
          ...updateData,
          isLoading: false
        });
        this.loadUserInfo();
        wx.showToast({ title: '注册成功！', icon: 'success', duration: 2000 });
      }
    } catch (e) {
      this.setData({ isLoading: false });
      wx.showToast({ title: e.message || '注册失败', icon: 'error' });
    }
  },

  copyUid() {
    const { uid } = this.data;
    if (!uid) return;
    wx.setClipboardData({
      data: uid,
      success: () => wx.showToast({ title: '已复制', icon: 'success' })
    });
  },

  // ========== 页面跳转 ==========
  goToWithdraw() { wx.navigateTo({ url: '/pages/tixian/tixian' }); },
  goToInviteUser() { wx.navigateTo({ url: '/pages/yaoqingdashou/yaoqingdashou' }); },
  goToMySubordinate() { wx.navigateTo({ url: '/pages/wodedashou/wodedashou' }); },
  goToRechargeRecord() { wx.navigateTo({ url: '/pages/czjilu/czjilu' }); },
  goToGuanshiRanking() { wx.navigateTo({ url: '/pages/guanshipaihang/guanshipaihang' }); },
  goToPromoPoster() { wx.navigateTo({ url: '/pages/haibao/haibao' }); }
});