<template>
  <div>
    <!--    <div @click="send">send</div>-->
    <router-view></router-view>
  </div>
</template>
<script>
import { isMini } from '@/utils/common';

// import { crmQueryMemberInfo } from '@/utils/api-crm-member';
// import Ws from '@/utils/websocket';
import SockJS from '@/utils/sockjs';
import Stomp from '@/lib/stompjs/index';
// import uni from '@/utils/uniHooks';
import { Encrypt, Decrypt } from '@/utils/crypto';
import CacheTool from '@/utils/cache-tool';
import uni from '@/utils/uniHooks';
import { mapState } from 'vuex';
import { initWxJsSdkConfig } from '@/utils/login.js';
import { getUrlParams, getPlatform } from '@/utils/index.js';
import KipCacheTool from '@/utils/kip-cache-tool.js';
import {
  kipCheckToken,
  kipGetNewAccessTokenByRefreshToken,
} from '@/utils/api-kip.js';
import { KIP_API_CODE } from '@/common/js/config';
// import qs from 'qs';
export default {
  data() {
    return {
      ws: null,
      msg: '',
      isInit: false,
      stompClient: null,
      host: 'https://dev-crm-kpl.kerryprops.com.cn/xcrm-api',
      token: '1234',
    };
  },
  created() {
    this.init();
  },
  mounted() {
    // if(!this.isInit) {
    //   this.init();
    // }
  },
  computed: {
    disabledBtn() {
      return this.numArr.findIndex((val) => !val) !== -1;
    },
    ...mapState({
      groupId: (state) => state.groupId,
      openid: (state) => state.openid,
      mallId: (state) => state.mallId,
      kipUserId: (state) => state.kipUserId,
      userInfo: (state) => state.userInfo,
    }),
  },
  methods: {
    toLogin() {
      let query = getUrlParams();
      // 本地
      // store
      // url 参数
      // const query = {
      //   groupId: mallid,
      // };
      this.$router.replace({
        path: '/login',
        query: query,
      });
    },
    async init() {
      // 初始化环境变量
      CacheTool.init();
      if (this.isInit) return;
      this.isInit = false;
      const kipAccessToken = uni.getStorageSync('kipAccessToken');
      const query = getUrlParams();
      // console.log('h5登录时的参数', query);
      const platform = getPlatform();
      if (
        (query.groupId && query.groupId !== 'undefined') ||
        uni.getStorageSync('mallId')
      ) {
        this.$store.commit(
          'SET_GROUP_ID',
          query?.groupId || uni.getStorageSync('groupId')
        );
      }
      if (
        (query.mallId && query.mallId !== 'undefined') ||
        uni.getStorageSync('mallId')
      ) {
        this.$store.commit(
          'SET_MALL_ID',
          query?.mallId?.replace('#/', '') || uni.getStorageSync('mallId')
        );
      }
      if (uni.getStorageSync('member')) {
        this.$store.dispatch('getUserDetail');
        this.$store.commit('SET_USER_INFO', uni.getStorageSync('member'));
        this.$store.commit('SET_MEMBER', uni.getStorageSync('member'));
      }

      // 如果是微信小程序入口，先把 传过来的 token 和 pageId 保存下来
      if (platform === 'miniprogram' && !uni.getStorageSync('pageId')) {
        const { pageId, token } = query;
        uni.setStorageSync('pageId', pageId);
        uni.setStorageSync('token', token);
      }

      // 如果用户没有openid
      const openid = uni.getStorageSync('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;
      }
      // 当前页面是否是在微信公众号运行：start
      // 微信公众号环境 start
      if (platform === 'micromessenger') {
        // 如果用户没有登录的话，我们需要让用户完成授权拿到 openid
        /* const openid = uni.getStorageSync('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;
        }
        if (!kipAccessToken) {
          /* if (!openid) {
            // 当进入其他页面时，需要先打开路由展示
            this.isInit = true;
            // 前往授权页面
            this.$router.replace({
              path: '/openWx',
              query: query,
            });
            return;
          } */
          // 初始化微信
          initWxJsSdkConfig(['chooseWXPay', 'scanQRCode', 'checkJsApi']);
          // 如果用户不选择登录，则不走登录逻辑
          this.isInit = true;
          this.$router.replace({
            path: '/login',
            query: query,
          });
          return;
        }
        // 如果用已经登录
        // 验证 kipAccessToken 是否过期，过期则刷新
        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: '/home',
          query: query,
        });
        this.isInit = true;
        return;
      }
      // 当前页面是否是在微信公众号运行：end

      // 当判断缓存中存在 pageId, token,并且地址栏中不存在 pageId, token。我们需要刷新页面，确保用户在微信小程序和H5公众号中使用的 open ID 保存一致
      if (
        uni.getStorageSync('pageId') &&
        uni.getStorageSync('pageId') !== 'undefined' &&
        uni.getStorageSync('token') &&
        (!query?.pageId || !query.token)
      ) {
        this.$router.replace({
          path: '/home',
          query: {
            pageId: uni.getStorageSync('pageId'),
            token: uni.getStorageSync('token'),
          },
        });
        return;
      }
      /* 微信小程序 webview 配置 */
      console.log(258, uni.getStorageSync('pageId'));
      if (
        !uni.getStorageSync('pageId') ||
        uni.getStorageSync('pageId') === 'undefined'
      ) {
        return;
      }
      window.token = query?.token || uni.getStorageSync('token');
      // this.getTicket()
      this.wss(() => {
        this.$store.dispatch('baseInit', {
          // pageId: window.location.href.replace(/.*pageId=([0-9A-Z]*).*/g, '$1'),
          pageId: query?.pageId || uni.getStorageSync('pageId'),
          // callback: this.wss,
          callback: () => {
            // console.log(838383, this.isInit);
            this.isInit = true;
            // if (!openid) {
            //   this.$router.replace({
            //     path: '/openWx',
            //     query: query,
            //   });
            //   return
            // }
            // 当所有的数据都初始化之后再次执行
            this.getTicket();
          },
        });
      });
    },
    send() {
      window.stompClient.send(
        '/sendToWechat',
        {},
        JSON.stringify({
          token: window.token,
          data: Encrypt(
            JSON.stringify({
              type: 'openWxPay',
              options: {},
            })
          ),
        })
      );
    },
    wss(callback) {
      try {
        console.log(
          107107,
          this.host + '/hafengWebsocket' + '?token=' + window.token
        );
        const socket = new SockJS(
          this.host + '/hafengWebsocket' + '?token=' + window.token
        );
        window.stompClient = Stomp.over(socket);
        window.stompClient.debug = null;
        const self = this;
        this.windowSendInit();
        window.stompClient.connect({}, (frame) => {
          callback && callback();
          window.subscribe('projectId', (options) => {
            self.$store.commit('SET_PROJECT_ID', options.projectId);
            self.$store.commit('SET_ACCESS_TOKEN', options.accessToken);
          });
        });
      } catch (err) {
        console.log(err);
        callback && callback();
      }
    },
    disconnect() {
      if (window.stompClient != null) {
        window.stompClient.disconnect();
      }
    },
    windowSendInit() {
      // uni.showToast({title: '哈哈哈哈'})
      // return
      window.toWXSendMsg = function ({
        type = '',
        funcName = '',
        options = {},
      }) {
        /**
         * 向小程序端发送消息
         */
        if (!type) return;
        console.log(259, '微信支付的options', options);
        window.stompClient.send(
          '/sendToWechat',
          {},
          JSON.stringify({
            token: window.token,
            data: Encrypt(
              JSON.stringify({
                type: type,
                funcName,
                options,
              })
            ),
          })
        );
      };
      // 主动订阅事件回调
      window.subscribe = function (type, callback) {
        const subscribeId = window.stompClient.subscribe(
          '/user/' + window.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 === self.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);
            }
          }
        );
      };
    },
    // 环境变量初始化
    envInit() {
      const href = `${window.location.href}`;
      // dev
      if (/8080|dev-/g.test(href)) {
        CacheTool.setEnv('qa');
        return;
      }
      // qa
      if (/qa-/g.test(href)) {
        CacheTool.setEnv('dev');
        return;
      }
      // prod
      CacheTool.setEnv('prod');
    },
    // h5获取配置---公众号支付
    getTicket() {
      console.log(173);
      let self = this;
      var datas = {
        groupId: this.groupId,
        mallid: this.mallId,
        url: window.location.href.split('#')[0],
      };
      self.$md(datas);
      console.log(199, datas);
      uni.request({
        // url: self.$baseURL + "api/1.0/login/getTicket",
        // url: 'https://qa-crm-kpl.kerryprops.com.cn/xcrm-api/' + "api/1.0/login/getTicket",
        method: 'POST',
        data: datas,
        header: JSON.parse(uni.getStorageSync('handleUser')),
        success: (res) => {
          console.log(206, res);
          if (res.data.code == 0) {
            self.$wx.config({
              debug: false, // 开启调试模式
              appId: res.data.data.appId, // 必填，公众号的唯一标识
              timestamp: res.data.data.timestamp, // 必填，生成签名的时间戳
              nonceStr: res.data.data.nonceStr, // 必填，生成签名的随机串
              signature: res.data.data.signature, // 必填，签名
              jsApiList: ['chooseWXPay', 'scanQRCode', 'checkJsApi'], // 必填，需要使用的JS接口列表
            });
            self.$wx.ready(function () {
              self.$wx.checkJsApi({
                jsApiList: ['chooseWXPay'],
                success: (res) => {
                  console.log('checked api:', res);
                },
                fail: (err) => {
                  console.log('check api fail:', err);
                },
              });
            });
            self.$wx.error(function (res) {
              console.log('err', res);
            });
          } else {
            uni.showToast({
              title: res.data.msg,
              duration: 2000,
              icon: 'none',
            });
          }
        },
      });
    },
    h5init() {
      if (uni.getStorageSync('groupId')) {
        this.$store.commit('SET_GROUP_ID', uni.getStorageSync('groupId'));
      }
      if (uni.getStorageSync('kipUserId')) {
        this.$store.commit('SET_KIP_USER_ID', uni.getStorageSync('kipUserId'));
      }
      if (uni.getStorageSync('mallId')) {
        this.$store.commit('SET_MALL_ID', uni.getStorageSync('mallId'));
      }
      if (uni.getStorageSync('openid')) {
        this.$store.commit('SET_OPENID', uni.getStorageSync('openid'));
      }
      if (uni.getStorageSync('mobile')) {
        this.$store.commit('SET_OPENID', uni.getStorageSync('mobile'));
      }
    },
  },
};
</script>
<style>
page {
  display: flex;
  flex-direction: column;
  height: 100%;
}

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