<template>
    <div class="demo-test">
      <McHeader :logoImg="'/src/assets/logo.svg'" :title="'MateChat'">
        <template #operationArea>
          <div class="operations">
            <i class="icon-close" @click="closeDrawer()"></i>
          </div>
        </template>
      </McHeader>
      <div v-if="startChat" ref="conversationRef" class="conversation-area">
        <template v-for="(msg, idx) in messages" :key="idx">
          <McBubble v-if="msg.from === 'user'" :content="msg.content" :align="'right'" :avatarConfig="msg.avatarConfig"></McBubble>
          <McBubble v-else :loading="msg.loading ?? false" :avatarPosition="msg.avatarPosition" :avatarConfig="msg.avatarConfig">
            <RenderMarkdown v-if="msg.type === 'common'" :content="msg.content"></RenderMarkdown>
            <div :id="'demoChart'+idx" 
              draggable="true"
              v-if="msg.type === 'card'"
              @dragstart="ondragstart($event, msg)"  
              @dragover.prevent="ondragover($event)"
              @dragleave.prevent="ondragleave($event)"
              @drop.prevent="ondrop($event)" 
              :class="['content-card']"
              >
                <DemoCard :chartStr="msg.componentStr" :containerId="'demoChart'+idx"></DemoCard>
            </div>
            <template #bottom>
              
            </template>
          </McBubble>
        </template>
      </div>
      <div v-else class="welcome-page">
        <McIntroduction
          class="intro"
          logo-img="/src/assets/logo2x.svg"
          title="MateChat"
          sub-title="Hi，欢迎使用 MateChat"
          :description="[
            'MateChat 可以辅助研发人员编码、查询知识和相关作业信息、编写文档等。',
            '作为AI模型，MateChat 提供的答案可能不总是确定或准确的，但您的反馈可以帮助 MateChat 做的更好。',
          ]"
        ></McIntroduction>
       </div>
      <div style="padding: 0 12px 12px 12px">
        <McInput :value="inputValue" :maxLength="2000" @change="(e) => (inputValue = e)" @submit="onSubmit">
          <template #extra>
            <div class="input-foot-wrapper">
              <div class="input-foot-left">
                <span class="input-foot-dividing-line"></span>
                <span class="input-foot-maxlength">{{ inputValue.length }}/2000</span>
              </div>
              <div class="input-foot-right">
                <d-button icon="op-clearup" shape="round" :disabled="!inputValue" @click="inputValue = ''">清空输入</d-button>
              </div>
            </div>
          </template>
        </McInput>
      </div>
    </div>
  </template>
  
  <script>
  import { ref, defineComponent, nextTick, defineEmits, onMounted, onUnmounted, watch, onActivated, onDeactivated } from 'vue';
  import { introPrompt, simplePrompt, mockAnswer, guessQuestions } from './mock.constant';
  import DemoCard from './DemoCard/DemoCard.vue';
  import RenderMarkdown from './RenderMarkdown.vue';

  
  export default defineComponent({
    components: {
      DemoCard, RenderMarkdown
    },
    emits: ['closeDrawer', 'chartStrChange'],
    setup(props, { emit }) {
    onActivated(() => {
      if (window.savedState) {
        messages.value = window.savedState.messages;
        inputValue.value = window.savedState.inputValue;
        startChat.value = window.savedState.startChat;
        chartStr.value = window.savedState.chartStr;

        nextTick(() => {
          if (conversationRef.value) {
            conversationRef.value.scrollTop = conversationRef.value.scrollHeight;
          }
        });
      }
    });

    onDeactivated(() => {
      window.savedState = {
        messages: [...messages.value],
        inputValue: inputValue.value,
        startChat: startChat.value,
        chartStr: chartStr.value,
        scrollPosition: conversationRef.value?.scrollTop || 0
      };
      
    });

      const inputValue = ref('');
      const startChat = ref(false);
      const conversationRef = ref();
      const isAgentOpen = ref(false);
      const agentList = ref([
        { label: 'MateChat', value: 'matechat', active: true },
        { label: 'InsCode', value: 'inscode' },
      ]);
      const selectedAgent = ref(agentList.value[0]);
      const aiModelAvatar = {
        imgSrc: "/src/assets/logo.svg",
        width: 32,
        height: 32,
      };
      const customerAvatar = {
        name: 'Me',
        width: 32,
        height: 32,
      };
      const inputFootIcons = [
        { icon: 'icon-at', text: '智能体' },
        { icon: 'icon-standard', text: '词库' },
        { icon: 'icon-add', text: '附件' },
      ];
      

      const messages = ref([]);

      const chartStr = ref('');
  
      const onSubmit = (e, answer = undefined, type = 'common') => { 
        inputValue.value = '';
        if (!messages.value.length) {
          startChat.value = true;
        }
        messages.value.push({
          from: 'user',
          content: e,
          type,
          avatarPosition: 'side-right',
          avatarConfig: { ...customerAvatar },
        });
        nextTick(() => {
          conversationRef.value?.scrollTo({
            top: conversationRef.value.scrollHeight,
            behavior: 'smooth',
          });
        });
        getMockAnswer(e, 'common');
      };

      const getMockAnswer = (answer, type) => {
        const aiAnswer = {
          from: 'ai-model',
          content: answer,
          type,
          avatarPosition: 'side-left',
          avatarConfig: { ...aiModelAvatar },
          loading: true,
        }
        messages.value.push(aiAnswer);
        setTimeout(() => {
            messages.value.at(-1).loading = false;
        }, 1000);
      }
  
      const onNewConvo = () => {
        startChat.value = false;
        messages.value = [];
      };
  
      const onItemClick = (item) => {
        if (mockAnswer[item.value]) {
          // 使用 mock 数据
          onSubmit(item.label, mockAnswer[item.value]);
        } else {
          // 使用 AI 数据
          onSubmit(item.label);
        }
      };

      const closeDrawer = () => {
        emit('closeDrawer')
      };
  
      return {
        inputValue,
        conversationRef,
        inputFootIcons,
        messages,
        onSubmit,
        introPrompt,
        simplePrompt,
        onNewConvo,
        onItemClick,
        startChat,
        guessQuestions,
        closeDrawer,
        ondragstart,
        ondragover,
        ondragleave,
        ondrop,
        isAgentOpen,
        selectedAgent,
        agentList,
      };
    },
  });
  </script>
  
  <style scoped lang="scss">
  .demo-test {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    gap: 8px;
  
    .conversation-area,
    .welcome-page {
      flex: 1;
      display: flex;
      flex-direction: column;
      overflow: auto;
      padding: 0 12px;
    }
  
    .conversation-area {
      gap: 8px;
    }
  
    .welcome-page {
      gap: 24px;
      justify-content: space-between;
      .intro {
        padding-top: 40px;
        flex: 1;
      }
    }
  
    .guess-question {
      width: 100%;
      padding: 16px 12px;
      border-radius: var(--devui-border-radius-card);
      background-color: var(--devui-gray-form-control-bg);
  
      .guess-title {
        display: flex;
        justify-content: space-between;
        align-items: center;
        color: var(--devui-text);
        margin-bottom: 12px;
  
        & > div:first-child {
          font-weight: 700;
          font-size: var(--devui-font-size);
        }
        & > div:last-child {
          font-size: var(--devui-font-size-sm);
          cursor: pointer;
          span {
            margin-left: 4px;
          }
        }
      }
  
      .guess-content {
        display: flex;
        align-items: center;
        flex-wrap: wrap;
        gap: 8px;
        span {
          font-size: var(--devui-font-size-sm);
          color: var(--devui-text);
          padding: 4px 12px;
          border-radius: var(--devui-border-radius-full);
          background-color: var(--devui-gray-form-control-hover-bg);
          cursor: pointer;
        }
      }
    }
  
    .bubble-bottom-operations {
      margin-top: 8px;
      i {
        padding: 4px;
        border-radius: 4px;
        cursor: pointer;
  
        &:hover {
          background-color: var(--devui-icon-hover-bg);
        }
      }
    }
  
    .new-convo-button {
      padding: 0 12px;
      display: flex;
      justify-content: flex-end;
      align-items: center;
      height: 39px;
      gap: 4px;
    }
  
    :deep(.simple-prompt .mc-list) {
      justify-content: unset;
    }
  
    :deep(.intro-prompt .mc-list) {
      justify-content: center;
  
      .mc-list-item {
        flex: 1;
      }
    }
  
    .operations {
      i {
        padding: 4px;
        border-radius: 4px;
        cursor: pointer;
  
        &:hover {
          background: var(--devui-global-bg);
        }
      }
    }
  
    .agent-knowledge {
      flex: 1;
      display: flex;
      align-items: center;
  
      .agent-wrapper {
        display: flex;
        align-items: center;
        padding: 4px 8px;
        border-radius: var(--devui-border-radius-full);
        background-color: var(--devui-area);
        cursor: pointer;
  
        img {
          width: 16px;
          height: 16px;
          margin-right: 4px;
        }
  
        span {
          font-size: var(--devui-font-size);
          color: var(--devui-text);
          margin-right: 8px;
        }
  
        i {
          font-size: var(--devui-font-size);
          color: var(--devui-text);
          transition: transform 0.3s ease-in-out;
  
          &:last-child {
            margin-left: 4px;
          }
        }
  
        .is-open {
          transform: rotate(180deg);
        }
      }
  
      .agent-knowledge-dividing-line {
        width: 1px;
        height: 14px;
        margin: 0 12px;
        background-color: var(--devui-line);
      }
  
      .knowledge-wrapper {
        font-size: var(--devui-font-size);
        color: var(--devui-text);
        cursor: pointer;
  
        span {
          margin-left: 4px;
        }
      }
    }
  
    .input-foot-wrapper {
      display: flex;
      justify-content: space-between;
      align-items: center;
      width: 100%;
      height: 100%;
      margin-right: 8px;
  
      .input-foot-left {
        display: flex;
        align-items: center;
        gap: 8px;
  
        span {
          font-size: var(--devui-font-size-sm);
          color: var(--devui-text);
          cursor: pointer;
        }
  
        .input-foot-dividing-line {
          width: 1px;
          height: 14px;
          background-color: var(--devui-line);
        }
  
        .input-foot-maxlength {
          font-size: var(--devui-font-size-sm);
          color: var(--devui-aide-text);
        }
      }
  
      .input-foot-right {
        & > *:not(:first-child) {
          margin-left: 8px;
        }
      }
    }
  }

  .content-card {
  margin: 8px;
  overflow: hidden;
  background-color: var(--devui-base-bg);
  border-radius: var(--devui-border-radius-card);
  box-shadow: var(--devui-shadow-length-base) var(--devui-light-shadow);
  height: 400px;
  width: 400px;
  transition: transform 0.3s, box-shadow 0.3s;
  &.dragging {
    opacity: 1 !important;
  }
  &:hover {
    transform: translateY(-5px);
    
  }
}
</style>