<template>
  <div class="AIeditor">
    <Toolbar
      style="border-bottom: 1px solid #ccc"
      :editor="editorRef"
      :defaultConfig="toolbarConfig"
      mode="default"
    />
    <div class="main">
      <div class="bgeditor">
        <div class="editor" style="padding-top: 100px">
          <input
            contenteditable
            v-model="titleh1"
            style="
              display: block;
              width: calc(100% - 200px);
              font-size: 24px;
              margin: 0 auto;
              border: none;
              outline: none;
            "
            placeholder="无标题"
          />
          <Editor
            :defaultConfig="editorConfig"
            style="padding: 0 90px; height: calc(100% - 150px)"
            mode="default"
            @onCreated="handleCreated"
            @onChange="contentChange"
          />
          <Transition name="toolCol">
            <div class="tool" v-if="toolShow">
              <el-icon color="#cacaca" :size="25">
                <MoreFilled style="transform: rotate(90deg)" />
              </el-icon>
              <el-button
                type="primary"
                style="
                  border-top-right-radius: 0;
                  border-bottom-right-radius: 0;
                "
                @click="() => saveDagang(18)"
              >
                写内容
              </el-button>
              <el-button
                type="primary"
                style="
                    border-top-left-radius;
                  border-bottom-left-radius: 0;
                  margin-left: 0;
                "
                @click="() => saveDagang(17)"
              >
                写大纲
              </el-button>
              <div>
                <el-button v-if="load" :loading="load">
                  <svg class="circular" viewBox="-10, -10, 50, 50">
                    <path
                      class="path"
                      d="
                        M 30 15
                        L 28 17
                        M 25.61 25.61
                        A 15 15, 0, 0, 1, 15 30
                        A 15 15, 0, 1, 1, 27.99 7.5
                        L 15 15
                    "
                      style="stroke-width: 4px; fill: rgba(0, 0, 0, 0)"
                    />
                  </svg>
                </el-button>
              </div>
              <div
                class="btnType"
                :class="{ btnTypeAct: btnType === 'short' }"
                @click="btnType = 'short'"
              >
                短
              </div>
              <div
                class="btnType"
                :class="{ btnTypeAct: btnType === 'default' }"
                @click="btnType = 'default'"
              >
                中
              </div>
              <div
                class="btnType"
                :class="{ btnTypeAct: btnType === 'long' }"
                @click="btnType = 'long'"
              >
                长
              </div>
              <div style="amrgin-right: 10px" @click="toolShow = false">
                <el-icon color="#cacaca" :size="25"><ArrowRight /></el-icon>
              </div>
            </div>
          </Transition>
          <Transition name="toolBtn">
            <el-icon
              v-if="!toolShow"
              @click="toolShow = true"
              class="toolBtnClass"
              :size="22"
              color="#3b82f6"
              ><ArrowLeft
            /></el-icon>
          </Transition>
        </div>
      </div>

      <div class="operate" v-if="statusPage[1]">
        <Transition name="toolRight">
          <div
            v-if="noOpenSon"
            style="transition: all 0.2s ease; position: relative"
          >
            <div class="toolHead">
              <div
                class="toolHeadItem"
                v-for="(v, i) in select_right_btn_list"
                :key="'ttt' + i"
                :style="{ left: v.left + 'px' }"
                @click="() => change_select_right_btn_type(i)"
                :class="{ toolAct: v.index === 0 }"
              >
                {{ v.text }}
                <div class="line"></div>
              </div>
            </div>
            <component
              @saveData="saveData"
              @closeType="closeType"
              @setImage="setImage"
              :headTitle="titleh1"
              :html="() => editorRef.getHtml()"
              :text="() => editorRef.getText()"
              :is="component_list[select_right_btn_type]"
            ></component>
          </div>
        </Transition>
        <Transition name="toolRightSon">
          <div
            v-if="!noOpenSon"
            style="transition: all 0.2s ease; position: relative; height: 100%"
          >
            <div class="RightSonTitle">
              <div class="t_header animate__faster">
                <div class="header_left">
                  <div class="model-panel-logo">
                    <img
                      :src="right_head.icon"
                      style="width: 24px; height: 24px; vertical-align: middle"
                    />
                  </div>
                  <div class="holder"></div>
                  <div class="msg_flex">
                    <div class="model-panel-name">
                      <span class="mpn-name" v-text="right_head.name"></span>
                    </div>
                    <div class="desc" v-text="right_head.sub_text"></div>
                  </div>
                </div>
                <div class="header_right">
                  <button class="header-right-btn" @click="closeType">
                    <svg
                      data-v-d643dfde=""
                      width="20"
                      height="20"
                      viewBox="0 0 20 20"
                      fill="none"
                      xmlns="http://www.w3.org/2000/svg"
                    >
                      <path
                        data-v-d643dfde=""
                        d="M18.158 9.52589H3.27982L10.2875 3.29702C10.5295 3.08192 10.5513 2.71141 10.3362 2.46944C10.1212 2.22748 9.75067 2.20564 9.50868 2.42075L1.4614 9.57362C1.33624 9.68487 1.26465 9.84432 1.26465 10.0118C1.26465 10.1792 1.33624 10.3387 1.4614 10.4499L9.50866 17.6028C9.62032 17.7021 9.75935 17.7509 9.89785 17.7509C10.0595 17.7508 10.2204 17.6844 10.3362 17.5541C10.5513 17.3121 10.5295 16.9416 10.2875 16.7265L3.51322 10.7051H18.158C18.4818 10.7051 18.7442 10.4392 18.7442 10.1155C18.7442 9.79175 18.4818 9.52589 18.158 9.52589Z"
                        fill="#8E8E8E"
                      ></path>
                    </svg>
                  </button>
                </div>
              </div>
            </div>
            <component
              @closeType="closeType"
              @setHtml="setHtml"
              @setTitle="setTitle"
              @setImage="setImage"
              :headTitle="titleh1"
              :html="() => editorRef.getHtml()"
              :text="() => editorRef.getText()"
              :is="component_2_list[select_right_2_btn_type]"
            ></component>
          </div>
        </Transition>
      </div>
    </div>
  </div>
