import './sass/editor.scss';
import Vditor from './lib/vditor/index.min';
import './lib/vditor/index.classic.css';
import emojiSet from './data/emoji.json';
let saveSvg = `<svg width="32px" height="32px" viewBox="0 0 32 32" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> <g id="Page-1" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd"> <g id="save" fill-rule="nonzero" fill="#000000"> <path d="M24.2,11.1461538 L22.8461538,9.75384615 C22.7923077,9.69230769 22.7076923,9.66153846 22.6307692,9.66153846 C22.5461538,9.66153846 22.4692308,9.69230769 22.4153846,9.75384615 L13.0307692,19.2076923 L9.61538462,15.7923077 C9.55384615,15.7307692 9.47692308,15.7 9.4,15.7 C9.32307692,15.7 9.24615385,15.7307692 9.18461538,15.7923077 L7.81538462,17.1615385 C7.69230769,17.2846154 7.69230769,17.4769231 7.81538462,17.6 L12.1230769,21.9076923 C12.4,22.1846154 12.7384615,22.3461538 13.0230769,22.3461538 C13.4307692,22.3461538 13.7846154,22.0461538 13.9153846,21.9230769 L13.9230769,21.9230769 L24.2076923,11.5846154 C24.3153846,11.4538462 24.3153846,11.2615385 24.2,11.1461538 L24.2,11.1461538 Z" id="Shape"></path> <path d="M16,2.15384615 C19.7,2.15384615 23.1769231,3.59230769 25.7923077,6.20769231 C28.4076923,8.82307692 29.8461538,12.3 29.8461538,16 C29.8461538,19.7 28.4076923,23.1769231 25.7923077,25.7923077 C23.1769231,28.4076923 19.7,29.8461538 16,29.8461538 C12.3,29.8461538 8.82307692,28.4076923 6.20769231,25.7923077 C3.59230769,23.1769231 2.15384615,19.7 2.15384615,16 C2.15384615,12.3 3.59230769,8.82307692 6.20769231,6.20769231 C8.82307692,3.59230769 12.3,2.15384615 16,2.15384615 L16,2.15384615 Z M16,0 C7.16153846,0 0,7.16153846 0,16 C0,24.8384615 7.16153846,32 16,32 C24.8384615,32 32,24.8384615 32,16 C32,7.16153846 24.8384615,0 16,0 Z" id="Shape"></path> </g> </g> </svg>`;
let saveUrl = "https://api.ourfor.top/blog/writes/content";

let emojis = {};
let emojiPath = `${pkg.cdn}/catalina@${pkg.version}/dist/emoji`;
_.each(emojiSet,(v,k) => {
  emojis[k] = `${emojiPath}/${v}`;
})

const LazyLoadImage = () => {
  const loadImg = (it) => {
    const testImage = document.createElement('img')
    testImage.src = it.getAttribute('data-src')
    testImage.addEventListener('load', () => {
      it.src = testImage.src
      it.style.backgroundImage = 'none'
      it.style.backgroundColor = 'transparent'
    })
    it.removeAttribute('data-src')
  }

  if (!('IntersectionObserver' in window)) {
    document.querySelectorAll('img').forEach((data) => {
      if (data.getAttribute('data-src')) {
        loadImg(data)
      }
    })
    return false
  }

  if (window.imageIntersectionObserver) {
    window.imageIntersectionObserver.disconnect()
    document.querySelectorAll('img').forEach(function (data) {
      window.imageIntersectionObserver.observe(data)
    })
  } else {
    window.imageIntersectionObserver = new IntersectionObserver((entries) => {
      entries.forEach((entrie) => {
        if ((typeof entrie.isIntersecting === 'undefined'
          ? entrie.intersectionRatio !== 0
          : entrie.isIntersecting) && entrie.target.getAttribute('data-src')) {
          loadImg(entrie.target)
        }
      })
    })
    document.querySelectorAll('img').forEach(function (data) {
      window.imageIntersectionObserver.observe(data)
    })
  }
}

