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

const router = useRouter()

const userStore = useUserStore()

const { isMobile } = useLayoutConfig()

const fullScreenLoading = ref(false)
const agentId = ref('')
const dialogsId = ref('')

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: 'ShareWebApplication',
      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
    })
    .catch(() => {
      router.replace({ name: 'Home' })
    })
}

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

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

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

function handleCreateApplicationPage() {
  window.$dialog.info({
    title: '温馨提示',
    content: '为保证您的体验，请通过pc端访问',
    positiveText: '我知道啦',
  })
}

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: '确认要清空对话吗？',
    content: '清空对话将清空区域所有历史对话内容，确定清空对话吗？',
    negativeText: '取消',
    positiveText: '确定',
    onPositiveClick: () => {
      footerInputRef.value?.blockMessageResponse()
      messageList.value = []
      window.$message.success('清空成功')
    },
  })
}

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="h-full w-full">
    <PageHeader
      :agent-title="agentApplicationConfig.baseInfo.agentTitle"
      @to-login="handleToLoginPage"
      @to-create-application="handleCreateApplicationPage"
    />

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

      <div v-if="messageList.length > 0" class="flex w-full flex-1 flex-col overflow-hidden pt-5">
        <div class="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="footer-operation px-4">
        <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>
</template>

<style lang="scss" scoped>
.footer-operation {
  padding-bottom: constant(safe-area-inset-bottom);
  padding-bottom: env(safe-area-inset-bottom);
}

@include custom-scrollbar(4px);
</style>
