// 佣金记录（三合一：接单佣金 / 管事分佣 / 组长分红）
import request from '../../utils/request.js';
import { getOrderStatusText } from '../../utils/api-helper.js';
import { isRoleStatusActive } from '../../utils/base-page.js';

const MEIYE_TIAOSHU_GUANSHI = 50;
const PAGE_SIZE_DASHOU = 15;
const PAGE_SIZE_ZUZHANG = 5;
const REFRESH_CD = 2000;

const TAB_MAP = {
  dashou: 'dashou',
  commission: 'dashou',
  guanshi: 'guanshi',
  recharge: 'guanshi',
  zuzhang: 'zuzhang',
  fenhong: 'zuzhang',
};

Page({
  data: {
    activeTab: 'dashou',
    tabs: [],

    isDashou: false,
    isGuanshi: false,
    isZuzhang: false,

    // 管事分佣统计
    yaoqingzongshu: 0,
    fenyongzonge: '0.00',
    chongzhiDashouShuliang: 0,

    // 组长分红统计
    fenhongZonge: '0.00',
    yaoqingGuanshi: 0,
    fenhongCishu: 0,

    // 接单佣金列表
    dashouCommissionList: [],
    dashouPage: 1,
    dashouHasMore: true,
    dashouTotal: 0,

    // 管事分佣列表
    guanshiList: [],
    guanshiPage: 1,
    guanshiHasMore: false,
    guanshiTotal: 0,

    // 组长分红列表
    zuzhangList: [],
    zuzhangPage: 1,
    zuzhangHasMore: true,
    zuzhangTotal: 0,

    jiazaiZhong: false,
    jiazaiGengduo: false,
    shuaxinKezhi: false,
    cuowuTishi: '',

    loadedTabs: {},
    scrollTop: 0,
  },

  onLoad(options) {
    this._initRoles();
    const requested = TAB_MAP[(options.tab || options.type || '').trim()] || 'dashou';
    const tabs = this._buildTabs();
    const activeTab = tabs.find((t) => t.key === requested)?.key || tabs[0]?.key || 'dashou';

    this.setData({ tabs, activeTab }, () => {
      if (this.data.isGuanshi) this.huoquQuanjubianliang();
      this._loadTab(activeTab, true);
    });
  },

  onShow() {
    this.registerNotificationComponent();
    if (this.data.isGuanshi) this.huoquQuanjubianliang();
  },

  registerNotificationComponent() {
    const app = getApp();
    const notificationComp = this.selectComponent('#global-notification');
    if (notificationComp && notificationComp.showNotification) {
      app.globalData.globalNotification = {
        show: (data) => notificationComp.showNotification(data),
        hide: () => notificationComp.hideNotification(),
      };
    }
  },

  _initRoles() {
    const isDashou = isRoleStatusActive(wx.getStorageSync('dashoustatus'));
    const isGuanshi = isRoleStatusActive(wx.getStorageSync('guanshistatus'));
    const isZuzhang = isRoleStatusActive(wx.getStorageSync('zuzhangstatus'));
    this.setData({
      isDashou: isDashou || (!isGuanshi && !isZuzhang),
      isGuanshi,
      isZuzhang,
    });
  },

  _buildTabs() {
    const { isDashou, isGuanshi, isZuzhang } = this.data;
    const tabs = [];
    if (isDashou) tabs.push({ key: 'dashou', label: '接单佣金' });
    if (isGuanshi) tabs.push({ key: 'guanshi', label: '管事分佣' });
    if (isZuzhang) tabs.push({ key: 'zuzhang', label: '组长分红' });
    if (!tabs.length) tabs.push({ key: 'dashou', label: '接单佣金' });
    return tabs;
  },

  onTabTap(e) {
    const key = e.currentTarget.dataset.key;
    if (key === this.data.activeTab) return;
    this.setData({ activeTab: key, cuowuTishi: '', scrollTop: 0 });
    if (!this.data.loadedTabs[key]) {
      this._loadTab(key, true);
    }
  },

  huoquQuanjubianliang() {
    const guanshiData = getApp().globalData.guanshi;
    if (guanshiData) {
      this.setData({
        yaoqingzongshu: guanshiData.yaoqingzongshu || 0,
        fenyongzonge: guanshiData.fenyongzonge || '0.00',
      });
    }
  },

  _loadTab(tab, reset) {
    if (tab === 'dashou') return this._loadDashouCommission(reset);
    if (tab === 'guanshi') return this._loadGuanshi(reset);
    if (tab === 'zuzhang') return this._loadZuzhang(reset);
    return Promise.resolve();
  },

  shuaxinShuju() {
    if (this.data.shuaxinKezhi) {
      wx.showToast({ title: `请等待${REFRESH_CD / 1000}秒`, icon: 'none' });
      return;
    }
    this.setData({ shuaxinKezhi: true, cuowuTishi: '' });
    this._loadTab(this.data.activeTab, true).finally(() => {
      setTimeout(() => this.setData({ shuaxinKezhi: false }), REFRESH_CD);
    });
  },

  shanglaJiazai() {
    const { activeTab, jiazaiGengduo, jiazaiZhong, loadedTabs } = this.data;
    if (!loadedTabs[activeTab] || jiazaiGengduo || jiazaiZhong) return;

    if (activeTab === 'dashou' && !this.data.dashouHasMore) return;
    if (activeTab === 'guanshi' && this.data.guanshiHasMore === false) return;
    if (activeTab === 'zuzhang' && !this.data.zuzhangHasMore) return;

    this._loadTab(activeTab, false);
  },

  chongshiJiazai() {
    this.setData({ cuowuTishi: '' });
    this._loadTab(this.data.activeTab, true);
  },

  async _loadDashouCommission(reset) {
    if (this.data.jiazaiZhong || this.data.jiazaiGengduo) return;
    const page = reset ? 1 : this.data.dashouPage;
    if (!reset && !this.data.dashouHasMore) return;

    this.setData({
      jiazaiZhong: reset,
      jiazaiGengduo: !reset,
      cuowuTishi: '',
    });

    try {
      const res = await request({
        url: '/dingdan/dshqdingdan',
        method: 'POST',
        data: {
          zhuangtai_list: [3, 8],
          page,
          page_size: PAGE_SIZE_DASHOU,
        },
      });
      const body = res?.data;
      if (body && (body.code === 200 || body.code === 0)) {
        const raw = body.data?.list || [];
        const rows = raw.map((item) => {
          const amt = item.jine || item.dashou_fencheng || '0.00';
          const brief = (item.jieshao || '').trim();
          const title = brief
            ? (brief.length > 18 ? `${brief.slice(0, 18)}…` : brief)
            : `订单 ${item.dingdan_id || ''}`;
          return {
            id: item.dingdan_id,
            title,
            time: item.wancheng_shijian || item.jiesuan_shijian || item.creat_time || getOrderStatusText(item.zhuangtai),
            amount: parseFloat(amt || 0).toFixed(2),
          };
        });
        const list = reset ? rows : [...this.data.dashouCommissionList, ...rows];
        const hasMore = body.data?.has_more ?? raw.length >= PAGE_SIZE_DASHOU;
        const loadedTabs = { ...this.data.loadedTabs, dashou: true };
        this.setData({
          dashouCommissionList: list,
          dashouPage: reset ? 2 : page + 1,
          dashouHasMore: hasMore,
          dashouTotal: body.data?.total || list.length,
          loadedTabs,
        });
      } else {
        this.setData({ cuowuTishi: body?.msg || '数据加载失败' });
      }
    } catch (e) {
      console.error('接单佣金加载失败', e);
      this.setData({ cuowuTishi: '网络错误，请检查网络连接' });
    } finally {
      this.setData({ jiazaiZhong: false, jiazaiGengduo: false });
    }
  },

  async _loadGuanshi(reset) {
    if (this.data.jiazaiZhong || this.data.jiazaiGengduo) return;

    if (reset) {
      this.setData({
        guanshiPage: 1,
        guanshiHasMore: false,
        guanshiList: [],
        guanshiTotal: 0,
        chongzhiDashouShuliang: 0,
      });
    } else {
      if (this.data.guanshiList.length > 0 && this.data.guanshiList.length < MEIYE_TIAOSHU_GUANSHI) {
        this.setData({ guanshiHasMore: false });
        return;
      }
      if (this.data.guanshiList.length >= this.data.guanshiTotal && this.data.guanshiTotal > 0) {
        this.setData({ guanshiHasMore: false });
        return;
      }
    }

    const dangqianYe = reset ? 1 : this.data.guanshiPage;
    this.setData({
      jiazaiZhong: reset,
      jiazaiGengduo: !reset,
      cuowuTishi: '',
    });

    try {
      const res = await request({
        url: '/shangpin/fenhonghq',
        method: 'POST',
        data: { page: dangqianYe, page_size: MEIYE_TIAOSHU_GUANSHI },
      });

      if (res.data.code === 200) {
        const data = res.data.data || {};
        const newList = this.chuliTouxiangURL(data.list || []);
        const hasMore = newList.length === MEIYE_TIAOSHU_GUANSHI;
        const loadedTabs = { ...this.data.loadedTabs, guanshi: true };
        this.setData({
          guanshiList: reset ? newList : [...this.data.guanshiList, ...newList],
          guanshiTotal: data.total || 0,
          chongzhiDashouShuliang: data.chongzhi_dashou_shuliang || 0,
          guanshiHasMore: hasMore,
          guanshiPage: reset ? 2 : dangqianYe + 1,
          loadedTabs,
        });
      } else {
        this.setData({ cuowuTishi: res.data.msg || '数据加载失败' });
      }
    } catch (e) {
      console.error('管事分佣加载失败', e);
      this.setData({ cuowuTishi: '网络错误，请检查网络连接' });
    } finally {
      this.setData({ jiazaiZhong: false, jiazaiGengduo: false });
    }
  },

  async _loadZuzhang(reset) {
    if (this.data.jiazaiZhong || this.data.jiazaiGengduo) return;
    const page = reset ? 1 : this.data.zuzhangPage;
    if (!reset && !this.data.zuzhangHasMore) return;

    this.setData({
      jiazaiZhong: reset,
      jiazaiGengduo: !reset,
      cuowuTishi: '',
    });

    try {
      const res = await request({
        url: '/shangpin/zuzhangfenhong',
        method: 'POST',
        data: { page, page_size: PAGE_SIZE_ZUZHANG },
      });

      if (res.data.code === 200) {
        const data = res.data.data || {};
        const processedList = this.processZuzhangList(data.list || []);
        const loadedTabs = { ...this.data.loadedTabs, zuzhang: true };
        if (reset) {
          this.setData({
            fenhongZonge: data.fenhong_zonge || '0.00',
            yaoqingGuanshi: data.yaoqing_guanshi || 0,
            fenhongCishu: data.fenhong_cishu || 0,
            zuzhangList: processedList,
            zuzhangTotal: data.total || 0,
            zuzhangPage: 2,
            zuzhangHasMore: processedList.length === PAGE_SIZE_ZUZHANG,
            loadedTabs,
          });
        } else {
          const newList = [...this.data.zuzhangList, ...processedList];
          this.setData({
            zuzhangList: newList,
            zuzhangPage: page + 1,
            zuzhangHasMore: processedList.length === PAGE_SIZE_ZUZHANG,
            loadedTabs,
          });
        }
      } else {
        this.setData({ cuowuTishi: res.data.msg || '数据加载失败' });
      }
    } catch (e) {
      console.error('组长分红加载失败', e);
      this.setData({ cuowuTishi: '网络错误，请检查网络连接' });
    } finally {
      this.setData({ jiazaiZhong: false, jiazaiGengduo: false });
    }
  },

  chuliTouxiangURL(list) {
    const app = getApp();
    const ossUrl = app.globalData.ossImageUrl || '';
    return list.map((item) => {
      let touxiangUrl = item.avatar || '';
      if (touxiangUrl && !touxiangUrl.startsWith('http')) {
        touxiangUrl = ossUrl + touxiangUrl;
      }
      let shijian = item.create_time || '';
      if (shijian) {
        if (/^\d+$/.test(shijian)) {
          const date = new Date(parseInt(shijian, 10));
          shijian = `${date.getMonth() + 1}月${date.getDate()}日 ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
        } else {
          try {
            const dateObj = new Date(shijian);
            shijian = `${dateObj.getMonth() + 1}月${dateObj.getDate()}日 ${String(dateObj.getHours()).padStart(2, '0')}:${String(dateObj.getMinutes()).padStart(2, '0')}`;
          } catch (err) {
            shijian = shijian.substring(0, 10);
          }
        }
      }
      return {
        ...item,
        touxiangUrl: touxiangUrl || '/images/default-avatar.png',
        shijian,
        fenhong: parseFloat(item.fenhong || 0).toFixed(2),
      };
    });
  },

  processZuzhangList(list) {
    const app = getApp();
    const ossUrl = app.globalData.ossImageUrl || '';
    const defaultAvatar = ossUrl + (app.globalData.morentouxiang || 'avatar/default.jpg');
    return list.map((item) => ({
      dashouAvatar: this.getFullUrl(item.dashou_avatar, ossUrl, defaultAvatar),
      dashouNicheng: item.dashou_nicheng || '接单员',
      dashouYonghuid: item.dashou_yonghuid || '',
      guanshiAvatar: this.getFullUrl(item.guanshi_avatar, ossUrl, defaultAvatar),
      guanshiNicheng: item.guanshi_nicheng || '管事',
      guanshiYonghuid: item.guanshi_yonghuid || '',
      fenhong: parseFloat(item.fenhong || 0).toFixed(2),
      shijian: this.formatTime(item.create_time),
    }));
  },

  getFullUrl(relativePath, ossUrl, defaultUrl) {
    if (!relativePath) return defaultUrl;
    if (relativePath.startsWith('http')) return relativePath;
    return ossUrl + (relativePath.startsWith('/') ? relativePath : `/${relativePath}`) || defaultUrl;
  },

  formatTime(timestamp) {
    if (!timestamp) return '';
    try {
      const date = new Date(timestamp);
      return `${date.getMonth() + 1}月${date.getDate()}日 ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
    } catch (e) {
      return String(timestamp).substring(0, 10) || '';
    }
  },
});
