// pages/assessor/assessor.js
import { createPage, request, isCenterPageActive, ensureRoleOnCenterPage } from '../../utils/base-page.js';

Page(createPage({
  data: {
    isKaoheguan: 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
    },
    planetPaused: {
      top: false,
      bottom: false,
      left: false,
      right: false
    }
  },

  _planetTimers: {},

  onLoad() {
    wx.redirectTo({ url: '/pages/fighter/fighter' });
    return;
    const icons = this.initImageUrls({
      'icons.refresh': 'beijing/kaohe/shuaxin.png',
      'icons.tixian': 'beijing/kaohe/tixian.png',
      'icons.daofen': 'beijing/kaohe/daofen.png',
      'icons.jilu': 'beijing/kaohe/jilu.png',
      'icons.zhongxin': 'beijing/kaohe/zhongxin.png',
      'icons.bgImage': 'beijing/kaohe/top_bg.jpg'
    });
    this.setData(icons);

    this.checkRoleStatus();
    if (this.data.isKaoheguan) {
      this.getKaoheguanInfo();
    }
    this.checkColdStartPopup('kaoheguanduan');
  },

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

  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, 'dashou');
      } 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() {
    this.registerWithInviteCode({
      inviteCode: this.data.inviteCode,
      apiUrl: '/dengji/khgzc',
      role: 'dashou',
      statusKey: 'kaoheguanstatus',
      successMsg: '注册成功',
      onSuccess: async () => {
        this.loadUserInfo();
        await this.getKaoheguanInfo();
        ensureRoleOnCenterPage(this, 'dashou');
      }
    });
  },

  refreshKaoheInfo() {
    this.throttledRefresh(this.getKaoheguanInfo);
  },

  goToWithdraw() {
    const yue = this.data.kaoheData.yue || 0;
    wx.navigateTo({
      url: `/pages/withdraw/withdraw?amount=${yue}&from=kaoheguan`
    });
  },
  goToDafen() { wx.navigateTo({ url: '/pages/assess-score/assess-score' }); },
  goToJilu() { wx.navigateTo({ url: '/pages/assess-log/assess-log' }); },
  goToZhongxin() { wx.navigateTo({ url: '/pages/assess-center/assess-center' }); },

  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);
  }
}, {
  roleConfig: {
    role: 'dashou',
    statusKey: 'kaoheguanstatus',
    dataFlag: 'isKaoheguan',
    pageId: 'kaoheguanduan',
    apiUrl: '/dengji/khgsx'
  }
}));
