<script setup>
import { ref, unref, computed, onUnmounted } from 'vue';
import { useMessage, NDatePicker } from 'naive-ui';
import { BaseButton, RecodeCardItem, TheSubMenu, TheChatView, ChatWelcome, SvgIcon } from '@/components';
import { ChatAsk, ChatAnswer } from '@/components/Chat';
import { chatApi } from '@/api/chat';

import {useInfinite, useScroll, useChat, useRecommend} from '@/composables';

const ANSWER_ID_KEY = '@@id@@';

let controller = new AbortController();

const { recordList, isFetching, onScrolltolower, onReset, addHistoryRecord } = useInfinite('/front/bigModel/qa/pageList', { module: 1 });
const { scrollRef, scrollToBottom, scrollToBottomIfAtBottom } = useScroll();
const { chatDataSource, addChat, updateChat, clearChat, updateById } = useChat();

const message = useMessage();
const reportDate = ref();
const switchActive = ref(false);

const isLoading = ref(false);
const inputRef = ref(null);

const currenSessionId = ref(null);

const isExistInHistory = computed(() => (recordList.value.findIndex(({ sessionId: sId }) => sId === unref(currenSessionId)) === -1));

// 新建对话
const handleCreateDialog = async () => {
  message.destroyAll();

  if (unref(isLoading)) {
    return message.warning('当前对话生成中');
  }

  if (!unref(chatDataSource).length) {
    return message.info('已切换最新会话');
  }

  currenSessionId.value = null;

  clearChat();
}

// 查询对话详情
const handleChatDetail = async ({ sessionId }) => {
  isLoading.value = false;

  controller.abort();

  const { data } = await chatApi.getAnswerHistoryDetail({ sessionId });

  chatDataSource.value = data.map(item => ({ ...item, loading: false,  }));
  currenSessionId.value = sessionId;

  scrollToBottom();
}

const onRegenerate = async ({ question, realQuestion }) => {
  controller = new AbortController();

  const sessionId = unref(currenSessionId);
  const params = {
    data: {
      sessionId,
      showVal: question,
      question: realQuestion || question,
      module: 1,
      isStrong: Number(unref(switchActive)),
      reportDate: reportDate.value
    },
    signal: controller.signal,
    onDownloadProgress: ({ event }) => {
      const xhr = event.target;
      const { responseText } = xhr;
      const [ answer ] = responseText.split(ANSWER_ID_KEY);

      updateChat({
        sessionId,
        showVal:question,
        answer,
        loading: true,
        delayLoading: false,
      })

      scrollToBottomIfAtBottom();
    }
  }

  try {
    const { data } = await chatApi.getChatStream(params);
 
    const [ answer, id ] = data.split(ANSWER_ID_KEY);

    updateChat({
      id,
      sessionId,
      showVal: question,
      answer,
      loading: false,
      delayLoading: false
    })
    
    scrollToBottomIfAtBottom();
  }
  catch (error){
    console.log("取消了请求 - catch", error);
  }
  finally {
    isLoading.value = false;
    onReset();
  }
}
// 提交问题
const handleSubmit = async (question, realQuestion = '') => {
  // 用于模拟 - 内容生成前置等待状态
  
  if (unref(isExistInHistory)) {
    const { data: sessionId } = await chatApi.getChatSessionTag();
    currenSessionId.value = sessionId;
  }
  
  isLoading.value = true;

  addChat({
    sessionId: unref(currenSessionId),
    showVal: question,
    realQuestion,
    answer: '',
    loading: true,
    delayLoading: true,
  })

  scrollToBottom();

  setTimeout(() => onRegenerate({ question, realQuestion }), 2 * 1000);
}

// 处理推荐问题
const handleCreateOrder = () => {
  
  if ( !reportDate.value ) {
    return message.warning('请选择日期');
  }

  handleSubmit(`请生成${reportDate.value}智能工单分析报告`);
}

// 删除历史对话
const handeChatDelete = async (id) => {
  await chatApi.deleteHistory(id);
  onReset();
  clearChat();
  message.success('删除成功');
}

