// pages/kaoheguan/kaoheguan.js
// 只新增了两个字段的接收，其余所有代码未变
import request from '../../utils/request.js';
import {
  isRoleStatusActive,
  isCenterPageActive,
  syncRoleStatuses,
  ensureRoleOnCenterPage,
} from '../../utils/role-tab-bar.js';
const app = getApp();

Page({
  data: {
    isKaoheguan: false,
    isLoading: false,
    inviteCode: '',
    statusText: '用户尚未注册或账号已被封禁',
    uid: '',
    avatarUrl: '',
    icons: {
      refresh: '',
      tixian: '',
      daofen: '',
      jilu: '',
      zhongxin: '',
      bgImage: ''
    },
    kaoheData: {
      shenheZongshu: 0,
      tongguoZongshu: 0,
      yue: '0.00',
      zonge: '0.00',
      shenheZhuangtai: 0,
      bankuaiList: [],
      isRenzheng: false,           // 🆕 是否认证
      pendingShenheCount: 0        // 🆕 审核中数量
    },
    lastRefreshTime: 0,
    canRefresh: true,
    planetPaused: {
      top: false,
      bottom: false,
      left: false,
      right: false
    }
  },

  _planetTimers: {},

  onLoad() {
    wx.redirectTo({ url: '/pages/dashouduan/dashouduan' });
    return;
    const ossUrl = app.globalData.ossImageUrl || '';
    const iconBase = 'beijing/kaohe/';
    this.setData({
      'icons.refresh': ossUrl + iconBase + 'shuaxin.png',
      'icons.tixian': ossUrl + iconBase + 'tixian.png',
      'icons.daofen': ossUrl + iconBase + 'daofen.png',
      'icons.jilu': ossUrl + iconBase + 'jilu.png',
      'icons.zhongxin': ossUrl + iconBase + 'zhongxin.png',
      'icons.bgImage': ossUrl + iconBase + 'top_bg.jpg'
    });

    const kaoheguanstatus = wx.getStorageSync('kaoheguanstatus');
    if (isRoleStatusActive(kaoheguanstatus)) {
      this.loadUserInfo();
      this.setData({ isKaoheguan: true });
      this.getKaoheguanInfo();
      ensureRoleOnCenterPage(this, 'kaoheguan');
    } else {
      this.setData({ isKaoheguan: false });
    }
  },

  onReady() {
    if (isCenterPageActive(this, 'isKaoheguan', 'kaoheguanstatus')) {
      ensureRoleOnCenterPage(this, 'kaoheguan');
    }
  },

  onShow() {
    if (isCenterPageActive(this, 'isKaoheguan', 'kaoheguanstatus')) {
      if (!this.data.isKaoheguan) this.setData({ isKaoheguan: true });
      ensureRoleOnCenterPage(this, 'kaoheguan');
      this.refreshKaoheInfo();
    }
  },

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

  async getKaoheguanInfo() {
    this.setData({ isLoading: true });
    try {
      const res = await request({ url: '/dengji/khgsx', method: 'POST' });
      if (res && res.data.code === 200) {
        const data = res.data.data;
        if (data.zhuangtai === 0 || data.zhuangtai === 2) {
          wx.setStorageSync('kaoheguanstatus', 0);
          this.setData({ isKaoheguan: false, isLoading: false, statusText: '用户尚未注册或账号已被封禁' });
          return;
        }
        wx.setStorageSync('kaoheguanstatus', 1);
        this.setData({
          isKaoheguan: true,
          isLoading: false,
          kaoheData: {
            shenheZongshu: data.shenhe_zongshu || 0,
            tongguoZongshu: data.tongguo_zongshu || 0,
            yue: data.yue || '0.00',
            zonge: data.zonge || '0.00',
            shenheZhuangtai: data.shenhe_zhuangtai || 0,
            bankuaiList: data.bankuai_list || [],
            isRenzheng: data.is_renzheng || false,              // 🆕
            pendingShenheCount: data.pending_shenhe_count || 0  // 🆕
          }
        });
        ensureRoleOnCenterPage(this, 'kaoheguan');
      } else {
        wx.showToast({ title: res?.data?.msg || '获取信息失败', icon: 'none' });
        this.setData({ isLoading: false });
      }
    } catch (error) {
      console.error('获取考核官信息失败:', error);
      wx.showToast({ title: '网络错误', icon: 'none' });
      this.setData({ isLoading: false });
    }
  },

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

  async onRegister() {
    const { inviteCode } = this.data;
    if (!inviteCode) {
      wx.showToast({ title: '请输入邀请码', icon: 'none', duration: 2000 });
      return;
    }
    if (inviteCode.length > 100) {
      wx.showToast({ title: '邀请码不能超过100位', icon: 'none', duration: 2000 });
      return;
    }
    this.setData({ isLoading: true });
    try {
      const res = await request({
        url: '/dengji/khgzc',
        method: 'POST',
        data: { inviteCode: inviteCode }
      });
      if (res && res.data.code === 200) {
        const data = res.data.data || {};
        syncRoleStatuses(data);
        if (!Object.prototype.hasOwnProperty.call(data, 'kaoheguanstatus')) {
          wx.setStorageSync('kaoheguanstatus', 1);
        }
        wx.showToast({ title: '注册成功', icon: 'success', duration: 2000 });
        this.loadUserInfo();
        await this.getKaoheguanInfo();
        ensureRoleOnCenterPage(this, 'kaoheguan');
      } else {
        wx.showToast({ title: res?.data?.msg || '注册失败', icon: 'none', duration: 2000 });
        this.setData({ isLoading: false });
      }
    } catch (error) {
      console.error('注册失败:', error);
      wx.showToast({ title: '网络错误', icon: 'none' });
      this.setData({ isLoading: false });
    }
  },

  refreshKaoheInfo() {
    const now = Date.now();
    const lastTime = this.data.lastRefreshTime;
    const canRefresh = this.data.canRefresh;
    if (!canRefresh || (now - lastTime < 3000)) return;
    this.setData({ lastRefreshTime: now, canRefresh: false });
    this.getKaoheguanInfo();
    setTimeout(() => this.setData({ canRefresh: true }), 3000);
  },

  goToWithdraw() {
    const yue = this.data.kaoheData.yue || 0;
    wx.navigateTo({
      url: `/pages/tixian/tixian?amount=${yue}&from=kaoheguan`
    });
  },
  goToDafen() { wx.navigateTo({ url: '/pages/kaohe_dafen/kaohe_dafen' }); },
  goToJilu() { wx.navigateTo({ url: '/pages/kaohe_jilu/kaohe_jilu' }); },
  goToZhongxin() { wx.navigateTo({ url: '/pages/kaohe_zhongxin/kaohe_zhongxin' }); },

  onPlanetTouch(e) {
    const id = e.currentTarget.dataset.id;
    if (this._planetTimers[id]) {
      clearTimeout(this._planetTimers[id]);
      this._planetTimers[id] = null;
    }
    const paused = `planetPaused.${id}`;
    this.setData({ [paused]: true });
  },

  onPlanetLeave(e) {
    const id = e.currentTarget.dataset.id;
    this._planetTimers[id] = setTimeout(() => {
      const paused = `planetPaused.${id}`;
      this.setData({ [paused]: false });
    }, 5000);
  }
});