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

import { onMounted, ref } from 'vue';

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

import {
  getAppListByType,
  getWorkflowInfo,
  getWorkflowList,
  sendPpt,
} from '#/api';

import { PptListView, PptWorkView } from './components';

const temp = ref([]);

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

const getLogs = async (appid: string, limit: number) => {
  loading.value = true;
  const res = await getWorkflowList({
    appid,
    limit,
  });
  // 将结果倒序后再赋值给 hitsory
  hitsory.value = res.reverse();
  loading.value = false;
};

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

async function handleClick(item: PPTTempItem) {
  // temp = item;
  const res = await getWorkflowInfo({
    appid: item.appId,
    workflowRunId: item.workflowRunId,
  });
  itemMessage.value = [];
  if (res.inputs) {
    itemMessage.value.push({
      key: itemMessage.value.length + 1,
      role: 'user',
      content: res.inputs.declarationDoc,
    });
  }
  if (res.outputs) {
    itemMessage.value.push({
      key: itemMessage.value.length + 1,
      role: 'ai',
      content: res.outputs.files[0],
    });
  }
}

function handleNewConversation() {
  // 清空对话内容
  itemMessage.value = [];
}

const currentTemp = ref<null | PPTTempItem>(null);

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

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

<template>
  <div class="layout">
    <div class="lg:w-1/6">
      <PptListView
        title="选择模板"
        :temp="temp"
        :items="hitsory"
        :loading="loading"
        @click-mode="handleClickMode"
        @click="handleClick"
        @new-conversation="handleNewConversation"
      />
    </div>
    <PptWorkView
      :item="currentTemp"
      :run-workflow="sendPpt"
      :item-message="itemMessage"
    />
  </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>
