<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import { useI18n } from 'vue-i18n'
import PageHeader from './components/web-page-header.vue'
import Preamble from './components/preamble.vue'
import MessageList from './components/message-list.vue'
import FooterInput from './components/footer-input.vue'
import { fetchCreateContinueQuestions, fetchCreateDialogues, fetchGetApplicationInfo } from '@/apis/agent-application'
import { PersonalAppConfigState } from '@/store/types/personal-app-config'
import { defaultPersonalAppConfigState } from '@/store/modules/personal-app-config'
import { createDefaultUserInfoFactory, useUserStore } from '@/store/modules/user'
import { useLayoutConfig } from '@/composables/useLayoutConfig'
import { fetchGetMemberInfoById } from '@/apis/user'
import { UserInfo } from '@/store/types/user'

const { t } = useI18n()

const router = useRouter()

const userStore = useUserStore()

const { isMobile } = useLayoutConfig()

const fullScreenLoading = ref(false)
const agentId = ref('')
const dialogsId = ref('')
const agentMemberInfo = ref<UserInfo>(createDefaultUserInfoFactory())

const agentApplicationConfig = ref<PersonalAppConfigState>(defaultPersonalAppConfigState())

const messageListRef = ref<InstanceType<typeof MessageList> | null>(null)
const footerInputRef = ref<InstanceType<typeof FooterInput> | null>(null)

const messageList = ref<ConversationMessageItem[]>([])

const continuousQuestionStatus = ref<'default' | 'close'>('default')
const continueQuestionList = ref<string[]>([])

onMounted(async () => {
  if (router.currentRoute.value.params.agentId) {
    agentId.value = router.currentRoute.value.params.agentId as string
  }

  if (isMobile.value) {
    router.replace({
      name: 'ShareMobileApplication',
      params: { agentId: agentId.value },
    })
  }

  if (agentId.value) {
    fullScreenLoading.value = true
    await handleGetApplicationDetail()
    userStore.isLogin && (await handleCreateDialogues())
    fullScreenLoading.value = false
    return
  }

  router.replace({ name: 'Home' })
})

async function handleGetApplicationDetail() {
  fetchGetApplicationInfo<PersonalAppConfigState>(agentId.value)
    .then((res) => {
      agentApplicationConfig.value = res.data
      continuousQuestionStatus.value = res.data.commConfig.continuousQuestionStatus
      document.title = agentApplicationConfig.value.baseInfo.agentTitle
      handleGetMemberInfo()
    })
    .catch(() => {
      router.replace({ name: 'Home' })
    })
}

async function handleGetMemberInfo() {
  const res = await fetchGetMemberInfoById<UserInfo>(agentApplicationConfig.value.baseInfo.memberId)

  if (res.code === 0) {
    agentMemberInfo.value = res.data
  }
}

async function handleCreateDialogues() {
  const res = await fetchCreateDialogues(agentId.value)

  if (res.code === 0) {
    dialogsId.value = res.data as string
  }
}

function handleBack() {
  if (!history.state.back) {
    router.replace({
      name: 'Home',
    })
  } else {
    router.back()
  }
}

function handleToLoginPage() {
  router.replace({
    name: 'Login',
    query: { redirect: encodeURIComponent(router.currentRoute.value.fullPath) },
  })
}

function handleCreateApplicationPage() {
  router.push({
    name: 'PersonalAppSetting',
  })
}

function handleAddMessageItem(messageItem: ConversationMessageItem) {
  messageList.value.push(messageItem)
}

function handleUpdateSpecifyMessageItem(messageItemIndex: number, newObj: Partial<ConversationMessageItem>) {
  if (messageList.value[messageItemIndex]) {
    Object.entries(newObj).forEach(([k, v]) => {
      ;(messageList.value[messageItemIndex] as any)[k as keyof typeof newObj] = v
    })
  }
}

function handleDeleteLastMessageItem() {
  messageList.value.pop()
}

