import { makeAutoObservable, } from 'mobx';
import API from '../api/index';
import { Toast } from "@grace/ui";
import { initWx, IWxShareInfo } from "@/built-in/share/weixin/weixin.ts";
import { _asyncThrottle, _debounce, getUrlParam, waitTime } from '@/utils/utils';
// import { IBubbleInfo } from "@/pages/HomePage/Top/Components/Bubble.ts";
// import { IOverflowBubbleInfo } from "@/pages/HomePage/Top/Components/OverflowBubble.ts";
import { getDomain } from '@spark/dbdomain';
import { showShareGuide } from '@spark/share';
import { ModalCtrl } from '@/core/ctrls/ModalCtrl';
import RankPrizePop from '@/panels/RankPrizePop/RankPrizePop';
import RankNoPrizePop from '@/panels/RankNoPrizePop/RankNoPrizePop';
import RulePop from "../components/rulepop/rulepop.jsx";
import LoginPop from "../components/loginpop/loginpop.jsx"

class Store {

  constructor() {
    makeAutoObservable(this);
  }

  baseInfo: any = {};

  /** 前端开发配置 */
  frontVariable: {
    shareInfo: any,
    ruleImg?: string,
    SaleManUrl?: string,
  } = {
      shareInfo: {
        title: "",
        desc: "",
        imgUrl: "",
      },
    };

  ruleInfo = '';

  /** 积分门票 */
  ticketNum = null;

  /** 获取活动规则 */
  async initRule() {
    // 模拟获取远程的数据
    const { data } = await API.getRule();
    this.ruleInfo = data;
  }

  /** 获取前端配置项 */
  async getFrontVariable() {
    // 获取前端开发配置
    const { data } = await API.getFrontVariable();
    this.frontVariable = data || {};
    console.log('前端开发配置', data)
  }

  /** 绑定手机号接口返回状态 */
  isApiCheckBack: false
  setIsApiCheckBack(status) {
    this.isApiCheckBack = status;
  }
  /** 校验是否绑定手机号 */
  async checkBindStatus() {
    const { success, data } = await API.checkBind({
      appId: getUrlParam("appId"),
      dbredirect: encodeURIComponent(window.location.href),
    });
    console.info("%c data", "font-size: 30px", data);
    if (success && data) {
      if (data?.bind) {
        if (data?.url) {
          location.replace(data?.url);
        } else {
          // 已经绑定过，跳转完后端返回的免登链接时，展示页面
          this.setIsApiCheckBack(true); // 助力
          return true;
        }
      } else {
        this.setIsApiCheckBack(true);
        ModalCtrl.showModal(LoginPop);
      }
      await waitTime(200);
    }
    return false;
  }

  indexData: {
    actStartTime?: number,  // 对应mock中的actStartTimestamp
    actEndTime?: number,    // 对应mock中的actEndTimestamp
    currentTime?: number,   // 对应mock中的currentTimestamp
    
    answerChance?: number,
    rank?: number,
    uid?: string,
    avatar?: string,
    isAgent?: boolean,
    agreePrivacy?: boolean,
    boundYkCode?: string,
    validUid?: boolean,
    rulePop?: boolean,
    rankPop?: {
      prizeName?: string | null,
      prizeImg?: string,
      rank?: number
    },

  } = {};
  firstIn = true;
  async updateIndex() {
    const { success, data } = await API.index();
    if (!success) {
      return;
    }
    this.indexData = data;

    /** 绑定业务员code判断 */
    if (data?.boundYkCode) {
      // 已绑定
      CFG.workerCode = data?.boundYkCode;
    } else {
      // 未绑定 从链接上取-无论是否有都要调用
      if (!data?.isAgent) {
        /**后端说增加非业务员才调用 */
        const res = await this.bindYkCode(CFG.workerCode || "");

        if (res.success && res.data?.code) {
          CFG.workerCode = res.data?.code;
        }
      }
    }

    if (this.firstIn && data.validUid) {
      API.visit()
      this.firstIn = false
    }

    if (data.rulePop) {
      ModalCtrl.showModal(RulePop)
    }

    if (data?.rankPop) {
      if (data?.rankPop?.prizeName) {
        ModalCtrl.showModal(RankPrizePop, {
          prize: data?.rankPop
        })
      } else {
        ModalCtrl.showModal(RankNoPrizePop, {
          prize: data?.rankPop
        })
      }
    }
  }

  /**
   * 更新首页信息，给倒计时用的
   */
  updateIndexThrottle = _debounce(async () => {
    return await this.updateIndex();
  }, 500);

  // 活动时间拦截
  // 结束不拦截 brakeEnd为false
  // 规则奖品始终可以点击 不用调方法 
  judgeActTime(brakeStart = true, brakeEnd = true) {
    if (brakeStart && this.indexData.currentTime < this.indexData.actStartTime) {
      Toast.show("活动未开始");
      return false
    } else if (brakeEnd && this.indexData.currentTime > this.indexData.actEndTime) {
      Toast.show("活动已结束");
      return false
    }
    return true;
  }


  async bindYkCode(code) {
    const res = await API.bindYk({
      code: code,
    });
    return res;
  }
}

export default (new Store());
