<template>
  <PageWrapper dense fixedHeight contentFullHeight class="bg-white">
    <div class="write-container">
      <div class="dialogue-box" v-if="state.list.length > 0">
        <div class="content answer-box" id="answer-box">
          <div class="item-box" v-for="(item, index) in state.list" :key="index">
            <div class="item right">
              <span class="text"> {{ item.question }} </span>
            </div>
            <div class="item left">
              <MarkdownViewer :value="item.answer" />
              <div v-if="item.answer">
                <a-button type="link" @click="handleDownLoad(0, item.answer)">下载md</a-button>
                <a-button type="link" @click="handleDownLoad(1, item.answer)">下载word</a-button>
                <a-button type="link" @click="handleDownLoad(2, item.answer)">下载pdf</a-button>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="header-box">
        <div class="title">帮我写作</div>
        <div class="detail">多种体裁，润色校对，一键成文</div>
      </div>
      <div class="relative">
        <div contenteditable="true" class="editable-textbox" ref="textBoxRef" @input="handleInput">
          <!-- <div v-if="selectContent.length">
            <div v-for="(info, index) in selectContent" :key="index">
              <span v-if="info.type === 'span'">{{ info.text }}</span>
              <span v-else-if="info.type === 'tag'" class="tag-span">{{ info.text }}</span>
              <a-select
                v-model:value="info.text"
                class="positon-class"
                contenteditable="false"
                v-else-if="info.type === 'select'"
              >
                <a-select-option :value="option" v-for="(option, idx) in info.options" :key="idx">
                  {{ option }}
                </a-select-option>
              </a-select>
              <div v-else-if="info.type === 'placeholder'" class="input-content">
                <span class="placeholder" :placeholder="info.placeholder" contenteditable="true">
                  {{ info.text }}
                </span>
              </div>
            </div>
          </div> -->
        </div>
        <ArrowUpOutlined :style="btnStyle" class="submit-icon" @click="handleSubmit" />
      </div>
      <a-tabs v-model:activeKey="activeKey" class="tabs-box">
        <a-tab-pane :key="index" :tab="item.title" v-for="(item, index) in data">
          <div class="tab-container">
            <div
              v-for="(info, idx) in item.content"
              :key="idx"
              :class="[
                'content-box',
                idx === selectedIdx ? 'active' : '',
                info.img ? 'hasImg-box' : '',
              ]"
              @click="handleSelectType(info.content, idx)"
            >
              <div class="content-title">
                <div
                  class="title-icon"
                  :style="{ background: info.color, borderColor: info.color }"
                  v-if="info.icon"
                >
                  <IconFontSymbol :icon="info.icon" fontSize="12" fillColor="#fff" />
                </div>
                <span>{{ info.title }}</span>
              </div>
              <div class="content-detail">{{ info.detail }}</div>
              <img :src="info.img" v-if="info.img" />
            </div>
          </div>
        </a-tab-pane>
      </a-tabs>
    </div>
  </PageWrapper>
