<!-- 用户编辑弹窗 -->
<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 } }"
    >
      <!-- 编辑器 -->
      <byte-md-editor
          v-model:value="requirement"
          placeholder="请输入您的内容，图片请直接粘贴"
          :locale="zh_Hans"
          mode="split"
          :plugins="plugins"
          height="500px"
          :editorConfig="{ lineNumbers: true }"
          @paste="onPaste"
      />
    </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 { addApp, updateApp } from '@/api/oa/app';
  import type { App } from '@/api/oa/app/model';
  import { useThemeStore } from '@/store/modules/theme';
  import { storeToRefs } from 'pinia';
  // 中文语言文件
  import zh_Hans from 'bytemd/locales/zh_Hans.json';
  // 链接、删除线、复选框、表格等的插件
  // 插件的中文语言文件
  import zh_HansGfm from '@bytemd/plugin-gfm/locales/zh_Hans.json';
  import 'bytemd/dist/index.min.css';
  import 'github-markdown-css/github-markdown-light.css';
  import highlight from '@bytemd/plugin-highlight';
  // 中文语言文件
  import gfm from '@bytemd/plugin-gfm';
  // // 预览界面的样式，这里用的 github 的 markdown 主题
  import 'github-markdown-css/github-markdown-light.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?: App | 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 plugins = ref([
    gfm({
      locale: zh_HansGfm
    }),
    highlight()
  ]);

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


  // 用户信息
  const form = reactive<App>({
    // 应用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) => {
    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 = () => {
    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 ? updateApp : addApp;
        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>