</template>

<script setup>
import '@wangeditor/editor/dist/css/style.css'; // 引入 css
import { onBeforeUnmount, ref, shallowRef, onMounted } from 'vue';
import { Editor, Toolbar } from '@wangeditor/editor-for-vue';
import { advertisement, generate_pc_get, getSID } from '@/api/aleditor.js';
// 右侧一级组件
import pen_ink from './components/pen_ink.vue';
import review from './components/review.vue';
import image from './components/image.vue';
import dictionary from './components/dictionary.vue';
import comment from './components/comment.vue';
// 右侧二级组件
import full_text from './components/full_text.vue';
import advertisementEle from './components/advertisement.vue';
import inspiration from './components/inspiration.vue';
import inspiration_fangan from './components/inspiration_fangan.vue';
import literature from './components/literature.vue';
import little_red_book from './components/little_red_book.vue';
import short_video from './components/short_video.vue';
import weekly from './components/weekly.vue';
import email from './components/email.vue';
import brainstorming from './components/brainstorming.vue';
import draw from './components/draw.vue';
import product_review from './components/product_review.vue';
import fission from './components/fission.vue';
import poetry from './components/poetry.vue';
import novel from './components/novel.vue';
import composition from './components/composition.vue';
import continuation from './components/continuation.vue';

// 右侧头部数据
const right_head = ref({});

const titleh1 = ref('');

const component_list = [pen_ink, review, image, dictionary, comment];
// index对应ai里的功能
const component_2_list = [
  full_text,
  advertisementEle,
  inspiration,
  literature,
  little_red_book,
  inspiration_fangan,
  short_video,
  weekly,
  email,
  brainstorming,
  draw,
  product_review,
  fission,
  poetry,
  novel,
  composition,
  continuation,
];

const noOpenSon = ref(true);

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();

// 内容 HTML
const select_right_btn_type = ref(0);
const select_right_2_btn_type = ref(0);
const select_right_btn_list = ref([
  {
    text: 'AI写作',
    width: 56,
    left: 0,
    index: 0,
  },
  {
    text: '校阅',
    width: 42,
    left: 75,
    index: 1,
  },
  {
    text: '图片',
    width: 42,
    left: 136,
    index: 2,
  },
  {
    text: '词典',
    width: 42,
    left: 197,
    index: 3,
  },
  {
    text: '评论',
    width: 42,
    left: 258,
    index: 4,
  },
]);

onMounted(() => {});

const statusPage = ref([false, true]); // 0 --> 目录  1 --> operate
const load = ref(false);
const toolShow = ref(true);
const btnType = ref('short');
let text = '';

const getSidFun = () => {
  getSID().then(r => {
    localStorage.setItem('fileId', r.fileId);
    localStorage.setItem('sid', r.sid);
  });
};

