<script lang="tsx">
import { message, Tooltip } from 'ant-design-vue';
import { BubbleList } from '@/components/xt-chat/xt-bubble';
import type { BubbleListProps } from 'ant-design-x-vue';
import { useRoute } from 'vue-router';
import SenderInput from '../sender-input/index.vue';
import markdownit from 'markdown-it';
import { Typography } from 'ant-design-vue';
import { useClipboard } from '@vueuse/core';
import { genRandomId } from '@/utils/tools';

const QUESTION_ROLE = 'question';
const ANSWER_ROLE = 'text';

export default {
  setup(props, { emit, expose }) {
    const route = useRoute();
    const { copy, copied, isSupported } = useClipboard();

    const senderRef = ref(null);
    const searchValue = ref('');
    const generateLoading = ref(false);
    const conversationList = ref([]);
    const md = markdownit({ html: true, breaks: true });

    const conversationId = computed(() => {
      return route.params.conversationId;
    });

    const onCopy = (content: string) => {
      copy(content);
      message.success('复制成功！');
    };

    const onRefresh = (tempId: string, tempIndex: number) => {
      generateLoading.value = true;
      conversationList.value.splice(tempIndex, 1, {
        id: tempId,
        loading: true,
        role: ANSWER_ROLE,
      });
    };

    const handleSubmit = () => {
      if (generateLoading.value) {
        message.warning('停止生成后可发送');
        return;
      }

      generateLoading.value = true;
      conversationList.value.push({
        role: QUESTION_ROLE,
        content: searchValue.value,
      });

      const tempId = genRandomId();
      const tempIndex = conversationList.value.length;
      conversationList.value.push({
        id: tempId,
        loading: true,
        role: ANSWER_ROLE,
      });

      setTimeout(() => {
        const content = `> Render as markdown content to show rich text!`;
        searchValue.value = '';
        conversationList.value.splice(tempIndex, 1, {
          id: tempId,
          loading: false,
          role: ANSWER_ROLE,
          content,
          messageRender: (content) => (
            <Typography>
              <div v-html={md.render(content)}></div>
            </Typography>
          ),
          footer: ({ item }) => {
            // 判断当前元素是否是最后一个非QUESTION_ROLE的元素
            const nonQuestionElements = conversationList.value.filter((item) => item.role !== QUESTION_ROLE);
            const isLastAnswer = nonQuestionElements[nonQuestionElements.length - 1]?.id === item.id;

            return (
              <div class="flex items-center">
                <Tooltip title="复制" onClick={() => onCopy(content)}>
                  <icon-copy size={16} class="mr-12px color-#737478 cursor-pointer" />
                </Tooltip>
                {isLastAnswer && (
                  <Tooltip title="重新生成" onClick={() => onRefresh(tempId, tempIndex)}>
                    <icon-refresh size={16} class="color-#737478 cursor-pointer" />
                  </Tooltip>
                )}
              </div>
            );
          },
        });
      }, 1000);
    };

    const handleCancel = () => {
      generateLoading.value = false;
      message.info('取消生成');
    };

    const roles: BubbleListProps['roles'] = {
      [ANSWER_ROLE]: {
        placement: 'start',
        variant: 'borderless',
        typing: { step: 2, interval: 100 },
        onTypingComplete: () => {
          console.log('onTypingComplete');
          generateLoading.value = false;
        },
      },
      [QUESTION_ROLE]: {
        placement: 'end',
        shape: 'round',
      },
    };

    return () => (
      <div class="conversation-detail-wrap w-full h-full flex">
        <div class="flex-1 flex justify-center">
          <section class="main w-600px h-full relative flex flex-col pt-20px">
            <BubbleList class="flex-1" roles={roles} items={conversationList.value} />
            <div class="w-full flex flex-col justify-center items-center">
              <SenderInput
                class="w-full"
                ref={senderRef}
                placeholder="继续追问..."
                loading={generateLoading.value}
                v-model={searchValue.value}
                onSubmit={handleSubmit}
                onCancel={handleCancel}
              />
              <p class="cts !color-#939499 text-12px !lh-20px my-4px">内容由AI生成，仅供参考</p>
            </div>
          </section>
        </div>
      </div>
    );
  },
};
</script>

<style lang="scss" scoped>
@import './style.scss';
</style>
