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"
import { isWeiXin } from '@/AppTools.js';
import { CHANNEL_PARAMS } from '@/utils/constants.js';
import CodePop from "../components/CodePop/CodePop.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 || {};
    }
  };

  // 点击抽奖
  doLotttery = async () => {
    // 微信端拦截
    if (isWeiXin()) {
      // 友客小程序
      if (CFG.channel == CHANNEL_PARAMS.YK_MINI) {
        return Toast.show("请前往人保寿险管家app活动抽奖～");
      }
      // 其他微信端 提醒唤端弹窗
      else {
        return ModalCtrl.showModal(CodePop);
      }
    }

    const { leftDrawTimes = 0 } = this.drawData;

    // 抽奖次数为0
    if (!leftDrawTimes) {
      return Toast.show("抽奖次数不足，快去猜谜赚次数吧～");
    }

    // 打开抽奖出奖弹窗 CK_TODO
  };


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

export default (new Store());
