<template>
  <van-config-provider>
    <div id="nav" class="min-h-screen" style="background: #f7f7fa">
      <router-view />
    </div>
    <!-- Target -->
    <input
      id="clipboardInput"
      :value="clipboardValue"
      style="opacity: 0; position: absolute; top: 0; left: 0"
    />
    <!-- Trigger -->
    <button
      class="clipboardBtn"
      ref="btn"
      data-clipboard-target="#clipboardInput"
      style="opacity: 0; position: absolute; top: 0; left: 0"
    ></button>
  </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 {
  defineComponent,
  nextTick,
  onBeforeMount,
  onBeforeUnmount,
  onMounted,
  watch,
} from "vue";
import decodeChatMessage from "./utils/fzm-message-protocol-chat/decodeChatMessage";
import ChatDBService from "@/db/ChatDBService";
import {
  checkPendingMsgAndSendIt,
  getMasterIdFromDisplayMsg,
  getTargetIdFromDisplayMsg,
} from "./utils/chatutils";
import isChattingWith from "./utils/isChattingWith";
import { ChatMessageTypes } from "@/types/chatMessageTypes";
import { chatCardTimeStamp } from "./store/chatCardStore";
import { getUserMsg, setUserMsg } 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 { clipboardValue, notchHeight } from "./store/AppStore";
import ClipboardJS from "clipboard";
import { judgeClient } from "./utils/env";
import { getLatestVersion } from "./service/VersionService";
import UserService from "./service/UserService";

