<template>
  <div class="homePage">
    <!-- 首页 -->
    <Index @indexPage="indexPage" v-if="showIndex" />

    <!-- 加载页 -->
    <Loading v-if="!showIndex" />
  </div>
</template>

<script setup>
import {
  onBeforeMount,
  onMounted,
  defineEmits,
  defineProps,
  reactive,
  ref,
  toRefs,
  getCurrentInstance,
  computed,
} from "vue";
import gsap from "gsap";
import axios from "axios";
import { Toast, Dialog } from "vant";
import { useStore } from "vuex";
// import { get_authorize, get_jssdk } from '@/api/authorize-api'
import service from "@/api/httpServe";
import qs from "qs";
import h5plugin from "@/utils/plugin";
import Index from "@/components/Index";
import Loading from "@/components/Loading";
import imgList from "@/data/imgList";

// 初始化
const emit = defineEmits(["indexPage"]); // 声明触发事件，对应父组件上面的方法
const props = defineProps({ sendMessage: Object }); // 获取props
const store = useStore(); //初始化vuex
const { proxy } = getCurrentInstance(); //初始化全局方法：plugin工具箱

// 变量定义
const authData = ref("");
const authCode = ref("");
const showIndex = ref(false);

// 活动参与人数
const getActivityNum = () => {
  return service.post(
    process.env.VUE_APP_API + "/cms-activity/cms88/user/count/"
  );
  // .then((res) => {
  //   console.log(res.data.data);
  //   store.commit({
  //     type: "updateParticipantNum",
  //     participantNum: res.data.data,
  //   });
  // });
};

// 是否在活动期间生日
const getBrithday = () => {
  return service.post(
    process.env.VUE_APP_API + "/cms-activity/cms88/user/isin/birthday",
    {}
  );
};

// 查询是否添加了企微： isInActivityDate 0活动前是否存在 1活动期间是否存在
const getIsAddService = (id) => {
  let isInActivityDate = id;
  return service.post(
    process.env.VUE_APP_API +
      "/cms-activity/cms88/qywx/isadded/" +
      isInActivityDate,
    {}
  );
};

// 红包记录
const getMyPrizeRecored = () => {
  return service.post(
    process.env.VUE_APP_API + "/cms-activity/cms88/prize/list",
    {}
  );
};

// 查询员工企业-微信二维码
const gerCardId = (carid) => {
  return service.get(
    process.env.VUE_APP_API + "/cms-activity/cms88/card/qrcode/" + carid
  );
};

// 获取绑定的资金账号
const getInfo = () => {
  return service.post(
    process.env.VUE_APP_API + "/cms-activity/cms88/nkh/info",
    {}
  );
};

// 接口数据处理
const apiAll = () => {
  // 页面挂载前请求接口
  Promise.all([
    gerCardId(store.state.userAccount.cardId),
    getInfo(),
    getMyPrizeRecored(),
    getBrithday(),
    getActivityNum(),
    getIsAddService(0),
    getIsAddService(1),
  ]).then((result) => {
    // console.log("接口都请求完成", result);
    console.log("1.获取企业微信二维码：", result[0].data);
    console.log("2.获取资金账号：", result[1].data);
    console.log("3.获取红包记录：", result[2].data);
    console.log("4.获取生日状态：", result[3].data);
    console.log("5.获取活动人数：", result[4].data);
    console.log("6.获取添加企业微信状态【活动前是否存在】：", result[5].data);
    console.log("7.获取添加企业微信状态【活动期间是否添加】：", result[6].data);

    // 更细二维码
    store.commit({ type: "updateeEqcodeImg", eqcodeImg: result[0].data.data });
    // 更新资金账号记录
    store.commit({ type: "updateeNkh", nkh: result[1].data.data });

    // 更新红包记录
    store.commit({ type: "updatePrizeList", prizeList: result[2].data.data });

    // 更新生日状态
    store.commit({ type: "updateBirthMoon", isBirthMon: result[3].data.data });

    // 更新活动人数
    store.commit({
      type: "updateParticipantNum",
      participantNum: result[4].data.data,
    });

    // 更新添加企微状态：活动前是否存在
    store.commit({
      type: "updateisAddCustomerBefore",
      isAddCustomerBefore: result[5].data.data,
    });

    // 更新添加企微状态：活动期间
    store.commit({
      type: "updateIsAddCustomer",
      isAddCustomer: result[6].data.data,
    });

    // 预加载图片资源
    pageImgsArrLoad(imgList).then(() => {
      console.log("load done");
      showIndex.value = true;
      gsap.from(".homePage", { duration: 0.1, autoAlpha: 0, y: 100 });
    });
  });
};

