import { useCtx } from "@/pages/website/context";
import { css } from "@linaria/core";

import { message, Spin } from "ant-design-vue";
import { List, View } from "queenjs/ui";
import { defineComponent, onMounted, reactive, ref } from "vue";
import { array, number, string } from "vue-types";

import Quill from "quill";
export default defineComponent({
  props: {
    value: string().def(""),
  },
  emits: ["change"],
  setup(props, { emit }) {
    const ctx = useCtx();

    let quill = null;
    onMounted(() => {
      initQuillEditor();
    });
    const initQuillEditor = () => {
      quill = new Quill("#editor", {
        theme: "snow",
        placeholder: "请在这里输入文物简介",
        modules: {
          toolbar: [
            ["bold", "italic", "underline"], //加粗，斜体，下划线，删除线
            [{ indent: "-1" }, { indent: "+1" }], // 缩进
            [{ align: [] }], //对齐方式
            [{ header: [1, 2, false] }], //几级标题
            ["clean"], //清除字体样式
            ["image"], //上传图片
          ],
        },
      });
      if (props.value) {
        let delta = JSON.parse(props.value);
        quill.setContents(delta);
        quill.update();
      }
      var toolbar = quill.getModule("toolbar");
      toolbar.addHandler("image", showImage);
      quill.on("text-change", () => {
        let content = quill.getContents();
        if (content) {
          emit("change", JSON.stringify(content));
        }
      });
    };
    const showImage = async () => {
      let res = await selectFile();
      if (res) {
        var range = quill.getSelection();
        if (range) {
          quill.insertEmbed(range.index, "image", res);
          quill.setSelection(range.index + 1);
          quill.update();
        }
      }
    };
    const selectFile = async () => {
      const exts = ["png", "jpg"];
      const maxSize = 1024 * 1024 * 20;
      const files = await ctx.list.uploader.selectAnyFile(false, "image/*");
      if (files.length < 1) return { error: "没有选中图片" };
      const oneFile = files[0];

      if (exts.indexOf(oneFile.ext) < 0) {
        message.warn("不支持的文件各式！");
        return false;
      }
      if (oneFile.file.size > maxSize) {
        message.warn("图片大小超出限制！");
        return false;
      }
      let res = await ctx.list.uploader.uploadFile2Server(oneFile.file);
      if (res?.url) {
        return res?.url;
      } else {
        message.warn("上传失败");
        return false;
      }
    };
    return () => {
      return <div id="editor"></div>;
    };
  },
});

const rootStyle = css``;