export default defineComponent({
  setup() {
    const btn = ref<HTMLButtonElement | null>(null);

    const getNewestApp = async () => {
      const client = judgeClient();

      function formatUpdateType(t: number) {
        if (t === 1) {
          return 1;
        } else if (t == 2) {
          return 0;
        }
      }

      if (client === "iOS") {
        const ret = await getLatestVersion({ os: "ios" });
        if (ret.code === 200) {
          new Bridge().bridge_getNewestApp({
            status: formatUpdateType(ret.data.update_type), // 0代表强制更新  1代表普通更新
            modifyContent: ret.data.content, // 代表本次更新的修改内容
            versionCode: ret.data.version_num, // 版本号
            versionName: ret.data.version_name, //版本名称
            downloadUrl_ios: ret.data.url, // 下载链接
          });
        }
      } else if (client === "Android") {
        const ret = await getLatestVersion({ os: "android" });
        if (ret.code === 200) {
          new Bridge().bridge_getNewestApp({
            status: formatUpdateType(ret.data.update_type), // 0代表强制更新  1代表普通更新
            modifyContent: ret.data.content, // 代表本次更新的修改内容
            versionCode: ret.data.version_num, // 版本号
            versionName: ret.data.version_name, //版本名称
            downloadUrl: ret.data.url,
          });
        }
      }
    };

    onMounted(() => {
      getNewestApp();
      const clipboard = new ClipboardJS(".clipboardBtn");
      clipboard.on("success", function () {
        Toast.success("复制成功");
      });

      clipboard.on("error", function () {
        Toast.fail("复制失败");
      });
    });

    watch(clipboardValue, (newValue) => {
      if (newValue !== "") {
        nextTick(() => {
          btn.value?.click();
          clipboardValue.value = "";
        });
      }
    });

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

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

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

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

      let prefix = "ws://";
      if (window.location.protocol === "https:") {
        prefix = "wss://";
      }
      const fmp = new FzmMessageProtocol(
        `${prefix}${window.location.host}/proxyWs/sub`
      );

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

      const chatTokenRet = await UserService.getInstance().getChatToken();
      if (chatTokenRet.code !== 200) {
        return;
      }

      UserMsg.userInfo.addr = chatTokenRet.data.addr;

      setUserMsg(UserMsg);

      fmp
        .authorize({
          appId: "dtalk",
          token: chatTokenRet.data.token,
        })
        .then((conn) => {
          connectionState.connection = conn;
          checkPendingMsgAndSendIt();
        })
        .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) => {
        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 {
      btn,
      clipboardValue,
    };
  },
});
</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;
}
.vhtml {
  font-family: PingFangSC-Regular, PingFang SC;
  em {
    font-style: italic;
  }
  strong {
    font-weight: 900 !important;
  }

  h1 {
    font-size: 1.4rem !important;
    font-weight: 300 !important;
    line-height: 1.5rem !important;
    letter-spacing: -0.01562em !important;
  }
  h2 {
    font-size: 1.2rem !important;
    font-weight: 300 !important;
    line-height: 1.5rem !important;
    letter-spacing: -0.01562em !important;
  }
  h3 {
    font-size: 1rem !important;
    font-weight: 300 !important;
    line-height: 1.5rem !important;
    letter-spacing: -0.01562em !important;
  }

  word-wrap: break-word;
  white-space: pre-wrap;

  > * {
    box-sizing: border-box;
  }

  p {
    margin-bottom: 0;
    margin-top: 0;
    outline: none;
    line-height: 40px;
    min-height: 40px;
  }

  h1,
  h2,
  h3,
  h4,
  h5 {
    margin-top: 20px;
    margin-bottom: 20px;

    &:first-child {
      margin-top: 0;
    }

    &:last-child {
      margin-bottom: 0;
    }
  }

  ul,
  ol {
    counter-reset: none;
    list-style-type: none;
    margin-bottom: 0;
    margin-left: 5px;
    margin-top: 0;
    padding-bottom: 5px;
    padding-left: 0;
    padding-top: 5px;
  }

  ol li > p {
    margin: 0;

    &:first-child::before {
      content: counter(el-tiptap-counter) "." !important;
      display: inline-block;
      left: -5px;
      line-height: 1;
      margin-left: -24px;
      position: relative;
      text-align: right;
      top: 0;
      width: 24px;
    }
  }

  ul li > p {
    &:first-child::before {
      content: "\2022";
      text-align: center;
      display: inline-block;
      left: -5px;
      line-height: 1;
      margin-left: -24px;
      position: relative;
      text-align: right;
      top: 0;
      width: 24px;
    }
  }

  ol {
    counter-reset: el-tiptap-counter;

    li > p:first-child::before {
      counter-increment: el-tiptap-counter;
    }
  }

  a {
    color: #409eff;
    cursor: pointer;
  }

  blockquote {
    border-left: 5px solid #edf2fc;
    border-radius: 2px;
    color: #606266;
    margin: 10px 0;
    padding-left: 1em;
  }

  code {
    background-color: #d9ecff;
    border-radius: 4px;
    color: #409eff;
    display: inline-block;
    font-size: 14px;
    font-weight: 700;
    padding: 0 8px;
  }
  @primary-text-color: #303133;
  pre {
    background-color: @primary-text-color;
    color: #d9ecff;
    font-size: 16px;
    overflow-x: auto;
    padding: 14px 20px;
    margin: 10px 0;
    border-radius: 5px;

    code {
      background-color: transparent;
      border-radius: 0;
      color: inherit;
      display: block;
      font-family: "Menlo,Monaco,Consolas,Courier,monospace";
      font-size: inherit;
      font-weight: normal;
      padding: 0;
    }
  }

  ul[data-type="todo_list"] {
    margin-left: 5px;

    .todo-item {
      display: flex;
      flex-direction: row;
      justify-content: flex-start;
      margin-bottom: 0;

      &[data-text-align="right"] {
        justify-content: flex-end !important;
      }

      &[data-text-align="center"] {
        justify-content: center !important;
      }

      &[data-text-align="justify"] {
        text-align: space-between !important;
      }

      .todo-content {
        padding-left: 10px;

        > p {
          font-size: 16px;

          &:last-of-type {
            margin-bottom: 0;
          }
        }
      }

      &--done {
        > .todo-checkbox {
          color: #409eff;
        }

        > .todo-content > p {
          color: #409eff;
          text-decoration: line-through;
        }
      }
    }
  }

  hr {
    margin-top: 20px;
    margin-bottom: 20px;
  }

  // @for $i from 1 through 7 /* max-indent */ {
  //   $indent-margin-base: 30px;

  //   *[data-indent="#{$i}"] {
  //     margin-left: $indent-margin-base * $i !important;
  //   }
  // }

  th {
    font-weight: 500;
    text-align: left;
  }

  .column-resize-handle {
    background-color: #b3d8ff;
    bottom: 0;
    pointer-events: none;
    position: absolute;
    right: -2px;
    top: 0;
    width: 4px;
    z-index: 20;
  }

  .resize-cursor {
    cursor: ew-resize;
    cursor: col-resize;
  }

  h1 {
    font-size: 1.4rem !important;
    font-weight: 300 !important;
    line-height: 1.5rem !important;
    letter-spacing: -0.01562em !important;
  }
  h2 {
    font-size: 1.2rem !important;
    font-weight: 300 !important;
    line-height: 1.5rem !important;
    letter-spacing: -0.01562em !important;
  }
  h3 {
    font-size: 1rem !important;
    font-weight: 300 !important;
    line-height: 1.5rem !important;
    letter-spacing: -0.01562em !important;
  }

  > * + * {
    margin-top: 0.75em;
  }

  ul,
  ol {
    padding: 0 1rem;
  }

  li {
    line-height: 2em !important;
  }

  h1,
  h2,
  h3,
  h4,
  h5,
  h6 {
    line-height: 1.1;
  }

  code {
    background-color: rgba(#616161, 0.1);
    color: #616161;
  }

  pre {
    background: #0d0d0d;
    color: #fff;
    font-family: "JetBrainsMono", monospace;
    padding: 0.75rem 1rem;
    border-radius: 0.5rem;

    code {
      color: inherit;
      padding: 0;
      background: none;
      font-size: 0.8rem;
    }
  }

  mark {
    background-color: #faf594;
  }

  img {
    max-width: 100%;
    height: auto;
  }

  hr {
    margin: 1rem 0;
  }

  blockquote {
    padding-left: 1rem;
    border-left: 2px solid rgba(#0d0d0d, 0.1);
  }

  hr {
    border: none;
    border-top: 2px solid rgba(#0d0d0d, 0.1);
    margin: 2rem 0;
  }

  ul[data-type="taskList"] {
    list-style: none;
    padding: 0;

    li {
      display: flex;
      align-items: center;

      > label {
        flex: 0 0 auto;
        margin-right: 0.5rem;
        user-select: none;
      }

      > div {
        flex: 1 1 auto;
      }
    }
  }
}
</style>
