<template>
  <div class="page" v-if="docsId > 0">
    <a-card v-if="form" :bordered="false" :title="`${form.title}`">
      <!-- 编辑器 -->
      <tinymce-editor
        v-model:value="content"
        :disabled="disabled"
        :init="config"
        placeholder="图片直接粘贴自动上传"
      />
      <div class="docs-sumbit" style="margin-top: 20px">
        <a-space>
          <a-button
            type="primary"
            :disabled="loading || content == ''"
            @click="save"
            >保存</a-button
          >
          <a-button @click="openPreview(`/docs/${form.code}?id=${form.docsId}`)"
            >预览</a-button
          >
        </a-space>
      </div>
    </a-card>
  </div>
</template>

<script lang="ts" setup>
  import { reactive, ref, unref, watch } from 'vue';
  import 'github-markdown-css/github-markdown-light.css';
  import type { Docs } from '@/api/cms/docs/model';
  import { Form, message } from 'ant-design-vue';
  import TinymceEditor from '@/components/TinymceEditor/index.vue';
  import { uploadOss } from '@/api/system/file';
  import { addDocs, getDocs, updateDocs } from '@/api/cms/docs';
  import { useRouter } from 'vue-router';
  import { assignObject } from 'ele-admin-pro';
  import { openPreview } from '@/utils/common';

  const emit = defineEmits<{
    (e: 'echo', data: Docs): void;
  }>();

  const { currentRoute } = useRouter();
  const useForm = Form.useForm;
  // 提交状态
  const loading = ref(false);
  // 编辑器内容，双向绑定
  const content = ref('');
  const disabled = ref(false);
  // 是否是修改
  const isUpdate = ref(false);
  // 文档ID
  const docsId = ref<number>(0);

  const form = reactive<Docs>({
    docsId: 0,
    title: '',
    content: '',
    bookId: undefined,
    code: '',
    parentId: undefined,
    parentName: '',
    createTime: '',
    updateTime: ''
  });

  const editorRef = ref<InstanceType<typeof TinymceEditor> | null>(null);
  const config = ref({
    height: 520,
    images_upload_handler: (blobInfo, success, error) => {
      const file = blobInfo.blob();
      const formData = new FormData();
      formData.append('file', file, file.name);
      uploadOss(file)
        .then((res) => {
          success(res.url);
        })
        .catch((msg) => {
          error(msg);
        });
      return false;
    },
    // 自定义文件上传(这里使用把选择的文件转成 blob 演示)
    file_picker_callback: (callback: any, _value: any, meta: any) => {
      const input = document.createElement('input');
      input.setAttribute('type', 'file');
      // 设定文件可选类型
      if (meta.filetype === 'image') {
        input.setAttribute('accept', 'image/*');
      } else if (meta.filetype === 'media') {
        input.setAttribute('accept', 'video/*,.pdf');
      }
      input.onchange = () => {
        const file = input.files?.[0];
        if (!file) {
          return;
        }
        if (meta.filetype === 'media') {
          if (file.size / 1024 / 1024 > 200) {
            editorRef.value?.alert({ content: '大小不能超过 200MB' });
            return;
          }
          if (!file.type.startsWith('video/')) {
            editorRef.value?.alert({ content: '只能选择视频文件' });
            return;
          }
          uploadOss(file).then((res) => {
            callback(res.url);
          });
        }
      };
      input.click();
    }
  });

  const { resetFields } = useForm(form);
  /* 搜索 */
  const reload = () => {
    resetFields();
    content.value = '';
    getDocs(docsId.value)
      .then((data) => {
        assignObject(form, data);
        if (data.content) {
          content.value = String(form.content);
        }
        emit('echo', form);
        isUpdate.value = true;
      })
      .catch(() => {
        loading.value = false;
        isUpdate.value = false;
      });
  };

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

  // 监听文档 id 变化
  watch(
    currentRoute,
    (route) => {
      const { query } = unref(route);
      const id = Number(query.id);
      if (id > 0) {
        docsId.value = id;
        reload();
      }
    },
    { immediate: true }
  );
</script>