// 页面未挂载
onBeforeMount(() => {
  goBackEvent()

  if (!h5plugin.isWX()) {
    apiAll();
  }

  console.log("link：", window.location.href);
  console.log("用户活动信息：", store.state.userAccount);

  console.log("code:", h5plugin.getQueryString("code"));

  // 微信环境授权
  if (h5plugin.isWX()) {
    if (h5plugin.getQueryString("code")) {
      // 存在code的话去换取openid
      authCode.value = h5plugin.getQueryString("code");
      getOpenId(authCode.value);
    } else {
      getCode();
    }
  }
});

// 页面挂载
onMounted(() => {
  fontAdpat();
  // stopBack()
});

// 来自首页的事件
const indexPage = (actions) => {
  console.log("来自index组件：", actions);
};

const getCode = () => {
  let redirect_uri = window.location.href;

  service
    .post(process.env.VUE_APP_API + "/cms-activity/cms88/zsApi/xfhdAuthorize", {
      redirect_uri: redirect_uri,
    })
    .then((res) => {
      let code = res.data.data;
      console.log("get code结果3", res);
      authCode.value = res.data.data;
      window.location.href = res.data.data;
      // location.href = res.data.data;
      // window.open(res.data.data)
    });
};

// 授权获取openid
const getOpenId = (code) => {
  service
    .post(
      process.env.VUE_APP_API + "/cms-activity/cms88/zsApi/oauthInfo",
      // qs.stringify({
      //   code: code
      // })
      {
        code: code,
      }
    )
    .then((res) => {
      if (res.data.code == 0) {
        console.log("后端返回的openid：", res.data);
        // 更新openid
        store.commit({ type: "updateXGLOpenid", openid: res.data.data });
        apiAll();
      }
    });
};

// 资源预加载器
const imgPreloader = (url) => {
  return new Promise((resolve, reject) => {
    let image = new Image();
    image.src = url;
    image.onload = () => {
      resolve();
    };
    image.onerror = () => {
      reject();
    };
  });
};

// 加载进度监控
const pageImgsArrLoad = (imgs) => {
  let promiseArr = [];
  imgs.forEach((element) => {
    promiseArr.push("img", imgPreloader(element));
  });
  return Promise.all(promiseArr);
};

// 字体适配
const fontAdpat = () => {
  if (
    typeof WeixinJSBridge == "object" &&
    typeof WeixinJSBridge.invoke == "function"
  ) {
    handleFontSize();
  } else {
    if (document.addEventListener) {
      document.addEventListener("WeixinJSBridgeReady", handleFontSize, false);
    } else if (document.attachEvent) {
      document.attachEvent("onWeixinJSBridgeReady", handleFontSize);
    }
  }
  function handleFontSize() {
    // 设置网页字体为默认大小
    WeixinJSBridge.invoke("setFontSizeCallback", { fontSize: 0 });
    // 重写设置网页字体大小的事件
    WeixinJSBridge.on("menu:setfont", function () {
      WeixinJSBridge.invoke("setFontSizeCallback", { fontSize: 0 });
    });
  }
};

// 禁止返回
const stopBack = () => {
  history.pushState(null, null, document.URL);

  window.addEventListener("popstate", function () {
    // history.pushState(null, null, document.URL);
    history.back(-1);
  });
};

// 监听后退事件
const goBackEvent = () => {
  // history.pushState({ page: 1 }, null, window.location.href);
  //然后监听popstate事件
  window.addEventListener("popstate", (event) => {
    console.log("退出");
    wx.miniProgram.navigateBack();
  });
};
</script>

<style lang="scss" scoped>
* {
  -webkit-touch-callout: none;
  -webkit-user-select: none;
  -khtml-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}

div {
  color: #fff;
}

.homePage {
  font-size: 24px;
  width: 750px;
  max-width: 750px;
  height: 100%;
  overflow: hidden;
  position: absolute;
  top: 0;
  left: 0;
  background: #ffd195;
}
</style>