</template>
<script setup lang="ts">
  import { ref, reactive, computed, nextTick } from 'vue';
  import { PageWrapper } from '/@/components/Page';
  import { MarkdownViewer } from '/@/components/Markdown';
  import {
    SelectContent,
    DataTypes,
    all,
    work,
    marketing,
    education,
    article,
    literature,
    reply,
  } from './content';
  import IconFontSymbol from '/@/components/IconFontSymbol/Index.vue';
  import { ArrowUpOutlined } from '@ant-design/icons-vue';
  import { cloneDeep } from 'lodash-es';
  import { getAppEnvConfig } from '/@/utils/env';
  import { useUserStore } from '/@/store/modules/user';
  import { sendAIAnswer, downLoadAIAnswer } from '/@/api/aiCreateTable';
  import { downloadByData } from '/@/utils/file/download';

  const data: {
    title: string;
    content: DataTypes[];
  }[] = [
    {
      title: '全部',
      content: [...all, ...work, ...marketing, ...education, ...article, ...literature, ...reply],
    },
    {
      title: '工作',
      content: work,
    },
    {
      title: '商业营销',
      content: marketing,
    },
    {
      title: '学习/教育',
      content: education,
    },
    {
      title: '社媒文章',
      content: article,
    },
    {
      title: '文学艺术',
      content: literature,
    },
    {
      title: '回复和改写',
      content: reply,
    },
  ];
  const userStore = useUserStore();

  const activeKey = ref(0);
  const textBoxRef = ref();
  const selectContent = ref<SelectContent[]>([]);
  const answer = ref<string>('');
  const selectedIdx = ref();
  const question = ref('');
  const showContent = ref(true);

  const state = reactive({
    list: [] as Array<{ question: string; answer?: string }>,
  });

  const btnStyle = computed(() => {
    if (!!question.value) {
      return {
        color: '#fff',
        background: '#0057ff',
        cursor: 'pointer',
      };
    } else {
      return {
        color: '#eee',
        background: '#d9d9d9',
        cursor: 'not-allowed',
      };
    }
  });

  const handleSelectType = (info, idx) => {
    showContent.value = false;
    setTimeout(() => {
      showContent.value = true;
      if (selectedIdx.value === idx) {
        selectedIdx.value = null;
        selectContent.value = [];
      } else {
        selectedIdx.value = idx;
        selectContent.value = cloneDeep(info);
        let strHtml = '';
        selectContent.value.forEach((info) => {
          if (info.type === 'span') {
            strHtml += `<span>${info.text}</span>`;
          } else if (info.type === 'tag') {
            strHtml += `<span class="tag-span">${info.text}</span>`;
          } else if (info.type === 'select') {
            let optHtml = '';
            info.options?.forEach((option, idx) => {
              optHtml += `<a-select-option value="${option}" key="${idx}">
                  ${option}
                </a-select-option>`;
            });
            strHtml += `<a-select
                v-model:value="${info.text}"
                class="positon-class"
                contenteditable="false" 
              >
                ${optHtml}
              </a-select>`;
          } else if (info.type === 'placeholder') {
            strHtml += `<div   class="input-content">
                <span class="placeholder" placeholder="${info.placeholder}" contenteditable="true"></span>
              </div>`;
          }
        });
        if (document.querySelector('.editable-textbox')) {
          document.querySelector('.editable-textbox')!.innerHTML = strHtml;
        }
      }
      nextTick(() => {
        if (document.querySelector('.editable-textbox')) {
          question.value = document.querySelector('.editable-textbox')!.textContent?.trim() || '';
        }
      });
    });
  };

  const handleInput = () => {
    if (document.querySelector('.editable-textbox'))
      question.value = document.querySelector('.editable-textbox')!.textContent?.trim() || '';
  };

  const scrollToBottom = () => {
    const divElement = document.getElementById('answer-box');
    if (divElement) {
      divElement.scrollTop = divElement?.scrollHeight;
    }
  };

  const handleSubmit = () => {
    if (!!question.value) {
      const clientId = userStore.getToken; // 唯一客户端标识（可动态生成）
      const message = document.querySelector('.editable-textbox')!.textContent?.trim() || ''; // 唯一客户端标识（可动态生成）
      const eventSource = new EventSource(
        `${
          getAppEnvConfig().VITE_GLOB_API_URL
        }/system/ai/kimi/chat?clientId=${clientId}&message=${encodeURIComponent(message)}`,
      );
      const obj = { question: question.value, answer: '' };
      state.list.push(obj);
      scrollToBottom();
      question.value = '';
      selectedIdx.value = null;
      selectContent.value = [];

      eventSource.onmessage = (event) => {
        const message = event.data;
        const info: string = message.replace('data: ', '').trim() || ''; // 去除前缀 "data: "
        if (info === '[DONE]') {
          answer.value = '';
        } else {
          if (info.includes('```')) {
            answer.value += '\r\n' + info;
          } else if (info === '') {
            answer.value += '\r\n';
          } else {
            answer.value += info;
          }
          state.list[state.list.length - 1].answer = answer.value;
          scrollToBottom();
        }
      };

      // 错误处理
      eventSource.onerror = () => {
        eventSource.close();
      };
    }
  };

  const handleDownLoad = async (type, content) => {
    const key = await sendAIAnswer(encodeURIComponent(content));
    const res = await downLoadAIAnswer({ fileType: type, key });
    let suffix = '';
    switch (type) {
      case 0:
        suffix = 'md';
        break;
      case 1:
        suffix = 'docx';
        break;
      case 2:
        suffix = 'pdf';
        break;
    }
    downloadByData(res.data, `写作.${suffix}`);
  };
