


import https from '@/https';
import server from './actions/server.js';
import Pomelo from './pomelo/Pomelo.js';
import ToolsBase from './tools/ToolsBase.js';
import storage, { actions } from '../utils/storage';
import { useUserStoreWithOut } from '@/stores/modules/user';
import { useGameStoreWithOut } from '@/stores/modules/game';
import Notify from './notify.js';
import { closeLoading, toast } from "@/utils/toast";
// import router from '@/router';
// import emitter from "@/utils/eventBus";

const pomeloCenter = Pomelo();
const pomeloMsg = Pomelo();

export default class extends ToolsBase {

  constructor() {
    super()
    this.userInfo = {};
    this.token = '';
    this.msg = {};
    /**
     * 发送请求
     * @param {String} url 路由
     * @param {any} params 参数
     */
    this.request = (url, params = {}) => {
      return new Promise((reslove, reject) => {
        pomeloCenter.request(url, params, (res) => {
          reslove(res)
        })
      })
    }
    /**
    * 注册事件
    * @param {String} event 事件名称
    */
    this.on = (url) => {
      return new Promise((reslove, reject) => {
        pomeloMsg.on(url, res => {
          reslove(res)
        })
      })
    }
    /**
     * 通知请求
     * @param {String} url 路由
     * @param {any} params 参数
     */
    this.notify = (url, params = {}) => {
      return new Promise((reslove, reject) => {
        pomeloCenter.notify(url, params, (res) => {
          reslove(res)
        })
      })
    }

    /**
     * 下线通知
     */
    // pomeloCenter.on(this.cfg.global.EVENT_NAME.ON_KICK, res => {
    //   console.log(res, '-----下线通知-----1');
    //   storage.clearStorage();
    //   storage.removeSessionStorage(actions.HOME_POSITION);
    //   useUserStoreWithOut().clearUser();
    //   useGameStoreWithOut().clearGameUrl();
    //   emitter.emit("closeGame");
    //   router.replace("/login");
    //   // this.connectMsg()
    // })
  }

  /**
   * 连接前
   * @returns 
   */
  beforeConnect() {
    this.userInfo = JSON.parse(storage.getStorage(actions.USER_INFO)) || {}
    this.token = storage.getStorage(actions.USER_TOEKN) || ''
    this.msg = {
      // 建立连接后调用entry方法前验证，并且成功后session绑定uid
      uid: this.userInfo.uid,
      token: this.token,
      lang: 'pt'
    }
    // this.connectMsg().then(() => {
    //   new Notify(pomeloMsg)
    // })
    // return new Promise((reslove, reject) => {
    //   try {
    //     this.connectCenter().then((status) => {
    //       if (!status) {
    //         reslove(false)
    //       }
    //       reslove(true)
    //     })
    //   } catch (error) {
    //     console.log(error, '??????socket 连接失败')
    //   }

    // })
  }


  /**
   * 已登录准备链接
   */
  connect() {
    return new Promise((reslove, reject) => {
      Promise.all([this.connectMsg()]).then((res) => {
        if (res[0] && res[1]) {
          reslove(true)
        }
        reslove(false)
      })
    })
  }

  /**
   * 连接中心服务器Url
   */
  connectCenter() {
    this.beforeConnect()
    return new Promise((reslove, reject) => {
      https.getCenterUrl().then(res => {
        if (res.code !== this.cfg.code.OK) {
          // router.replace("/login");
          reslove(false)
          return
        }

        const params = this.setParams(res.data.url)
        pomeloCenter.createConnect(server.centerRoute, params, this.msg, (ress) => {
          // console.log('-----center连接成功-----', ress)
          // 如果上次的连接只是踢下线，不再重新建立连接，直接登录
          if (ress.code === this.cfg.code.C1044.CODE) {
            this.request(server.centerRoute, this.msg).then(() => {
              reslove(true)
            });
            return;
          };

          // if (ress.code == this.cfg.code.C15.CODE || ress.code == this.cfg.code.C14.CODE) {
          //   closeLoading()
          //   toast(ress.txt)
          //   storage.clearStorage()
          //   useUserStoreWithOut().clearUser()
          //   this.disconnect()
          //   reslove(false)
          //   return
          // }

          if (ress.code !== this.cfg.code.OK) {
            closeLoading()
            toast(ress.txt)
            storage.clearStorage()
            storage.removeSessionStorage(actions.HOME_POSITION);
            useUserStoreWithOut().clearUser()
            useGameStoreWithOut().clearGameUrl();
            this.disconnect()
            reslove(false)
            return
          };
          reslove(true)
        })
      })
    })
  }

  /**
   * 连接消息服务器url
   */
  connectMsg() {
    this.beforeConnect()
    return new Promise((reslove, reject) => {
      console.log(https);
      https.getMsgServer().then((res) => {
        if (res.code !== this.cfg.code.OK) {
          // router.replace("/login");
          reslove(false)
          return
        }
        const params = this.setParams(res.data.url, 'Msg', 20)
        pomeloMsg.createConnect(server.messageRoute, params, this.msg, ress => {
          if (ress.code !== this.cfg.code.OK) {
            // 有可能Center服务器断线了，3秒后重试
            setTimeout(() => {
              this.connectMsg();
            }, 3000);
            return;
          };
          // !JSON.parse(import.meta.env.VITE_OPEN_CONSOLE) ? toast('message connect') : null
          new Notify(pomeloMsg)
          reslove(true)
        })
      })
    })

  }

  disconnect() {
    pomeloCenter.disconnect('discount center');
    pomeloMsg.disconnect('discount msg');
  }

  disconnectMsg() {
    pomeloMsg.disconnect('discount msg');
  }

  /**
   * 设置连接参数
   * @param {String} url 获取服务器url
   * @param {String} serverName 名称 Center Msg
   * @param {Number} maxReconnectAttempts 最大重连次数
   */
  setParams(url, serverName = 'Center', maxReconnectAttempts = 5) {
    return {
      url,
      reconnect: true,
      maxReconnectAttempts,
      serverName: serverName,
      serverTime: this.serverTime,
      // 建立连接之前验证
      uid: this.userInfo.uid ? this.userInfo.uid : undefined,
      token: this.token ? this.token : undefined,
      // 消息加解密方法
      enData: this.enData.bind(this),
      deData: this.deData.bind(this),
      cert: JSON.parse(import.meta.env.VITE_SOCKET_CERT)
    }
  }
}

