<template>
  <div class="homePage">
    <!-- 加载页 -->

    <!-- 首页 -->
    <Index @indexPage="indexPage" 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 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 = () => {
  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 = () => {
  service
    .post(
      process.env.VUE_APP_API + "/cms-activity/cms88/user/isin/birthday",
      {}
    )
    .then((res) => {
      console.log("生日是否处于当月：", res.data.data);
      // store.state.userAccount.isBirthMon = 1
      store.commit({
        type: "updateBirthMoon",
        isBirthMon: res.data.data,
        // isBirthMon: 1,
      });
    });
};

// 查询是否添加了企微： isInActivityDate 0否 1是
const getIsAddService = () => {
  let isInActivityDate = 1;
  service
    .post(
      process.env.VUE_APP_API +
        "/cms-activity/cms88/qywx/isadded/" +
        isInActivityDate,
      {}
    )
    .then((res) => {
      console.log("是否添加了企微", res.data);
      // store.state.userAccount.isBirthMon = res.data.data
      store.commit({
        type: "updateIsAddCustomer",
        // isBirthMon:res.data.data,
        isAddCustomer: res.data.data,
      });
    });
};

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

      store.commit({
        type: "updatePrizeList",
        prizeList: res.data.data,
      });
    });
};

// 查询员工企业-微信二维码
const gerCardId = (carid) => {
  service
    .get(process.env.VUE_APP_API + "/cms-activity/cms88/card/qrcode/" + carid)
    .then((res) => {
      console.log("企微二维码：", res.data.data);
      store.commit({
        type: "updateeEqcodeImg",
        eqcodeImg: res.data.data,
      });
    });
};

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

// 页面未挂载
onBeforeMount(() => {
  // gerCardId(store.state.userAccount.cardId);
  // getInfo();
  // getMyPrizeRecored();
  // getBrithday();
  // getActivityNum();
  // getIsAddService();
  // 页面挂载前请求接口
  Promise.all([
    gerCardId(store.state.userAccount.cardId),
    getInfo(),
    getMyPrizeRecored(),
    getBrithday(),
    getActivityNum(),
    getIsAddService(),
  ]).then((result) => {
    console.log("接口都请求完成",result);
    // 预加载图片资源
    pageImgsArrLoad(imgList).then(() => {
      console.log("load done");
      showIndex.value = true;
      gsap.from(".homePage", { duration: 0.1, autoAlpha: 0, y: 100 });
    });
  });

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

  // 微信环境授权
  if (h5plugin.isWX()) {
    console.log("code:", h5plugin.getQueryString("code"));

    if (h5plugin.getQueryString("code")) {
      // 存在code的话去换取openid
      authCode.value = h5plugin.getQueryString("code");
      getOpenId(authCode.value);
    } else {
      getCode();
    }
  }
});

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

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

// 授权获取code
const getCode = () => {
  let redirect_uri = window.location.href;
  // service.post(process.env.VUE_APP_API + '/cms-activity/cms88/zsApi/xfhdAuthorize?redirect_uri='+redirect_uri,
  service
    .post(
      process.env.VUE_APP_API + "/cms-activity/cms88/zsApi/xfhdAuthorize",
      // qs.stringify({
      //   redirect_uri: redirect_uri
      // })

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

// 授权获取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 });
        // store.commit({ type: "updateToken", token: h5plugin.getQueryString('token') });
        // store.commit({ type: "updateCardId", cardId: h5plugin.getQueryString('cardId') });
        // store.commit({ type: "updateNkh", cardId: h5plugin.getQueryString('nkh') });
        // console.log("用户活动信息：", store.state.userAccount);
      }
    });
};

// 资源预加载器
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);
};
</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>