<template>
  <van-config-provider>
    <div id="nav" class="min-h-screen" style="background:#F7F7FA">
      <router-view />
    </div>
  </van-config-provider>
</template>

<script lang="ts">
import { ref } from "@vue/reactivity";
import { connectionState } from "./store/connectionStore";
import FzmMessageProtocol from "@/utils/fzm-message-protocol";
import { generateToken } from "./utils/generateToken/generate-token";
import { defineComponent, onBeforeMount, onBeforeUnmount, onMounted, watch } from "vue";
import decodeChatMessage from "./utils/fzm-message-protocol-chat/decodeChatMessage";
import ChatDBService from "@/db/ChatDBService"
import { getMasterIdFromDisplayMsg, getTargetIdFromDisplayMsg } from "./utils/chatutils";
import isChattingWith from "./utils/isChattingWith";
import { ChatMessageTypes } from "@/types/chatMessageTypes"
import { chatCardTimeStamp } from "./store/chatCardStore";
import { getUserMsg } from "./utils/userMsg";
import { chatLoginActionMark, eLoginType } from "./store/chatStore";
import { Toast } from "vant";
import router from "./router";
import { useRoute } from "vue-router";
import Bridge from '@/utils/jsBridge2'
import { chatAuthCheck } from "./utils/authCheck";
import { notchHeight } from "./store/AppStore";


export default defineComponent({
  setup() {

    onBeforeMount(() => {
      setTimeout(() => {
        new Bridge().getNotchHeight(null, (height: any) => {
          console.log('getNotchHeight', height);
        })
      }, 3000);

      new Bridge().getNotchHeight(null, (height: any) => {
        height = Number(height)
        notchHeight.value = height;
      })
    })

    const route = useRoute();
    const initError = ref(false);

    const connect = () => {
      connectionState.error = false;
      initError.value = false;

      const fmp = new FzmMessageProtocol(`ws://${window.location.host}/proxyWs/sub`);

      const UserMsg = getUserMsg();
      if (!UserMsg) {
        Toast('未登录')
        router.push({
          name: 'Login'
        })
        return;
      }


      fmp
        .authorize({
          appId: "dtalk",
          token: generateToken({
            address: UserMsg.userInfo.addr,
            privateKeyHex: UserMsg.userInfo.pri_key,
            publicKeyHex: UserMsg.userInfo.pub_key,
          }),
        })
        .then((conn) => {
          connectionState.connection = conn;
        })
        .catch((reason) => {
          initError.value = true;
          console.error(reason);
        });
    };

    watch(chatLoginActionMark, (newMark) => {
      if (newMark === eLoginType.login) {
        chatAuthCheck(connect)
      } else if (newMark === eLoginType.logout) {
        connectionState.connection?.disconnect();
      }
    })

    const checkRoute = (n: string) => {
      switch (n) {
        case '/home':
          return true
        case '/chatList':
          return true
        case '/loan':
          return true
        case '/mine':
          return true
        default:
          return false
      }
    }

    watch(() => route.path, (n) => {
      console.log(n)
      const result = checkRoute(n)
      console.log(result, ' result')
      new Bridge().bridge_quitApp(result)
    }
    )

    onMounted(() => {
      if (getUserMsg()) {
        chatAuthCheck(connect)
      }
    })

    watch(() => connectionState.error, () => {
      if (connectionState.error) {
        chatAuthCheck(connect);
      }
    })

    watch(() => connectionState.connection, () => {

      if (!connectionState.connection) return;
      // 连接后，指定每次收到消息要做的事
      connectionState.connection.onReceiveMessage = (msgData) => {
        const msg = decodeChatMessage(msgData);

        const displayMsg = msg && {
          target: msg.target, content: msg.content, from: msg.from,
          uuid: msg.uuid, state: null, type: ((msg.type as unknown) as ChatMessageTypes),
          datetime: msg.datetime
        };

        console.log(displayMsg, 'in receive');

        msg && displayMsg && (ChatDBService.getInstance().handleEveryReceive({
          msg: displayMsg,
          masterId: getMasterIdFromDisplayMsg(displayMsg),
          isChattingWithTargetId: isChattingWith(getMasterIdFromDisplayMsg(displayMsg), getTargetIdFromDisplayMsg(displayMsg), route.query.targetId as string)
        })).then(() => {
          console.log(displayMsg);
          chatCardTimeStamp.value = new Date().getTime() + (Math.ceil(Math.random() * 1000))
        });
      };

      // 连接后，指定每次断开连接要做的事
      connectionState.connection.onLoseConnection = () => {
        connectionState.connection = undefined;
        connectionState.error = true;
      };
    })

    onBeforeUnmount(() => {
      connectionState.connection?.disconnect();
    });
    return {
    }
  }
})

</script>


<style lang="less">
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.5s;
}
.fade-enter, .fade-leave-to /* .fade-leave-active below version 2.1.8 */ {
  opacity: 0;
}
/* 可以设置不同的进入和离开动画 */
/* 设置持续时间和动画函数 */
.slide-fade-enter-active {
  transition: all 0.3s ease;
}
.slide-fade-leave-active {
  transition: all 0.8s cubic-bezier(1, 0.5, 0.8, 1);
}
.slide-fade-enter, .slide-fade-leave-to
  /* .slide-fade-leave-active for below version 2.1.8 */ {
  transform: translateX(10px);
  opacity: 0;
}

.flex-col {
  display: flex;
  flex-direction: column;
}
.flex-row {
  display: flex;
  flex-direction: row;
}
</style>