function handleUpdatePageScroll() {
  messageListRef.value?.scrollToBottom()
}

function handleClearAllMessage() {
  window.$dialog.warning({
    title: t('common_module.dialogue_module.clear_message_dialog_title'),
    content: t('common_module.dialogue_module.clear_message_dialog_content'),
    negativeText: t('common_module.cancel_btn_text'),
    positiveText: t('common_module.confirm_btn_text'),
    onPositiveClick: () => {
      footerInputRef.value?.blockMessageResponse()
      messageList.value = []
      window.$message.success(t('common_module.clear_success_message'))
    },
  })
}

async function handleCreateContinueQuestions(replyTextContent: string) {
  const res = await fetchCreateContinueQuestions<string[]>({ input: replyTextContent })

  if (res.code === 0) {
    continueQuestionList.value = res.data
    handleUpdatePageScroll()
  }
}

function handleResetContinueQuestionList() {
  continueQuestionList.value = []
}
</script>

<template>
  <div v-loading="fullScreenLoading" class="flex h-screen min-h-[500px] w-full flex-col overflow-y-hidden">
    <main class="h-full min-w-[1100px]">
      <PageHeader
        :agent-application-config="agentApplicationConfig"
        :agent-member-info="agentMemberInfo"
        @back="handleBack"
        @to-login="handleToLoginPage"
        @to-create-application="handleCreateApplicationPage"
      />

      <div class="h-[calc(100%-68px)] w-full bg-[#f2f5f9]">
        <div class="mx-auto flex h-full w-[1000px] flex-col overflow-hidden">
          <div v-if="messageList.length === 0" class="w-full flex-1 overflow-auto px-5">
            <Preamble :agent-application-config="agentApplicationConfig" />
          </div>

          <div v-if="messageList.length > 0" class="flex w-full flex-1 flex-col overflow-hidden">
            <!-- <div class="my-5 ml-16 mr-5 border-b border-[#e8e9eb] py-6">
              <div class="flex items-start">
                <img :src="agentApplicationConfig.baseInfo.agentAvatar" class="h-14 w-14 rounded-xl" />
                <p class="font-500 ml-4 line-clamp-1 h-8 max-w-[90%] break-all text-2xl leading-8 text-[#151b26]">
                  {{ agentApplicationConfig.baseInfo.agentTitle }}
                </p>
              </div>
              <div
                v-show="agentApplicationConfig.commConfig.preamble"
                class="mt-3 rounded-xl border border-[#e8e9eb] bg-white px-4 py-3 shadow-[0_2px_2px_#0000000a]"
              >
                {{ agentApplicationConfig.commConfig.preamble }}
              </div>
            </div> -->
            <div class="mt-16 flex-1 overflow-auto">
              <MessageList
                ref="messageListRef"
                :agent-application-config="agentApplicationConfig"
                :message-list="messageList"
                :continuous-question-status="continuousQuestionStatus"
                :continuous-question-list="continueQuestionList"
              />
            </div>
          </div>

          <div class="px-5">
            <FooterInput
              ref="footerInputRef"
              :message-list="messageList"
              :dialogs-id="dialogsId"
              :agent-id="agentApplicationConfig.baseInfo.agentId"
              :continuous-question-status="continuousQuestionStatus"
              @add-message-item="handleAddMessageItem"
              @update-specify-message-item="handleUpdateSpecifyMessageItem"
              @delete-last-message-item="handleDeleteLastMessageItem"
              @update-page-scroll="handleUpdatePageScroll"
              @clear-all-message="handleClearAllMessage"
              @to-login="handleToLoginPage"
              @create-continue-questions="handleCreateContinueQuestions"
              @reset-continue-question-list="handleResetContinueQuestionList"
            />
          </div>
        </div>
      </div>
    </main>
  </div>
</template>

<style scoped lang="scss">
@include custom-scrollbar(6px);
</style>
