<template>
  <div class="page">
    <a-card v-if="current" :bordered="false" :title="`${current.title}`">
      <template #extra>
        <a-space>
          <a @click="onEdit">{{ isUpdate ? '预览' : '编辑' }}</a>
          <a-divider v-if="isUpdate" type="vertical" />
          <a v-if="isUpdate" type="primary" @click="save">保存</a>
        </a-space>
      </template>
      <div class="content">
        <!-- 编辑器 -->
        <byte-md-editor
            v-if="isUpdate"
            v-model:value="content"
            placeholder="请输入您的内容，图片请直接粘贴"
            :locale="zh_Hans"
            mode="split"
            :plugins="plugins"
            :editorConfig="{ lineNumbers: true }"
            @paste="onPaste"
        />
        <byte-md-viewer v-else :value="content" :plugins="plugins" />
      </div>
    </a-card>
    <div class="docs-sumbit" v-if="isUpdate">
      <a-button type="primary" @click="save">保存</a-button>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import 'bytemd/dist/index.min.css';
  import { reactive, ref, watch } from 'vue';
  import 'github-markdown-css/github-markdown-light.css';
  import type { Docs } from '@/api/cms/docs/model';
  import { message } from 'ant-design-vue';
  import ByteMdEditor from '@/components/ByteMdEditor/index.vue';
  import highlight from '@bytemd/plugin-highlight';
  // 中文语言文件
  import zh_Hans from 'bytemd/locales/zh_Hans.json';
  // // 链接、删除线、复选框、表格等的插件
  import gfm from '@bytemd/plugin-gfm';
  // // 插件的中文语言文件
  import zh_HansGfm from '@bytemd/plugin-gfm/locales/zh_Hans.json';
  // // 预览界面的样式，这里用的 github 的 markdown 主题
  import 'github-markdown-css/github-markdown-light.css';
  import { addDocs, updateDocs } from '@/api/cms/docs';
  import {ItemType} from "ele-admin-pro/es/ele-image-upload/types";
  import {uploadFile} from "@/api/system/file";

  const props = defineProps<{
    // 文档 id
    current?: Docs | null;
  }>();

  // 插件
  const plugins = ref([
    gfm({
      locale: zh_HansGfm
    }),
    highlight()
  ]);

  // 提交状态
  const loading = ref(false);
  // 编辑器内容，双向绑定
  const content = ref('');
  const editStatus = ref(false);
  // const disabled = ref(false);
  // 是否是修改
  const isUpdate = ref(false);
  // const docsContentId = ref(0);

  const form = reactive<Docs>({
    docsId: 0,
    content: ''
  });

  const onEdit = () => {
    isUpdate.value = !isUpdate.value;
  }


  /* 粘贴图片上传服务器并插入编辑器 */
  const onPaste = (e) => {
    console.log(e);
    const items = (e.clipboardData || e.originalEvent.clipboardData).items;
    console.log(items);
    let hasFile = false;
    for (let i = 0; i < items.length; i++) {
      if (items[i].type.indexOf('image') !== -1) {
        let file = items[i].getAsFile();
        const item: ItemType = {
          file,
          uid: (file as any).lastModified,
          name: file.name
        };
        uploadFile(<File>item.file)
            .then((result) => {
              const addPath = '!['+result.name+']('+ result.url+')\n\r';
              content.value = content.value + addPath
            })
            .catch((e) => {
              message.error(e.message);
            });
        hasFile = true;
      }
    }
    if (hasFile) {
      e.preventDefault();
    }
  }

  // 保存文档
  const save = () => {
    loading.value = true;
    const docsData = {
      ...form,
      docsId: props.current?.docsId,
      content: content.value
    };
    const saveOrUpdate = isUpdate.value ? updateDocs : addDocs;
    saveOrUpdate(docsData)
      .then((msg) => {
        loading.value = false;
        isUpdate.value = false;
        message.success(msg);
      })
      .catch((e) => {
        loading.value = false;
        message.error(e.message);
      });
  };

  // 监听文档 id 变化
  watch(
    () => props.current?.docsId,
    () => {
      content.value = props.current?.content + '';
    }
  );
</script>

<script lang="ts">
  export default {
    name: 'Markdown'
  };
</script>
<style lang="less" scoped>
  /deep/.markdown-body{
    background-color: transparent; /* 设置背景透明 */
  }
  .sys-category-table :deep(.ant-table-body) {
    overflow: auto !important;
    overflow: overlay !important;
  }

  .sys-category-table :deep(.ant-table-pagination.ant-pagination) {
    padding: 0 4px;
    margin-bottom: 0;
  }
  .content *{
      max-width: 80%;
  }
  .docs-sumbit {
    margin: 20px 0;
  }
</style>