!localStorage.getItem('fileId') && getSidFun();

const toolbarConfig = {
  toolbarKeys: [
    'redo',
    'undo',
    'bold',
    'underline',
    'italic',
    'through',
    '|',
    'clearStyle',
    'color',
    'bgColor',
    'fontSize',
    'fontFamily',
    '|',
    'indent',
    'delIndent',
    'justifyLeft',
    'justifyRight',
    'justifyCenter',
    'justifyJustify',
    '|',
    'divider',
    'headerSelect',
    'bulletedList',
    'numberedList',
  ],
};
const editorConfig = {
  placeholder: '请输入内容...',
  hoverbarKeys: {
    text: {
      // 如有 match 函数，则优先根据 match 判断，而忽略 element type
      match: () => {
        // 可参考下文的源码
        // console.log(editor.getConfig());
      },
      menuKeys: [], // 定义你想要的 menu keys
    },
  },
};

const contentChange = () => {
  try {
    if (!window.getSelection()) return;
    const s = window.getSelection().getRangeAt(0);
    let SText = s.startContainer || s.endContainer || s.commonAncestorContainer;
    SText = SText.nodeValue || SText.innerText;
    if (!SText) return;
    const offset = editorRef.value.selection
      ? editorRef.value.selection.focus.offset
      : undefined;
    const NSText = SText.substring(0, offset) + '///' + SText.substring(offset);
    const ot = editorRef.value.getHtml().replace(SText, NSText);
    text = ot.split('///');
  } catch (error) {
    console.log(error)
  }
  // 编辑器修改
};

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  if (editorRef.value != null) editorRef.value.destroy();
});

const handleCreated = editor => {
  editorRef.value = editor; // 记录 editor 实例，重要！
};

const change_select_right_btn_type = index => {
  const oldList = JSON.parse(JSON.stringify(select_right_btn_list.value));
  const zIndex = oldList[index].index;
  const zLeft = oldList[index].left;
  select_right_btn_type.value = index;
  for (let i = 0; i < oldList.length; i++) {
    const v = oldList[i];
    if (v.index === 0) {
      v.index = zIndex;
      v.left = zLeft;
    }
    if (i === index) {
      v.index = 0;
      v.left = 0;
    }
  }
  for (let i = 0; i < oldList.length; i++) {
    const v = oldList[i];
    if (v.left === 0) continue;
    v.left = getLast(v.index, oldList);
  }
  select_right_btn_list.value = oldList;
};

const getLast = (index, li) => {
  let oldleft = 0;
  for (let i = 0; i < li.length; i++) {
    if (li[i].index >= index) continue;
    oldleft += li[i].width + 19;
  }
  return oldleft;
};

const closeType = () => {
  noOpenSon.value = !noOpenSon.value;
};

const saveData = item => {
  select_right_2_btn_type.value = item.index;
  right_head.value = item;
};

let doc_id = '';

// 右侧生成编辑器内容
const setHtml = html => {
  const ot = editorRef.value.getHtml();
  editorRef.value.setHtml(ot + '<p>' + html + '</p>');
};
// 右侧生成图片
const setImage = imgs => {
  const ot = editorRef.value.getHtml();
  if (typeof imgs == 'string') {
    editorRef.value.setHtml(ot + `<img src="${imgs}" />`);
  } else if (Array.isArray(imgs)) {
    for (let i = 0; i < imgs.length; i++) {
      const v = imgs[i];
      editorRef.value.setHtml(ot + `<img src="${v}" />`);
    }
  }
};
const setTitle = text => {
  titleh1.value = text;
};

// 写大纲
const saveDagang = generateType => {
  if (!titleh1.value) {
    return;
  }
  load.value = true;
  console.log(text);
  const p = {
    data: {
      title: titleh1.value,
      prev: text[0] || undefined, // 获取大纲内容
      next: text[1] || undefined,
    },
    generateType,
    length: btnType.value,
    noblock: true,
    query_type: generateType === 17 ? 'title' : 'content',
  };
  if (doc_id) {
    p.req = { doc_id };
  }
  advertisement({
    data: p,
    noload: true,
  }).then(r => {
    if (r.errCode !== 0) return (load.value = false);
    doc_id = r.data.doc_id;
    p.req = { doc_id };
    get(p, generateType);
  });
};
const get = (p, generateType) => {
  generate_pc_get({
    data: p,
    noload: true,
  })
    .then(res => {
      load.value = false;
      if (res.errCode !== 0 && res.data.status === 'RUNNING') {
        let t = setTimeout(() => {
          get(p);
          clearTimeout(t);
        }, 200);
        return;
      }
      if (generateType == 17) {
        let t = '';
        for (let i = 0; i < res.data.result.subtitles.length; i++) {
          const v = res.data.result.subtitles[i];
          t += `<h4>${v.title}</h4>`;
        }
        setHtml(t);
      } else {
        setHtml(res.data.result.content);
      }
    })
    .catch(() => {
      load.value = false;
    });
};
</script>

