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 { getDomain } from '@spark/dbdomain';
import { showShareGuide } from '@spark/share';
import { ModalCtrl } from '@/core/ctrls/ModalCtrl';
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() {
    // 获取前端开发配置
    console.info('time',new Date().getTime())
    const { data } = await API.getFrontVariable();
    this.frontVariable = data || {};
    console.log('前端开发配置', data)
  }

  /** 绑定手机号接口返回状态 */
  isApiCheckBack: false
  setIsApiCheckBack(status) {
    this.isApiCheckBack = status;
  }
  /** 校验是否绑定手机号 */
  async checkBindStatus() {
    // alert(encodeURIComponent(window.location.href))
    const { success, data } = await API.checkBind({
      appId: getUrlParam("appId"),
      dbredirect: 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: {
    actStartTimestamp?: number, 
    actEndTimestamp?: number,    
    currentTimestamp?: number,   
    
    leftGameTimes?: number,
    uid?: string,
    avatar?: string,
    isAgent?: boolean,
    agreePrivacyFlag?: boolean,
    boundYkCode?: string,
    validUid?: boolean,
    rulePop?: boolean,

  } = {};
  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)
    }
  }

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

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

  drawData: any = {};
  /** 获取抽奖信息 */
  getDrawInfo = async () => {
    const { success, data } = await API.drawIndex();
    if (success && data) {
      this.drawData = data || {};
    }
  };


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

export default (new Store());