onUnmounted(() => {
  controller.abort();
})
</script>

<template>
  <section class="flex items-start h-full">

    <TheSubMenu title="智能工单" @scrollToLower="onScrolltolower" :loading="isFetching">
      <template #top>
        <div class="create-btn px-[11px] pb-[22px]">
          <BaseButton @click="handleCreateDialog">新建工单</BaseButton>
        </div>
      </template>

      <div class="pr-[4px] text-[#5e5e5e]">
        <RecodeCardItem v-for="item, index in recordList" :key="item.sessionId + index" :title="item.showVal"
          :time="item.createTime" :data-item="item" @on-click="handleChatDetail" @on-delete="handeChatDelete" />
      </div>
    </TheSubMenu>

    <TheChatView ref="scrollRef" :is-footer="false">
      <ChatWelcome 
        title="您好，我是LibraAI智慧工单助手" 
        :sub-title="[
          '基于大语言模型的智能工单分析助手，可以为您实现数据分析及数据解读',
          '选择日期并为您生成日报分析'
        ]"
        v-if="!chatDataSource.length"
      />

      <div class="conversation-item" v-if="chatDataSource.length">
        <template v-for="item in chatDataSource" :key="item.id">
          <ChatAsk :content="item.showVal" :sessionId="item.sessionId"></ChatAsk>
          <ChatAnswer
            :id="item.id"
            :content="item.answer"
            :loading="item.loading"
            :delay-loading="item.delayLoading"
            :isSatisfied="item.isSatisfied"
            @on-click-icon=" params => updateById(params)"
          ></ChatAnswer>
        </template>
      </div>

      <div class="order-container px-[60px] py-[30px] mt-[36px] rounded-[10px] bg-[#fff]" v-if="!chatDataSource.length">
        <div class="flex items-end justify-start space-x-[16px] pb-[20px] border-b-[1px] border-solid border-[#F1F1F1]">
          <span class="text-[20px] leading-[28px] font-bold">智慧工单报告</span>
          <span class="text-[12px] text-[#8F959C]">选择日期后为您生成日报工单</span>
        </div>

        <main class="order pt-[20px] text-[#1A2029]">
          <div class="flex items-center justify-start text-[16px] space-x-[16px]">
            <span class="font-bold">选择时间</span>
            <div class="w-[164px] border-[1px] border-[#EFEFF0] rounded-[8px] overflow-hidden">
              <NDatePicker placeholder="选择日期" :readonly="true" v-model:formatted-value="reportDate" value-format="yyyy-MM-dd">
                <template #date-icon>
                  <SvgIcon name="tool-arrow-bottom"></SvgIcon>
                </template>
              </NDatePicker>
            </div>
          </div>

          <dl class="pt-[26px] text-[#1A2029] space-y-[16px]">
            <dt class="text-[16px] font-bold leading-[22px]">报告内容</dt>
            <dd>1、水质数据、生化数据情况</dd>
            <dd>2、各项指标数据分析</dd>
            <dd>3、对于工艺调整方面、数据趋势方面的措施与建议</dd>
          </dl>
        </main>

        <footer class="pt-[24px]">
          <button class="btn-primary" @click="handleCreateOrder">立即生成</button>
        </footer>
      </div>
    </TheChatView>
  </section>
</template>

<style scoped lang="scss">
.n-input__input-el {
  font-size: 12px !important;
}

.list-item {
  margin-bottom: 16px;

  .title {
    font-size: 14px;
    font-weight: bold;
    line-height: 20px;
  }

  .item-top {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10px;

    .num {
      font-size: 12px;
      font-weight: 400;
      color: #B0B7C0;
    }
  }
}


.btn-primary {
  width: 88px;
  height: 32px;
  border-radius: 6px;
  background-color: #2454FF;
  font-size: 14px;
  line-height: 32px;
  color: #fff;

  &:hover {
    background: #1D43CC;
  }
}
</style>

<style lang="scss">
.order {
  .n-input__input-el, .n-input__placeholder {
    font-size: 14px;
  }
}
</style>