import {
  makeAutoObservable
} from 'mobx';
import { userInfoApi } from '../api/api';
import {
  delUrlParam,
  getUrlParam,
  isIos,
} from '../utils';
import Toast from '../components/toast';
import { getQRCode, randomStr, url2Base64, waitTime } from '../utils/utils';
import CryptoJS from 'crypto-js'
import modalStore from './modal';
import { GetCurrSkinId, getCustomShareId } from "../utils/utils";
import { PAGE_MAP } from '../utils/constants';
import { indexApi } from "../api/api.js";
import { initSensors } from '../utils/sensorMd.js';
export const skinId = GetCurrSkinId() || getCustomShareId();
const store = makeAutoObservable({

  /** 当前页面 */
  curPage:
    {
      // index: PAGE_MAP.HOME_PAGE,
    }[skinId] || PAGE_MAP.HOME_PAGE,

  pageData: {},

  changePage(val) {
    this.curPage = val
  },

  indexInfo: {},
  async getIndexInfo() {
    const res = await indexApi({
      channel: CFG.channel
    })
    console.log(res)
    if (res.ok) {
      const resData = res.data || {}
      store.indexInfo = resData

      let { medalInfoList, newGetMedalInfoList } = resData
      if (newGetMedalInfoList && newGetMedalInfoList.length > 0) {
        newGetMedalInfoList = newGetMedalInfoList.map(item => {
          const medalInfo = medalInfoList.find(medal => medal.medalId === item.medalId)
          return {
            ...item,
            ...medalInfo
          }
        })
        modalStore.pushPop('LightNewPop', { newGetMedalInfoList })
      }
    }
  },

  // 活动时间拦截
  // 结束不拦截 brakeEnd为false
  // 规则奖品始终可以点击 不用调方法 
  checkActivityStatus(brakeStart = true, brakeEnd = true) {
    const activityBaseInfo = store.indexInfo.activityBaseInfo;
    if (activityBaseInfo && activityBaseInfo.startTime && activityBaseInfo.endTime) {
      const startTime = activityBaseInfo.startTime;
      const endTime = activityBaseInfo.endTime;
      const now = new Date().getTime();
      if (brakeStart && now < startTime) {
        Toast('活动暂未开始')
        return false;
      }
      if (brakeEnd && now > endTime) {
        Toast('活动已经结束')
        return false;
      }
    } else {
      Toast('活动异常~')
      return false;
    }
    return true;
  },

  // 跳转至【官微大转盘】
  jumpDraw() {
    wx.miniProgram.navigateTo({
      url: ' /packageTbzy/pages/lottery/lottery?activityCode=DRAWFARM&source_channel=nianjianhuodong'
    })
  },


  userInfo: {},
  setUserInfo(userInfo) {
    this.userInfo = userInfo;
  },
  /** 初始化神策埋点 */
  async initSensorsMd() {
    const res = await userInfoApi();
    if (res.ok) {
      store.setUserInfo(res.data || {});
      const { unionid, openId, friendEmpNo, friendOpenId, empNo } = res.data || {};
      // initSensors(unionId, openId, friendEmpNo, friendOpenId);
      initSensors(unionid, empNo, res.data);
    }
  },
});

export default store;