let handleSave = (vditor)=>{
    let md = vditor.editor.element.innerText;
    let preview = vditor.preview.element;
    let html = preview.querySelector(".vditor-reset").innerHTML;
    let counter = vditor.counter.element;
    let count = counter.innerText.split("/")[0];
    let dataId = document.querySelector("div.title>div[data-id]").getAttribute('data-id');
    let articleId = new Number(dataId);
    let data = {md,html,articleId,count};
    $.ajax({
      url: saveUrl,
      method: 'put',
      contentType: 'application/json',
      data: JSON.stringify(data),
      dataType: 'json',
      success: data=>{
        if(data.msg=='ok') vditor.tip.show("保存成功 🍓🍒🍈🍇🍉🍅");
        else vditor.tip.show("保存失败 😁😆😆😆😂");
      }
    });
};

let config = {
  counter: 100,
  height: 700,
  width: 1200,
  editorName: 'vditor',
  hint: {
    emojiPath: 'https://cdn.jsdelivr.net/npm/vditor@1.8.3/dist/images/emoji',
    emojiTail: '<a href="https://hacpai.com/settings/function" target="_blank">设置常用表情</a>',
    emoji: {
      '+1': '👍',
      '-1': '👎',
      'egg': '🥚',
      'eggplant': '🍆',
      'eight': '8⃣',
      'eight_pointed_black_star': '✴',
      'eight_spoked_asterisk': '✳',
      'electric_plug': '🔌',
      'elephant': '🐘',
      'email': '✉',
      'end': '🔚',
      'envelope': '✉',
      'es': '🇪🇸',
      'euro': '💶',
      'european_castle': '🏰',
      'european_post_office': '🏤',
      'evergreen_tree': '🌲',
      'exclamation': '❗',
      'expressionless': '😑',
      'eyeglasses': '👓',
      'eyes': '👀',
      'facepunch': '👊',
      'factory': '🏭',
      'fallen_leaf': '🍂',
      'family': '👪',
      'fast_forward': '⏩',
      'fax': '📠',
      'fearful': '😨',
      'feet': '🐾',
      'ferris_wheel': '🎡',
      'file_folder': '📁',
      'fire': '🔥',
      'fire_engine': '🚒',
      'fireworks': '🎆',
      'first_quarter_moon': '🌓',
      'first_quarter_moon_with_face': '🌛',
      'fish': '🐟',
      'fish_cake': '🍥',
      'fishing_pole_and_fish': '🎣',
      'fist': '✊',
      'five': '5⃣',
      'flags': '🎏',
      'flashlight': '🔦',
      'floppy_disk': '💾',
      'flower_playing_cards': '🎴',
      'flushed': '😳',
      'foggy': '🌁',
      'football': '🏈',
      'fork_and_knife': '🍴',
      'fountain': '⛲',
      'four': '4⃣',
      'four_leaf_clover': '🍀',
      'fr': '🇫🇷',
      'free': '🆓',
      'fried_shrimp': '🍤',
      'fries': '🍟',
      'frog': '🐸',
      'frowning': '😦',
      'fuelpump': '⛽',
      'full_moon': '🌕',
      'full_moon_with_face': '🌝',
      'trollface': 'https://unpkg.com/vditor@1.3.1/dist/images/emoji/trollface.png',
      'huaji': 'https://unpkg.com/vditor@1.3.1/dist/images/emoji/huaji.gif',
      ...emojis,
    },

  },
  tab: '\t',
  preview: {
    mode: 'both',
    parse: () => {
      LazyLoadImage()
    },
  },
  toolbar: [{
        hotkey: "⌘-e",
        name: "emoji",
        tipPosition: "ne",
    }, {
        hotkey: "⌘-h",
        name: "headings",
        tipPosition: "ne",
    }, {
        hotkey: "⌘-b",
        name: "bold",
        prefix: "**",
        suffix: "**",
        tipPosition: "ne",
    }, {
        hotkey: "⌘-i",
        name: "italic",
        prefix: "*",
        suffix: "*",
        tipPosition: "ne",
    }, {
        hotkey: "⌘-s",
        name: "strike",
        prefix: "~~",
        suffix: "~~",
        tipPosition: "ne",
    }, {
        name: "|",
    }, {
        hotkey: "⌘-⇧-d",
        name: "line",
        prefix: "---",
        tipPosition: "n",
    }, {
        hotkey: "⌘-.",
        name: "quote",
        prefix: "> ",
        tipPosition: "n",
    }, {
        name: "|",
    }, {
        hotkey: "⌘-l",
        name: "list",
        prefix: "* ",
        tipPosition: "n",
    }, {
        hotkey: "⌘-o",
        name: "ordered-list",
        prefix: "1. ",
        tipPosition: "n",
    }, {
        hotkey: "⌘-j",
        name: "check",
        prefix: "* [ ] ",
        tipPosition: "n",
    }, {
        name: "|",
    }, {
        hotkey: "⌘-u",
        name: "code",
        prefix: "```\n",
        suffix: "\n```",
        tipPosition: "n",
    }, {
        hotkey: "⌘-g",
        name: "inline-code",
        prefix: "`",
        suffix: "`",
        tipPosition: "n",
    }, {
        name: "|",
    }, {
        hotkey: "⌘-z",
        name: "undo",
        tipPosition: "n",
    }, {
        hotkey: "⌘-y",
        name: "redo",
        tipPosition: "n",
    }, {
        name: "|",
    }, {
        name: "upload",
        tipPosition: "n",
    }, {
        hotkey: "⌘-k",
        name: "link",
        prefix: "[",
        suffix: "](https://)",
        tipPosition: "n",
    }, {
        hotkey: "⌘-m",
        name: "table",
        prefix: "| col1",
        suffix: " | col2 | col3 |\n| --- | --- | --- |\n|  |  |  |\n|  |  |  |",
        tipPosition: "n",
    }, {
        name: "record",
        tipPosition: "n",
    }, {
        name: "|",
    }, {
        hotkey: "⌘-p",
        name: "both",
        tipPosition: "nw",
    }, {
        hotkey: "⌘-⇧-p",
        name: "preview",
        tipPosition: "nw",
    }, {
        hotkey: "⌘-'",
        name: "fullscreen",
        tipPosition: "nw",
    }, {
      name: 'format',
      tipPosition: 'nw'
    }, {
      name: 'wysiwyg',
      tipPosition: 'ne',
    }, {
      name: 'both',
      tipPosition: 'ne',
    },
    'strike',
    'devtools',
    {
       name: "save",
       tipPosition: "nw",
       class: "save",
       icon: saveSvg,
       tip: "保存文章",
       url: "hahah",
       click: handleSave,
    }, {
        name: "title",
        tipPosition: "nw",
        class: "title",
        icon: "",
        id: "1",
        tip: "文章标题",
    }, {
        name: "br",
    }],
    resize: {
      enable: true,
      position: 'top',
      after: height => {
        console.log(`after resize, height change: ${height}`)
      },
    },
    upload: {
      accept: 'image/*,.pdf,.war,.java,.kt,.js,.zip',
      token: 'Have a good time',
      url: "http://localhost:8080/upload",
      linkToImgUrl: '/api/upload/fetch',
      filename: name => {
        // ? \ / : | < > * [ ] white to -
        return name.replace(/\?|\\|\/|:|\||<|>|\*|\[|\]|\s+/g, '-')
      },
      // handler (file) {
      //   console.log(file)
      //   return 'handler'
      // },
      save(){
        let title = document.querySelector('div.title>div')
        return title.innerText;
      }
    },
};

