"use strict";
import React from "react";
import { observer } from "mobx-react";
import { _asyncThrottle } from "@src/utils/utils";
import store from "@src/store";
import shareStore from "@src/store/share";
import modalStore from "@src/store/modal";
import { opfStatisticSdkClick } from "@src/store/opfStatisticSdk";
import { noUrl } from "@src/utils/share";
import { RES_PATH } from "../../../sparkrc.js";
import "./index.less";
import { handleLogClick, handleLogExposure } from "../../../MD";
import { Toast } from "@spark/ui";

@observer
class ShouYe extends React.Component {
  state = {
    firstList: [],
    secondList: [],
    thirdList: [],
  };
  constructor(props) {
    super(props);
  }

  async componentDidMount() {
    // 获取首页信息
    await store.fetchHomeInfo();
    // 获取用户信息
    await store.getUserInfo();
    this.handleBannerList();
    // 埋点注册
    await store.initStatistic();
    // 首页曝光埋点
    handleLogExposure(1, 1);
    // 首页-分享按钮
    handleLogExposure(1, 2);
    // 首页-分会场活动按钮曝光
    store?.homeInfo?.activityInfo?.map((act, index) => {
      handleLogExposure(1, 3, `${index + 1}_${act.remark}分会场活动按钮`);
    });
  }

  handleBannerList = () => {
    const data = this.groupByOrderTo2DArray(store.homeInfo.bannerInfo);
    const firstList = data?.[0] || [];
    const secondList = data?.[1] || [];
    const thirdList = data?.[2] || [];
    console.log("data", data);
    this.setState({
      firstList,
      secondList,
      thirdList,
    });

    /** 薪有所定 */
    firstList.map((item, index) => {
      handleLogExposure(1, 6, item.activityId, index + 1);
    });
    /** 薪享安心 */
    secondList.map((item, index) => {
      handleLogExposure(1, 7, item.activityId, index + 1);
    });
    /** 薪投外部 */
    thirdList.map((item, index) => {
      handleLogExposure(1, 8, item.activityId, index + 1);
    });
  };

  groupByOrderTo2DArray(data) {
    if (!Array.isArray(data)) return [];

    const result = [];
    let prevOrder = null;

    data
      .slice() // 创建副本避免修改原数组
      .sort((a, b) => a.index - b.index) // 按 order 排序
      .forEach((item) => {
        if (prevOrder === null || item.index !== prevOrder) {
          result.push([]); // 新建子数组
        }
        result[result.length - 1].push(item);
        prevOrder = item.index;
      });

    return result;
  }

  handleClickJump = _asyncThrottle(async (item, index) => {
    await store.appAuth(() => {
      handleLogClick(1, 3, `${index + 1}_${item.remark}分会场活动按钮`);
      opfStatisticSdkClick(`join-btn-${index + 1}`, `首页-${item.remark}分会场活动按钮`);

      // 如果没有规则内容，直接跳转
      const { rule, wxUrl, appUrl } = item;
      if (!rule) {
        if (noUrl({ wxUrl, appUrl })) {
          Toast("活动暂未开始");
        } else {
          setTimeout(() => store.jumpLink(item));
        }
        return;
      }
      // 有规则内容，显示弹窗
      setTimeout(() => modalStore.pushPop("RulePop", { item }));
    });
  }, 500);

  handleClickBanner = _asyncThrottle(async (item, index, type) => {
    if (noUrl(item)) return;
    await store.appAuth(() => {
      handleLogClick(1, type, item.activityId, index + 1);
      opfStatisticSdkClick(`level-${type - 5}-card-${index + 1}`, item.activityId);
      setTimeout(() => store.jumpLink(item));
    });
  }, 500);

  handleClickShare = _asyncThrottle(async () => {
    handleLogClick(1, 2);
    opfStatisticSdkClick(`share-btn`, "首页-分享按");
    shareStore.doShare();
  }, 1000);

  render() {
    const { activityInfo = [] } = store.homeInfo;
    const { pageBgImg } = store.frontVariable;
    const { firstList = [], secondList = [], thirdList = [] } = this.state;

    return (
      <div className="shouYe">
        <img className="beiJing" src={pageBgImg || RES_PATH + "首页/背景.png"} alt="bg" />
        <div className="activityInfo">
          {activityInfo?.map((item, index) => (
            <span
              key={"activity_" + index}
              className={`item item_${index}`}
              onClick={() => this.handleClickJump(item, index)}>
              <img src={item.buttonImg} alt="" />
            </span>
          ))}
        </div>
        <div className="bannerInfo">
          <div className={`scroll-wrapper scroll-wrapper1 ${firstList?.length <= 3 ? "scroll-wrapper-center" : ""}`}>
            {firstList?.map((item, index) => (
              <span
                key={"banner_" + index}
                className={`banner banner_${index}`}
                onClick={() => this.handleClickBanner(item, index, 6)}>
                <img src={item.bannerImg} alt="" />
              </span>
            ))}
          </div>
          <div className={`scroll-wrapper scroll-wrapper2 ${secondList?.length <= 3 ? "scroll-wrapper-center" : ""}`}>
            {secondList?.map((item, index) => (
              <span
                key={"banner_" + index}
                className={`banner banner_${index}`}
                onClick={() => this.handleClickBanner(item, index, 7)}>
                <img src={item.bannerImg} alt="" />
              </span>
            ))}
          </div>
          <div className={`scroll-wrapper scroll-wrapper3 ${thirdList?.length <= 3 ? "scroll-wrapper-center" : ""}`}>
            {thirdList?.map((item, index) => (
              <span
                key={"banner_" + index}
                className={`banner banner_${index}`}
                onClick={() => this.handleClickBanner(item, index, 8)}>
                <img src={item.bannerImg} alt="" />
              </span>
            ))}
          </div>
        </div>
        <span className="share" onClick={this.handleClickShare}></span>

        {/* <FloatingIcon /> */}
      </div>
    );
  }
}

export default ShouYe;
