<template>
  <ele-modal
    width="70%"
    :visible="visible"
    :title="`编辑记录`"
    :body-style="{ paddingBottom: '28px' }"
    @update:visible="updateVisible"
    @ok="save"
  >
    <!-- 编辑器 -->
    <byte-md-editor
      v-model:value="form.content"
      placeholder="请输入您的回复内容，图片请直接粘贴"
      :locale="zh_Hans"
      :plugins="plugins"
      mode="tab"
      height="300px"
      maxLength="500"
      :editorConfig="{ lineNumbers: true }"
      contenteditable="true"
      @paste="onPaste"
    />
    <a-space class="files">
      <a-upload
        v-model:file-list="fileList"
        class="upload-list-inline"
        list-type="picture"
        :before-upload="onBeforeUpload"
      >
        <a-button>
          <UploadOutlined />
          上传附件
        </a-button>
      </a-upload>
    </a-space>
  </ele-modal>
</template>
<script lang="ts" setup>
  import { ref, watch } from 'vue';
  import useFormData from '@/utils/use-form-data';
  import { message } from 'ant-design-vue';
  import { TaskRecord } from '@/api/oa/task-record/model';
  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';
  import highlight from '@bytemd/plugin-highlight-ssr';
  import { updateTaskRecord } from '@/api/oa/task-record';
  import { ItemType } from "ele-admin-pro/es/ele-image-upload/types";
  import { uploadOss } from "@/api/system/file";
  import { getVersion, isImage } from "@/utils/common";
  import { useUserStore } from "@/store/modules/user";

  const props = defineProps<{
    // 弹窗是否打开
    visible: boolean;
    data: TaskRecord;
  }>();

  const emit = defineEmits<{
    (e: 'done'): void;
    (e: 'update:visible', visible: boolean): void;
  }>();

  /* 更新visible */
  const updateVisible = (value: boolean) => {
    emit('update:visible', value);
  };

  const user = useUserStore();
  const content = ref('');
  const files = ref<any[]>([]);
  const fileList = ref<any[]>([]);
  const version = ref<number>(0);

  // 应用信息
  const { form, resetFields, assignFields } = useFormData<TaskRecord>({
    appId: 0,
    avatar: '',
    children: [],
    comments: '',
    createTime: '',
    developerId: 0,
    nickname: '',
    parentId: 0,
    sortNumber: 0,
    status: '',
    taskRecordId: 0,
    toUser: null,
    userId: 0,
    taskId: undefined,
    content: '',
    files: ''
  });

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

  /* 粘贴图片上传服务器并插入编辑器 */
  const onPaste = (e) => {
    const items = (e.clipboardData || e.originalEvent.clipboardData).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
        };
        uploadOss(<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 onBeforeUpload = (file: File) => {
    const item: ItemType = {
      file,
      uid: (file as any).uid,
      name: file.name
    }
    if (!file.type.startsWith("image")) {
      if (file.size / 1024 / 1024 > 100) {
        message.error("大小不能超过 100MB");
        return;
      }
    }
    onUpload(item);
    return false;
  };

  const onUpload = (d: ItemType) => {
    uploadOss(<File>d.file)
      .then((result) => {
        files.value.push({
          uid: result.id,
          url: result.path,
          name: isImage(result.path) ? 'image' : result.name,
          status: "done"
        });
        fileList.value = files.value;
        message.success("上传成功");
      })
      .catch((e) => {
        message.error(e.message);
      });
  };

  const save = () => {
    const { taskRecordId, content, files } = form;
    updateTaskRecord({ toUser: null, taskRecordId, content, files: JSON.stringify(fileList.value) }).then((msg) => {
      fileList.value = [];
      message.success(msg);
      updateVisible(false);
      emit('done');
    });
  };

  watch(
    () => props.visible,
    (visible) => {
      if (visible) {
        if (props.data) {
          assignFields(props.data);
          if (props.data?.files) {
            fileList.value = JSON.parse(props.data?.files);
            files.value = JSON.parse(props.data?.files);
          }
          version.value = <number>getVersion();
        }
      } else {
        resetFields();
      }
    }
  );
</script>
<style scoped lang="less">
  .upload-image {
    margin-bottom: 30px;
    display: flex;
    justify-content: center;
  }
  .files{
    margin-top: 10px;
  }
</style>
