<!-- 用户编辑弹窗 -->
<template>
  <ele-modal
    width="80%"
    :visible="visible"
    :maskClosable="false"
    :maxable="maxable"
    :title="isUpdate ? '协同文档' : '协同文档'"
    :body-style="{ paddingBottom: '28px' }"
    @update:visible="updateVisible"
    @ok="save"
  >
    <a-form
        ref="formRef"
        :model="form"
        :label-col="{ md: { span: 7 }, sm: { span: 4 }, xs: { span: 24 } }"
        :wrapper-col="{ md: { span: 17 }, sm: { span: 20 }, xs: { span: 24 } }"
    >
      <!-- 编辑器 -->
      <MdEditor v-model="requirement" @paste="onPaste" placeholder="类似腾讯文档的功能，支持多人编辑" />
    </a-form>
  </ele-modal>
</template>

<script lang="ts" setup>
  import { ref, reactive, watch } from 'vue';
  import { Form, message } from 'ant-design-vue';
  import {assignObject} from "ele-admin-pro";
  import { addProject, updateProject } from '@/api/project/project';
  import type { Project } from '@/api/project/project/model';
  import { useThemeStore } from '@/store/modules/theme';
  import { storeToRefs } from 'pinia';
  import {MdEditor} from 'md-editor-v3';
  import 'md-editor-v3/lib/style.css';
  import 'md-editor-v3/lib/preview.css';
  import {FormInstance} from 'ant-design-vue/es/form';
  import { ItemType } from 'ele-admin-pro/es/ele-image-upload/types';
  import { uploadFile } from "@/api/system/file";
  import { TOKEN_STORE_NAME } from "@/config/setting";


  // 是否是修改
  const isUpdate = ref(false);
  const useForm = Form.useForm;
  // 是否开启响应式布局
  const themeStore = useThemeStore();
  const { styleResponsive } = storeToRefs(themeStore);

  const props = defineProps<{
    // 弹窗是否打开
    visible: boolean;
    // 修改回显的数据
    data?: Project | null;
  }>();

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

  // 提交状态
  const loading = ref(false);
  // 是否显示最大化切换按钮
  const maxable = ref(true);
  const images = ref<ItemType[]>([]);
  const content = ref('');
  const requirement = ref('');

  const token = localStorage.getItem(TOKEN_STORE_NAME);
  const formRef = ref<FormInstance | null>(null);


  // 用户信息
  const form = reactive<Project>({
    // 应用id
    appId: undefined,
    // 项目需求
    requirement: ''
  });

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

  const { resetFields, validate, validateInfos } = useForm(form);

  const config = ref({
    height: 500,
    images_upload_handler: (blobInfo, success, error) => {
      const file = blobInfo.blob();
      // 使用 axios 上传，实际开发这段建议写在 api 中再调用 api
      const formData = new FormData();
      formData.append('file', file, file.name);
      uploadFile(<File>file)
        .then((result) => {
          if (result.length) {
            if (file.size / 1024 / 1024 > 2) {
              error('图片大小不能超过 2MB');
            }
            success(result.url);
          } else {
            error('上传失败');
          }
        })
        .catch((e) => {
          message.error(e.message);
        });
    },
  });

  /* 粘贴图片上传服务器并插入编辑器 */
  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
        };
        uploadFile(<File>item.file)
          .then((result) => {
            const addPath = '!['+result.name+']('+ result.url+')\n\r';
            requirement.value = requirement.value + addPath
          })
          .catch((e) => {
            message.error(e.message);
          });
        hasFile = true;
      }
    }
    if (hasFile) {
      e.preventDefault();
    }
  }

  /* 保存编辑 */
  const save = () => {
    if (!formRef.value) {
      return;
    }
    formRef.value
      .validate()
      .then(() => {
        loading.value = true;
        const formData = {
          ...form,
          content: content.value,
          requirement: requirement.value,
          images: JSON.stringify(images.value)
        };
        const saveOrUpdate = isUpdate.value ? updateProject : addProject;
        saveOrUpdate(formData)
          .then((msg) => {
            loading.value = false;
            message.success(msg);
            updateVisible(false);
            emit('done');
          })
          .catch((e) => {
            loading.value = false;
            message.error(e.message);
          });
      })
      .catch(() => {});
  };

  /* 上传事件 */
  const uploadHandler = (file: File) => {
    const item: ItemType = {
      file,
      uid: (file as any).uid,
      name: file.name
    };
    if (!file.type.startsWith('image')) {
      message.error('只能选择图片');
      return;
    }
    if (file.size / 1024 / 1024 > 2) {
      message.error('大小不能超过 2MB');
      return;
    }
    onUpload(item);
  };

  // 上传文件
  const onUpload = (item) => {
    const { file } = item;
    uploadFile(file)
      .then((data) => {
        images.value.push({
          uid: data.id,
          url: data.url,
          status: 'done'
        });
      })
      .catch((e) => {
        message.error(e.message);
      });
  };

  watch(
    () => props.visible,
    (visible) => {
      if (visible) {
        content.value = '';
        requirement.value = '';
        if (props.data) {
          assignObject(form, props.data);
          if (props.data.requirement){
            requirement.value = props.data.requirement;
          }
          if (props.data.content) {
            content.value = props.data.content;
          }
          isUpdate.value = true;
        } else {
          isUpdate.value = false;
        }
      } else {
        resetFields();
      }
    }
  );
</script>