</script>
<style lang="less" scoped>
  :deep(.vben-page-wrapper-content) {
    overflow: auto;
  }

  .write-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 10px 0;

    .dialogue-box {
      display: flex;
      align-items: center;
      width: 800px;
      height: 500px;
      overflow: auto;
      margin-bottom: 10px;

      .content {
        flex: 1;
        display: flex;
        flex-flow: column;
        min-height: 46px;
        box-sizing: border-box;
        max-width: 100%;
        position: relative;
        height: 100%;
      }

      .answer-box {
        color: rgb(0 0 0 / 80%);
      }

      .item-box {
        display: flex;
        flex-direction: column;
        font-size: 16px;

        .text {
          width: 100%;
        }

        .item {
          display: flex;
        }

        .left {
          align-self: flex-start;
          flex-direction: column;
          max-width: calc(100% - 10px);
          margin-left: 10px;
        }

        .right {
          align-self: flex-end;
          background: #f3f3f3;
          padding: 5px 15px;
          border-radius: 5px;
          margin: 15px 10px;
          max-width: calc(100% - 20px);
        }
      }
    }

    .header-box {
      width: 800px;
    }

    .title {
      font-size: 24px;
      font-weight: bold;
      text-align: center;
    }

    .detail {
      font-size: 16px;
      color: #0000004d;
      text-align: center;
      margin: 10px 0 20px;
    }

    .tabs-box {
      width: 800px;

      :deep(.ant-tabs-content-holder) {
        overflow: auto;
        padding-bottom: 5px;
      }

      .tab-container {
        display: flex;
        flex-wrap: wrap;
        gap: 10px;

        .hasImg-box {
          padding-top: 10px !important;
          position: relative;
          overflow: hidden;

          img {
            position: absolute;
            top: 54px;
            left: 35px;
            width: 110px;
          }

          .content-detail {
            margin-top: 5px !important;
          }
        }

        .content-box {
          width: 190px;
          border: 1px solid #ebebeb;
          border-radius: 10px;
          height: 90px;
          padding: 16px 16px 0;

          &:hover {
            box-shadow: 0 6px 10px 0 #ebebeb;
          }

          .content-title {
            display: flex;
            align-items: center;
            font-size: 16px;

            .title-icon {
              border: 1px solid #ff9500;
              background: #ff9500;
              border-radius: 50%;
              padding: 3px;
              margin-right: 7px;
            }
          }

          .content-detail {
            margin-top: 15px;
            white-space: nowrap;
            text-overflow: ellipsis;
            overflow: hidden;
            color: #b2b2b2;
            font-size: 12px;
          }
        }

        .active {
          border-color: #0057ff;
        }
      }
    }

    .editable-textbox {
      border: 1px solid #ebebeb;
      border-radius: 20px;
      padding: 10px;
      height: 120px;
      font-size: 16px;
      width: 800px;
      overflow: auto;

      &:empty::before {
        content: '请输入你要撰写的内容';
        color: #ccc;
      }

      .ant-select {
        display: inline-block;
        margin: 0 5px;
        width: auto;
        border: none;
        background-color: #f0f5ff;
        color: #06f;
        font-size: 16px;
        border-radius: 10px;
      }

      :deep(.ant-select-selector) {
        display: flex;
        align-items: center;
        background-color: #f0f5ff;
        border: none;
        height: 28px;
      }

      :deep(.ant-select-arrow) {
        color: #06f;
      }

      :deep(.ant-select-selection-item) {
        font-weight: 600;
      }

      :deep(.tag-span) {
        display: inline-block;
        padding: 3px 7px;
        background: #f0f5ff;
        color: #06f;
        font-weight: 600;
        font-size: 16px;
        border-radius: 10px;
      }
    }

    .submit-icon {
      position: absolute;
      right: 10px;
      bottom: 10px;
      border: 1px solid;
      padding: 7px;
      border-radius: 50%;
    }

    :deep(.input-content) {
      display: inline-block;
      min-width: 20px;
      position: relative;

      span {
        color: #06f;
        background: #f0f5ff;
        border: none;
        box-shadow: none;
        padding: 3px 7px;
        font-size: 16px;
        font-weight: 600;
        display: inline-block;
        border-radius: 10px;
        max-width: 770px;
        margin: 5px 0;
      }

      .placeholder:empty::before {
        content: attr(placeholder);
        color: #a8c5ff;
      }

      textarea {
        display: inline-block;
        height: 100%;
        position: absolute;
        left: 0;
        top: 0;
        opacity: 1;
        min-width: 20px;
        color: #06f;
        background: #f0f5ff;
        border: none;
        box-shadow: none;
        padding: 2px 7px;
        font-size: 16px;
        font-weight: 600;

        &::placeholder {
          color: #a8c5ff;
        }
      }
    }

    :deep(.ant-tabs-top > .ant-tabs-nav::before) {
      border-bottom: none;
    }

    :deep(.ant-tabs-tab.ant-tabs-tab-active .ant-tabs-tab-btn) {
      color: #000;
      font-weight: bold;
    }

    :deep(.ant-tabs-ink-bar) {
      background-color: #000 !important;
    }

    :deep(.ant-tabs-tab:hover) {
      color: #000;
    }
  }

  .inner-text {
    color: pink;
  }

  :deep(.ant-btn) {
    padding: 0;
    margin-right: 10px;
  }
</style>
