<!-- 用户编辑弹窗 -->
<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 } }"
    >
      <!-- 编辑器 -->
      <div class="content">
        <!-- 编辑器 -->
        <MdEditor v-model="content" @paste="onPaste" placeholder="用于显示插件市场上的介绍（机密信息勿填），图片请直接粘贴" />
      </div>
      <!-- 编辑器 -->
<!--      <byte-md-editor-->
<!--          v-model:value="content"-->
<!--          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 { 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, uploadOss} 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 token = localStorage.getItem(TOKEN_STORE_NAME);
  const formRef = ref<FormInstance | null>(null);


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

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

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

  /* 粘贴图片上传服务器并插入编辑器 */
  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 = `<p><img class="content-img" src="${result.url}"></p>`;
            content.value = content.value + addPath
            // 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
        };
        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 = '';
        if (props.data) {
          assignObject(form, props.data);
          if (props.data.content) {
            content.value = props.data.content;
          }
          isUpdate.value = true;
        } else {
          isUpdate.value = false;
        }
      } else {
        resetFields();
      }
    }
  );
</script>
