<template>
  <div>
    <keep-alive v-if="isInit" :include="cachedViews" :max="15">
      <router-view :key="key" />
    </keep-alive>
    <div v-else>
      <br />
      <br />
      <van-skeleton title :row="3" />
      <br />
      <br />
      <van-skeleton title :row="4" />
      <br />
      <br />
      <van-skeleton title :row="3" />
      <br />
      <br />
      <van-skeleton title :row="4" />
      <br />
      <br />
    </div>
    <wx-points-commit ref="wxPointsCommit"></wx-points-commit>
  </div>
</template>
<script>
import { createAxiosByinterceptors } from '@/api/request';
import Stomp from '@/lib/stompjs';
import loginMinix from '@/mixins/login';
import { Decrypt, Encrypt } from '@/utils/crypto';
import { getIsMin, getIsWxh5, getUrlParams } from '@/utils/index.js';
import SockJS from '@/utils/sockjs';
import uni from '@/utils/uniHooks';
import { getAppIdByGroupIdAndMallId } from '@/utils/index.js';

export default {
  mixins: [loginMinix],
  async created() {
    await this.initEnv();
    await this.requestInit();
    await this.init();
    // 初始化环境变量
  },
  computed: {
    cachedViews() {
      return this.$store.state.cachedViews.cachedViews;
    },
    passLogin() {
      return this.$store.state.passLogin;
    },
    key() {
      return this.$route.path;
    },
    isInit() {
      return this.$store.state.isInit;
    },
  },
  watch: {
    cachedViews() {
      console.log('cachedViews(打印已经缓存的页面)', this.cachedViews);
    },
    $route: {
      immediate: true,
      handler(route) {
        const {
          name,
          meta: { keepAlive },
        } = route;
        if (name && keepAlive) {
          this.$store.commit('cachedViews/ADD_CACHED_VIEW', route);
        }
      },
    },
  },
  methods: {
    async init() {
      uni.setStorageSync('env', window.env);
      // 如果是微信小程序。初始化wss
      if (getIsMin()) {
        // 保留 carList
        const carList = uni.getStorageSync('carList');
        // 每次进入页面清空 缓存数据
        window.localStorage.clear();
        if (carList) {
          uni.setStorageSync('carList', JSON.parse(carList));
        }

        this.$store.commit('SET_IS_INIT', false);
        window.token = `${window.location.href}`.replace(/.*wx\/(.*)\/.*/g, '$1');
        try {
          const options = await this.wss();
          this.$store.dispatch('baseInit', {
            options,
            callback: () => {
              this.$store.commit('SET_IS_INIT', true);
              // 无感积分逻辑
              this.wxEasyPointsCommitStatusInit();
            },
          });
        } catch (err) {
          console.log(err);
        }
      }
      // 如果是微信公众号
      if (getIsWxh5()) {
        // 判断用户是否登录
        this.micromessengerInit();
      }
    },
    wss() {
      return new Promise((resolve, reject) => {
        try {
          const socket = new SockJS(`${this.getUrl()}/hafengWebsocket?token=${window.token}`);
          window.stompClient = Stomp.over(socket);
          window.stompClient.debug = null;
          this.windowSendInit();
          window.stompClient.connect({}, (frame) => {
            // 请求 projectId
            window.toWXSendMsg({
              type: 'getProjectId',
              options: {},
            });
            window.subscribe('projectId', (options) => {
              resolve(options);
            });
          });
        } catch (err) {
          // console.log(err);
          reject(err);
          // callback && callback();
        }
      });
    },
    windowSendInit() {
      const token = window.token;
      // console.log(118, token);
      window.toWXSendMsg = function ({ type = '', funcName = '', options = {} }) {
        /**
         * 向小程序端发送消息
         */
        if (!type) return;
        // console.log(259, '微信支付的options', options);
        window.stompClient.send(
          '/sendToWechat',
          {},
          JSON.stringify({
            token,
            data: Encrypt(
              JSON.stringify({
                type: type,
                funcName,
                options,
              })
            ),
          })
        );
      };

      // 主动订阅事件回调
      window.subscribe = function (type, callback) {
        const subscribeId = window.stompClient.subscribe('/user/' + token + '/toH5', function (response) {
          try {
            let res = {
              token: '', // 微信小程序端 页面的传递过来的token
              data: '', // 微信小程序端 页面的传递过来的信息（已加密）
            };
            if (response.body) {
              res = JSON.parse(response.body);
            }
            // 检查 微信小程序端 发送过来的信息和token是否与当前页面的 token一致。并且 res.data 携带信息，在解密之后是 json 格式
            if (res.token && res.token === token && res.data) {
              const msgJson = JSON.parse(Decrypt(res.data));
              const reg = new RegExp(type);
              // 获取 projectId
              if (reg.test(msgJson.type)) {
                callback(msgJson.options, subscribeId);
                subscribeId.unsubscribe();
                return;
              }
            }
          } catch (err) {
            console.log('stomp error', err);
          }
        });
      };
    },
    initEnv() {
      const href = window.location.href;
      console.log('当前页面的url地址  ', href);
      if (/dev-|8080/.test(href)) {
        // window.env = 'qa';
        // window.profileApi = 'https://qa-apim.kerryplus.com/c/api';
        // window.api = 'qaApi';
        window.env = 'dev';
        window.profileApi = 'https://dev-gateway-kip.kerryonvip.com/api';
        window.api = 'devApi';
        return;
      }
      if (/qa-/.test(href)) {
        window.env = 'qa';
        window.api = 'qaApi';
        window.profileApi = 'https://qa-apim.kerryplus.com/c/api';
        return;
      }
      window.env = 'prod';
      window.profileApi = 'https://apim.kerryplus.com/c/api';
      window.api = 'api';
    },
    requestInit() {
      window.requestms = createAxiosByinterceptors({
        // baseURL: `https://dev-kip-service-internal.kerryonvip.com/`,
        // baseURL: `http://tp.hht.test/`,
        // baseURL: window.profileApi, // TODO: 微服务发布到DEV环境之后取消注释
        baseURL: `/msApi`,
      });
    },
    // websocket 链接
    getUrl() {
      // 如果 kerry+ 这边的访问环境是 sl 或者 lt，需要把 wss 指向 qa 环境。
      const href = `${window.location.href}`;
      if (/dev-|8080/.test(href)) {
        return 'https://qa-crm-kpl.kerryprops.com.cn/xcrm-api';
      }
      if (/qa-/.test(href)) {
        return 'https://qa-crm-kpl.kerryprops.com.cn/xcrm-api';
      }
      // return 'https://qa-crm-kpl.kerryprops.com.cn/xcrm-api';
      return `https://crm.kerryplus.com/xcrm-api`;
    },
    micromessengerInit() {
      this.$store.commit('SET_IS_INIT', false);
      let path = '';
      let [groupId, mallId] = window.location.pathname.split('/').filter((elm) => elm);
      console.log(265, groupId, mallId);
      // return;
      // 如果groupId 是 tparking
      if (groupId === 'tparking') {
        [path, groupId, mallId] = window.location.pathname.split('/').filter((elm) => elm);
      }
      if (!groupId || !mallId) {
        groupId = uni.getStorageSync('groupId');
        mallId = uni.getStorageSync('mallId');
      }

      this.$store.commit('SET_GROUP_ID', groupId);
      this.$store.commit('SET_MALL_ID', mallId);
      // 设置appid
      const appid = getAppIdByGroupIdAndMallId({
        groupId,
        mallId,
        type: 'appid',
      });
      uni.setStorageSync('appid', appid);
      // 如果用户没有openid
      const openid = uni.getStorageSync('openid');

      const query = getUrlParams();
      console.log(284, query, groupId, mallId);
      // return;
      // 设置openid
      this.$nextTick(() => {
        this.$store.commit('SET_IS_INIT', true);
        if (openid && openid !== 'undefined') {
          this.$store.commit('SET_OPENID', openid);
          // 用户选择不登录
          if (this.isLogin !== '3') {
            this.$store.commit('SET_IS_INIT', false);
            setTimeout(() => {
              this.$store.commit('SET_IS_INIT', true);
            }, 700);
            // 判断用户是否需要登录
            this.checkIsLogin(() => {
              this.$store.commit('SET_IS_INIT', true);
              // window.location.reload();
              this.$store.dispatch('getUserDetail');
              this.$store.commit('SET_MEMBER', uni.getStorageSync('member'));
              // 无感积分逻辑
              this.wxEasyPointsCommitStatusInit();
              // uni.getStorageSync();
            });
          }
        } else {
          // 前往授权页面
          if (this.$route.path.indexOf('openWx') < 0) {
            let openWxPath = 'openWx';
            if (this.$route.fullPath === '/') {
              openWxPath = `/${groupId}/${mallId}/openWx`;
            }
            this.$router.push({
              path: openWxPath,
              query,
            });
          }
        }
      });
    },
    // 无感积分相关
    async wxEasyPointsCommitStatusInit() {
      return
      this.$refs.wxPointsCommit.open();
      // 判断用户是否登陆
      if (uni.getStorageSync('openid') && uni.getStorageSync('member') && uni.getStorageSync('member') !== {}) {
				const easyPointsCommitStatus = await getWxEasyPointsCommitStatus()
				if (easyPointsCommitStatus) {
					this.$refs.wxPointsCommit.open();
				}
			}
    }
  },
};
</script>
<style lang="less">
/* 如果有其他引入，合并即可，该文件最好放第一行 */
// @import '@kip/ui-mobile/theme/theme.css';
@import '~@/kui/theme/theme.css';
</style>

<style>
page {
  display: flex;
  flex-direction: column;
  height: 100%;
}

body {
  padding: 0;
  margin: 0;
}
</style>