<style scoped>
.toolCol-enter-active,
.toolCol-leave-active {
  opacity: 1;
}
.toolCol-enter-from,
.toolCol-leave-to {
  transform: translateX(0%) !important;
  opacity: 0;
}

.toolRight-enter-active,
.toolRight-leave-active {
  transform: translateX(0%) !important;
  opacity: 1;
}
.toolRight-enter-from,
.toolRight-leave-to {
  transform: translateX(100%) !important;
  opacity: 0;
}

.toolRightSon-enter-active,
.toolRightSon-leave-active {
  transform: translateX(100%) !important;
  opacity: 1;
}
.toolRightSon-enter-from,
.toolRightSon-leave-to {
  transform: translateX(0%) !important;
  opacity: 0;
}

.toolBtn-enter-active,
.toolBtn-leave-active {
  opacity: 1;
}
.toolBtn-enter-from,
.toolBtn-leave-to {
  opacity: 0;
  transform: translateX(100%);
}
</style>

<style scoped>
@import url(./assets/css/righttop.css);
.AIeditor {
  height: 100%;
}

.AIeditor .main {
  height: calc(100% - 40px);
  overflow-y: auto;
  width: 100%;
  display: flex;
}

.editor {
  transition: all 0.2s ease;
  position: relative;
  width: 100%;
  max-width: 816px;
  box-shadow: 0 0 25px #eeeeee;
  height: 100vh;
  margin: 1em auto;
}

.bgeditor {
  padding: 0 73px 0 73px;
  flex: 1;
  height: 100vh;
  overflow: hidden;
}

.tool {
  transition: all 0.2s ease;
  bottom: 35px;
  align-items: center;
  display: flex;
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  border-radius: 3px;
  border: 1px solid #eee;
  height: 60px;
  width: 500px;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  padding: 8px 0 8px 9px;
  background-color: #fff;
  -webkit-box-pack: justify;
  -ms-flex-pack: justify;
  justify-content: space-between;
}

.btnType {
  width: 32px;
  height: 32px;
  background-color: #f5f5f5;
  color: #909399;
  font-size: 12px;
  border-radius: 3px;
  line-height: 32px;
  text-align: center;
  border: 1px solid transparent;
  cursor: pointer;
}

.btnTypeAct {
  background-color: #e4f2ff;
  border: 1px solid #3b82f6;
  color: #3b82f6;
}

.toolBtnClass {
  transition: all 0.2s ease;
  position: absolute;
  right: 5px;
  bottom: 55px;
}

.operate {
  flex: 1;
  margin-top: 1em;
  margin-left: 15px;
  height: 100vh;
  overflow-y: auto;
}

@media screen and (max-width: 1500px) {
  .bgeditor {
    padding: 0;
  }

  .operate {
    margin-left: 8px;
  }
}

.toolHead {
  position: sticky;
  top: 0;
  -webkit-box-flex: 0;
  -ms-flex: none;
  flex: none;
  z-index: 1;
  position: relative;
  width: 100%;
  height: 50px;
  /* display: flex;
    flex-wrap: wrap; */
}

.toolHeadItem {
  transition: all 0.3s ease;
  padding: 0.3em 0.5em;
  color: #8e8e9c;
  /* margin-right: 19px; */
  /* transform: scale(0); */
  font-size: 16px;
  text-align: center;
  /* display: inline-block; */
  position: absolute;
  line-height: 2;
  font-size: 14px;
  font-weight: 700;
  opacity: 0;
  cursor: pointer;
  order: 1;
}
.toolHead:hover .toolHeadItem {
  opacity: 1;
}
.toolHeadItem .line {
  height: 6px;
  border-radius: 5px;
  width: 115%;
  margin-left: -8%;
  background-color: #e1e1e1;
}
.toolAct {
  color: #1f1f1f;
  opacity: 1;
  /* order: 0; */
}
.toolAct .line {
  background-color: #8e8e8e;
}
</style>

<style>
.w-e-bar-show {
  justify-content: center;
}
</style>
