<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>
  </div>
</template>
<script>
import { KIP_API_CODE } from '@/common/js/config';
import Stomp from '@/lib/stompjs';
import loginMinix from '@/mixins/login';
import {
  kipCheckToken,
  kipGetNewAccessTokenByRefreshToken,
} from '@/utils/api-kip';
import CacheTool from '@/utils/cache-tool';
import { Decrypt, Encrypt } from '@/utils/crypto';
import { getIsMin, getIsWxh5, getUrlParams } from '@/utils/index.js';
import KipCacheTool from '@/utils/kip-cache-tool';
import log from '@/utils/log';
import SockJS from '@/utils/sockjs';
import uni from '@/utils/uniHooks';
import { getAppIdByGroupIdAndMallId } from '@/utils/index.js';
import { Toast } from 'vant';
import { pathToRegexp, parse, compile } from 'path-to-regexp';

export default {
  mixins: [loginMinix],
  data() {
    return {
      ws: null,
      stompClient: null,
      isInit: true,
      Toastloading: null,
    };
  },
  created() {
    console.log('重新打包');
    this.initEnv();
    this.init();
    // 初始化环境变量
  },
  computed: {
    cachedViews() {
      return this.$store.state.cachedViews.cachedViews;
    },
    passLogin() {
      return this.$store.state.passLogin;
    },
    key() {
      return this.$route.path;
    },
  },
  watch: {
    cachedViews() {
      console.log(49, '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() {
      // 如果是微信小程序。初始化wss
      if (getIsMin()) {
        // this.Toastloading = Toast.loading({
        //   message: '加载中',
        //   duration: 0,
        //   forbidClick: true,
        // });
        console.log('触发重新发布功能 8?');
        console.log('触发重新发布功能 8?');
        // 每次进入页面清空 缓存数据
        window.localStorage.clear();
        this.isInit = false;
        console.log(window.location.href);
        console.log(56, this.$route);
        console.log('触发重新发布功能 6?');
        window.token = `${window.location.href}`.replace(
          /.*wx\/(.*)\/.*/g,
          '$1'
        );
        try {
          const options = await this.wss();
          // console.log(8383, options);
          this.$store.dispatch('baseInit', {
            options,
            callback: () => {
              // this.Toastloading.clear();
              this.isInit = true;
            },
          });
        } catch (err) {
          console.log(err);
        }
      }
      // 如果是微信公众号
      if (getIsWxh5()) {
        // https://developers.weixin.qq.com/community/develop/doc/000ae2cb950808f90d8bc415551800
        window.H5_LAUNCH_URL = location.href;
        // 判断用户是否登录
        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() {
      CacheTool.init();
      const href = window.location.href;
      console.log('当前页面的url地址  ', href);
      if (/dev-|8080/.test(href)) {
        window.env = 'qa';
        window.profileApi = 'profileApi';
        window.api = 'qaApi';
        return;
      }
      if (/qa-/.test(href)) {
        window.env = 'qa';
        window.api = 'qaApi';
        window.profileApi = 'profileApi';
        return;
      }
      window.env = 'prod';
      window.profileApi = 'profileApiProd';
      window.api = 'api';
    },
    send() {
      const token = window.token;
      window.stompClient.send(
        '/sendToWechat',
        {},
        JSON.stringify({
          token: token,
          data: Encrypt(
            JSON.stringify({
              type: 'openWxPay',
              options: {},
            })
          ),
        })
      );
    },
    // 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.isInit = false;
      let [groupId, mallId] = window.location.pathname
        .split('/')
        .filter((elm) => elm);
      console.log(265, groupId, mallId);
      // return;
      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.isInit = true;
        if (openid && openid !== 'undefined') {
          this.$store.commit('SET_OPENID', openid);
          // 用户选择不登录
          if (this.isLogin !== '3') {
            // 判断用户是否需要登录
            this.checkIsLogin(() => {
              // window.location.reload();
            });
          }
        } 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,
            });
          }
        }
      });
      // 获取openid
      // openid 在本地存在的话，走登录验证
      // openid 不存在的话
      // window.location.pathname
      // this.$router.replace({
      //   path: 'openWx',
      //   query: query,
      // });
      // 初始化微信jsdk
      // 初始化appid，根据 lbsId、groupId、mallId

      /*console.log(109, { groupId, mallId });
      const kipAccessToken = uni.getStorageSync('kipAccessToken');
      // 设置 member、groupId 和 mallId
      this.$store.commit(
        'SET_GROUP_ID',
        groupId || uni.getStorageSync('groupId')
      );
      this.$store.commit('SET_MALL_ID', mallId || uni.getStorageSync('mallId'));
      // 如果用户没有登录的话，我们需要让用户完成授权拿到 openid
      /!* const openid = uni.getStorageSync('openid');
       // console.log(949494, openid);
       // 设置openid
       if (openid && openid !== 'undefined') {
       this.$store.commit('SET_OPENID', openid);
       } *!/
      // 如果用户没有openid
      const openid = uni.getStorageSync('openid');
      // 如果 存在，清空缓存，然后先去openid
      // console.log(949494, openid);
      // 设置openid
      if (openid && openid !== 'undefined') {
        this.$store.commit('SET_OPENID', openid);
      }
      if (!openid) {
        // 当进入其他页面时，需要先打开路由展示
        this.isInit = true;
        // 前往授权页面
        this.$router.replace({
          path: '/openWx',
          query: query,
        });
        return;
      }
      /!* 如果用户选择不登录 *!/
      const passLogin = uni.getStorageSync('passLogin');
      if (passLogin && /true/.test(passLogin)) {
        return;
      }
      if (!openid) {
        // 当进入其他页面时，需要先打开路由展示
        this.isInit = true;
        // 前往授权页面
        this.$router.replace({
          path: 'openWx',
          query: query,
        });
        return;
      }
      if (!kipAccessToken) {
        // 如果用户不选择登录，则不走登录逻辑
        this.isInit = true;
        this.$router.replace({
          path: '/login',
          query: query,
        });
        return;
      }
      // 如果用已经登录
      // 验证 kipAccessToken 是否过期，过期则刷新
      const _this = this;
      kipCheckToken(kipAccessToken)
        .then((resp) => {
          // console.log(120, resp);
          if (resp && resp.statusCode == '401') {
            log.info(
              `access_token已过期，使用refresh_token刷新access_token，如果refresh_token过期则删除所有数据`
            );
            // token过期之后使用refresh_token刷新access_token，如果refresh_token过期则删除所有数据
            const kipRefreshToken = KipCacheTool.getKipRefreshToken();
            kipGetNewAccessTokenByRefreshToken(kipRefreshToken)
              .then((result) => {
                // const result = resp.data;
                if (
                  result &&
                  result.code === '000000' &&
                  result.data.access_token
                ) {
                  KipCacheTool.setKipToken(result.data.access_token);
                  log.info(
                    `refreshToken获取成功，这是新的token:`,
                    result.data.access_token
                  );
                } else {
                  if (
                    result &&
                    result.code !== KIP_API_CODE.REFRESH_TOKEN_EXPIRED
                  ) {
                    uni.showToast({
                      title: result.message,
                      duration: 2000,
                      icon: 'none',
                    });
                  }
                  console.warn('===>清除所有缓存1');
                  log.info(`清除所有缓存1`);
                  _this.cleanAll();
                  this.$router.replace({
                    path: '/login',
                    query: query,
                  });
                }
              })
              .catch((err) => {
                console.warn('===>清除所有缓存2');
                log.info(`清除所有缓存2`);
                _this.cleanAll();
                this.$router.replace({
                  path: '/login',
                  query: query,
                });
              });
          }
        })
        .catch((err) => {
          console.error(err);
          console.warn('===>清除所有缓存3');
          log.info(`refresh_token获取失败，清除所有缓存3`, err);
          _this.cleanAll();
          this.$router.replace({
            path: '/login',
            query: query,
          });
        });
      // 初始化微信
      console.log('初始化');
      // initWxJsSdkConfig(['chooseWXPay', 'scanQRCode', 'checkJsApi'],['wx-open-launch-weapp']);
      // initWxJsSdkConfig(['chooseWXPay']);
      this.$router.push({
        path: '/home',
        query: query,
      });*/
    },
  },
};
</script>
<style>
page {
  display: flex;
  flex-direction: column;
  height: 100%;
}

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