<script lang="ts" setup>
import type {
  AppListResult,
  ChatListResult,
  ResultItem,
  WordTempItem,
} from './typing';

import { onMounted, ref } from 'vue';

import { useUserStore } from '@vben/stores';

import { message, notification } from 'ant-design-vue';

import {
  deleteChatflow,
  getAppListByType,
  getChatflowMessage,
  getChatList,
  getChatParameters,
  sendWord,
} from '#/api';

import { WordListView, WordWorkView } from './components';

const temp = ref<AppListResult[]>([]);

const history = ref<ChatListResult[]>([]);
const loading = ref(true);
const params = ref([]);
const projectInfo = ref({});
const userStore = useUserStore();

const getLogs = async (appid: string) => {
  loading.value = true;
  const res = await getChatList(
    {
      appid,
    },
    {
      userId: userStore.userInfo?.userId || '',
      lastId: '',
      sortBy: '',
      limit: '9',
    },
  );
  history.value = res.data;

  loading.value = false;
};

const getTemp = async () => {
  const res = await getAppListByType(1);
  if (Array.isArray(res) && res.length > 0) {
    // 提取 id 和 name 并赋值给 temp
    temp.value = res.map(({ id, name }) => ({ id, name }));
  }
};

const currentTemp = ref<AppListResult>({
  id: '',
  name: '',
});
const activeKey = ref('');

function handleClickMode(item: WordTempItem) {
  notification.success({
    message: `${item.name}`,
    description: '已选取',
    duration: 3,
  });
  currentTemp.value = item;
  getLogs(item.id);
  getParameters(item.id);
}

async function changeLogs(id: string) {
  const res = await getChatList(
    {
      appid: id,
    },
    {
      userId: userStore.userInfo?.userId || '',
      lastId: '',
      sortBy: '',
      limit: '9',
    },
  );
  history.value = res.data;
  activeKey.value = res.data[0].id;
}

function handleNewConversation() {
  // 清空项目信息
  projectInfo.value = {
    projectName: '',
    projectContext: '',
    projectKeyAvoidTechOrKeyword: '',
    userInitialInnovationPoint: '',
  };

  // 清空对话内容
  itemMessage.value = [];
}

const itemMessage = ref<ResultItem[]>([]);

async function deleteLog(item: any) {
  const res = await deleteChatflow({
    appId: currentTemp.value.id || '',
    conversationId: item,
    userId: userStore.userInfo?.userId || '',
  });
  if (res.message === '删除成功') {
    message.success('删除成功');
    await getLogs(currentTemp.value.id);
    handleNewConversation();
  } else {
    message.error('删除失败');
  }
}

async function getParameters(id: string) {
  const res = await getChatParameters(id);
  params.value = res.suggestedQuestions;
}

async function handleClick(item: string) {
  const res = await getChatflowMessage(currentTemp.value.id, {
    userId: userStore.userInfo?.userId || '',
    firstId: '',
    conversationId: item,
    limit: '',
  });
  projectInfo.value = res.data[0].inputs;
  itemMessage.value = [];
  if (res.data.length > 0) {
    res.data.forEach((msg) => {
      if (msg.inputs) {
        itemMessage.value.push({
          key: itemMessage.value.length + 1,
          role: 'user', // 'user' or 'ai'
          content: msg.query,
          // footer: msg.footer,
        });
      }
      if (msg.answer) {
        itemMessage.value.push({
          key: itemMessage.value.length + 1,
          role: 'ai',
          content: msg,
        });
      }
    });
  }
}

onMounted(() => {
  getTemp();
  handleNewConversation();
});
</script>

<template>
  <div class="layout">
    <div class="lg:w-1/6">
      <WordListView
        title="选择模板"
        :temp="temp"
        :items="history"
        :loading="loading"
        :key="activeKey"
        @click-mode="handleClickMode"
        @click="handleClick"
        @delete="deleteLog"
        @new-conversation="handleNewConversation"
      />
    </div>
    <WordWorkView
      :item="currentTemp"
      :params-data="params"
      :run-chat-flow="sendWord"
      :item-message="itemMessage"
      :project-info="projectInfo"
      @history="changeLogs"
    />
  </div>
</template>

<style scoped lang="less">
.layout {
  width: 100%;
  min-width: 1400px;
  height: 100%;
  display: flex;
  background: hsl(216deg 21.74% 95.49%);
  font-family: AlibabaPuHuiTi, v-deep(var(--ant-font-family)), sans-serif;
  border-radius: v-deep(var(--ant-border-radius));
}
</style>
