<template>
  <div class="flex flex-col flex-nowrap bg-gray-50 h-screen">
    <NavBar :title="title" />
    <div
      v-if="!connectionState.connection"
      class="flex flex-row justify-center items-center bg-gray-50 h-full w-full"
    >
      <q-spinner color="primary" size="3rem" :thickness="5" />
    </div>
    <div
      class="flex flex-col flex-grow overflow-hidden"
      style="flex-basis: 0px"
    >
      <ChatContentVue :isRobootOffLine="isRobootOffLine" />
      <ServiceRating
        :setSelectedRate="handleSelect"
        :selected="selected"
        v-if="showServiceRating"
      />
      <ChatOption>
        <ChatOptionItemVue
          v-if="isUser && isChatWithRoboot && !isRobootOffLine"
          :selected="questionSelected"
          @click="handleClickQuestionOption"
          value="常用问题"
        />
        <ChatOptionItemVue
          v-if="isUser && isChatWithRoboot"
          :selected="serviceSelected"
          :value="serviceShowValue"
          @click="handleClickService"
        />
        <ChatOptionItemVue
          :selected="false"
          value="电话联系"
          @click="handleClickCall"
        />
      </ChatOption>
      <ChatInputVue :serviceShowValue="serviceShowValue" />
      <CommonUseSentence
        class="transition-all h-0"
        :class="{ 'h-40': showShortSentences }"
        :loading="sentensesLoading"
        @useSentence="useSentence"
        :list="sentenceList"
      />
    </div>
    <ShowCall
      v-model:show="showCall"
      :phone="callPhone"
      @hidden="showCall = false"
    />
  </div>
</template>

<script lang="ts">
/* eslint-disable */
import NavBar from "@/components/NavBar/index.vue";
import {
  defineComponent,
  onMounted,
  ref,
  watch,
  defineAsyncComponent,
  computed,
} from "vue";
import { connectionState } from "@/store/connectionStore";
import { getFromId } from "@/store/appCallerStore";
import { messageStore } from "@/store/messagesStore";
import ChatMessageDB from "@/db/ChatMessageDB";
import { chatCardTimeStamp } from "@/store/chatCardStore";
import ChatListCardDB from "@/db/ChatListCardDB";
import { v4 as uuidv4 } from "uuid";
import { ChatMessageTypes } from "@/types/chatMessageTypes";
import { useRoute } from "vue-router";
import { queryFaqAnswer, queryFaqList } from "@/service/FaqService";
import { getDisplayNames, getMsgFromAddress } from "@/utils/displayName";
import { MessageContent } from "@/types/chat-message";
import { CONST_END_CHAT, CONST_START_CHAT } from "@/config/chat";
import ChatOptionItemVue from "@/components/ChatOptions/ChatOptionItem.vue";
import ShowCall from "@/components/showCall/index.vue";
import { getUserMsg } from "@/utils/userMsg";
import { eRole } from "@/types/roleType";
import ChatDBService from "@/db/ChatDBService";
import UserService from "@/service/UserService";
import { gotoChatWithStaff } from "@/router/navigate";