let link = document.location.href;
link = "http://blog.ourfor.com/post/Spring+RESTful%E9%87%8D%E6%9E%84%E5%8D%9A%E5%AE%A2";
let index = config.toolbar.length
let uri = decodeURI(link)
// let content = "https://api.ourfor.top/blog/writes/content";
let content = `${$conf.api.base}/${$conf.api.path.write.editBuff}`;
// config.upload.url = "https://api.ourfor.top/blog/upload";
config.upload.url = `${$conf.api.base}/${$conf.api.path.upload}`;
config.cache = false;


class Editor extends Component {
    constructor(props){
        super(props);
        this.state = {
          title: 0,
          artilceId: '',
        };
    }
    componentWillMount(){
      $.get(content,data=>{
        config.toolbar[index-2].icon = data.title;
        config.toolbar[index-2].id = data.articleId;
        this.setState({
          title: data.title,
          artilceId: data.artilceId,
          data
        });
        let vditor = new Vditor('vditor', config);
        setTimeout(()=>{
          $('.vditor-textarea').text(data.md)
          $('.vditor-textarea + .vditor-preview>div').html(data.html)
        },1000);
      },'json');
    }
    componentDidMount(){
    }
    componentDidUpdate(){
    }
    render(){
        return <div id="vditor"></div>
    }
}

export default Editor;