export default defineComponent({
  components: {
    ChatContentVue: defineAsyncComponent(
      () => import(/* webpackChunkName: 'ChatContentVue' */ "./ChatContent.vue")
    ),
    ChatInputVue: defineAsyncComponent(
      () => import(/* webpackChunkName: 'ChatInputVue' */ "./ChatInput.vue")
    ),
    NavBar,
    ServiceRating: defineAsyncComponent(
      () =>
        import(
          /* webpackChunkName: 'serviceRating' */ "@/components/ServiceRating/index.vue"
        )
    ),
    ChatOption: defineAsyncComponent(
      () =>
        import(
          /* webpackChunkName: 'ChatOption' */ "@/components/ChatOptions/index.vue"
        )
    ),
    CommonUseSentence: defineAsyncComponent(
      () =>
        import(
          /* webpackChunkName: 'CommonUseSentence' */ "@/components/CommonUseSentence/index.vue"
        )
    ),
    ChatOptionItemVue,
    ShowCall,
  },

  setup() {
    const questionSelected = ref(false);
    const handleClickQuestionOption = () => {
      questionSelected.value = !questionSelected.value;
    };

    watch(questionSelected, () => {
      setShowSentences(questionSelected.value);
      sentensesLoading.value = true;
      questionSelected.value &&
        queryFaqList().then((ret) => {
          if (ret.code === 200) {
            sentenceList.value = ret.data.question;
          }
          sentensesLoading.value = false;
        });
    });

    const serviceSelected = ref(false);
    const serviceShowValue = ref("人工服务");

    const sendChatMessage = (payload: {
      type: ChatMessageTypes;
      content: MessageContent;
      target?: string;
    }) => {
      return messageStore.sendMessage({
        type: payload.type,
        content: payload.content,
        target: payload.target || (route.query.targetId as string),
      });
    };

    const handleClickService = async () => {
      if (serviceShowValue.value === "人工服务") {
        questionSelected.value = false;
        const ret = await UserService.getInstance().contact_custom_service({
          outLetID: route.query.targetId as string,
        });
        if (ret.code === 200) {
          gotoChatWithStaff({
            address: ret.data.addr,
            beginChat: true,
          });
        } else {
          // await sendChatMessage({
          //   type: ChatMessageTypes.Card,
          //   content: {
          //     bank: CONST_WARNING.user.id,
          //     name: CONST_WARNING.staff.id,
          //     account: '',
          //   } as MessageContent,
          //   target: route.query.targetId as string
          // })
          return;
        }
      } else if (serviceShowValue.value === "结束服务") {
        serviceShowValue.value = "人工服务";
        sendChatMessage({
          type: ChatMessageTypes.Card,
          content: {
            bank: CONST_END_CHAT.user.id,
            name: CONST_END_CHAT.staff.id,
            account: "",
          } as MessageContent,
        });
      }
    };

    const initError = ref(false);
    const showServiceRating = ref(false);
    const selected = ref("");
    const showShortSentences = ref(false);

    const route = useRoute();
    const target = route.query.targetId as string;

    const sentenceList = ref<any[]>([]);
    const sentensesLoading = ref(false);

    const setShowSentences = (show: boolean) =>
      (showShortSentences.value = show);
    const handleSelect = (select: string) => (selected.value = select);

    const handleClickCall = async () => {
      if (isChatWithRoboot.value) {
        const ret = await UserService.getInstance().contact_custom_service({
          outLetID: target,
        });
        if (ret.code === 200) {
          callPhone.value = ret.data.phone;
        } else {
          return;
        }
      } else {
        const ret = await getMsgFromAddress([route.query.targetId as string]);
        callPhone.value = ret[0].phone;
      }
      showCall.value = true;
    };

    const useSentence = async (content: string) => {
      /* 问 */
      messageStore.displayNewMessage({
        content: {
          content,
        },
        from: getFromId() as string,
        target: target,
        uuid: uuidv4(),
        state: "success",
        datetime: new Date().getTime(),
        type: ChatMessageTypes.robot,
      });

      await ChatDBService.getInstance().handleEveryReceive({
        msg: {
          content: {
            content: content,
          },
          from: getFromId() as string,
          target: target,
          uuid: uuidv4(),
          state: "success",
          datetime: new Date().getTime(),
          type: ChatMessageTypes.robot,
        },
        masterId: getFromId() as string,
        isChattingWithTargetId: true,
        isRoboot: true,
      });

      queryFaqAnswer({
        question: content,
      }).then((ret) => {
        if (ret.code === 200) {
          /* 答 */
          messageStore.displayNewMessage({
            content: {
              content: ret.data,
            },
            from: target,
            target: getFromId(),
            uuid: uuidv4(),
            state: null,
            datetime: new Date().getTime(),
            type: ChatMessageTypes.robot,
          });

          ChatDBService.getInstance().handleEveryReceive({
            msg: {
              content: {
                content: ret.data,
              },
              from: target as string,
              target: getFromId(),
              uuid: uuidv4(),
              state: null,
              datetime: new Date().getTime(),
              type: ChatMessageTypes.robot,
            },
            masterId: getFromId() as string,
            isChattingWithTargetId: true,
            isRoboot: true,
          });
        }
      });
    };

    watch(chatCardTimeStamp, async () => {
      const messageList = await ChatMessageDB.getInstance().getMessage(
        getFromId() as string,
        route.query.targetId as string
      );
      messageStore.messages.splice(0, messageStore.messages.length);
      messageStore.messages.push(...messageList);
    });

    const title = ref("");

    const isChatWithRoboot = computed(() => {
      return route.query.outlet !== undefined;
    });

    const isRobootOffLine = computed(() => {
      if (isChatWithRoboot.value) {
        return !!title?.value?.match(/\(已停止营业\)$/);
      } else {
        return undefined;
      }
    });

    const initTitle = async () => {
      if (isChatWithRoboot.value) {
        let list = await getDisplayNames([
          { outletPosId: route.query.targetId as string },
        ]);
        title.value = list[0] as string;
        list = await getDisplayNames(
          [{ outletPosId: route.query.targetId as string }],
          true
        );
        title.value = list[0] as string;
      } else {
        let list = await getDisplayNames([
          { address: route.query.targetId as string },
        ]);
        title.value = list[0] as string;
        list = await getDisplayNames(
          [{ address: route.query.targetId as string }],
          true
        );
        title.value = list[0] as string;
      }
    };

    const initMessageList = async () => {
      messageStore.messages.splice(0, messageStore.messages.length);
      const messageList = await ChatMessageDB.getInstance().getMessage(
        getFromId() as string,
        route.query.targetId as string
      );
      messageStore.messages.push(...messageList);
      ChatListCardDB.getInstance().readMsg(
        getFromId() as string,
        route.query.targetId as string
      );
    };

    const notifyUserAndStaffTheChatBegin = async () => {
      await sendChatMessage({
        type: ChatMessageTypes.Card,
        content: {
          bank: CONST_START_CHAT.user.id,
          name: CONST_START_CHAT.staff.id,
          account: "",
        } as MessageContent,
        target: route.query.targetId as string,
      });
    };

    watch(
      () => route.query.targetId,
      async () => {
        await initMessageList();
        await initTitle();
        if (!isChatWithRoboot.value && route.query.beginChat !== undefined) {
          setTimeout(() => {
            if (!isChatWithRoboot.value) {
              notifyUserAndStaffTheChatBegin();
            }
          }, 1000);
        }
      }
    );

    onMounted(async () => {
      initMessageList();
      initTitle();
      serviceShowValue.value = "人工服务";
    });

    const showCall = ref(false);
    const callPhone = ref("");

    const isUser = computed(() => {
      return getUserMsg()?.role2 === eRole.user;
    });

    return {
      connectionState,
      selected,
      handleSelect,
      showServiceRating,
      showShortSentences,
      useSentence,
      sentenceList,
      sentensesLoading,
      title,
      questionSelected,
      handleClickQuestionOption,
      serviceSelected,
      serviceShowValue,
      handleClickService,
      handleClickCall,
      showCall,
      callPhone,
      isChatWithRoboot,
      isUser,
      isRobootOffLine,
    };
  },
});
</script>
