import {CDN_IMG_URL} from './config'
import network from "./network";
import tool from "./tool";

const EDITOR_ROOT_URL = `${CDN_IMG_URL}/tinymce`
const EDITOR_LANGUAGE = `${EDITOR_ROOT_URL}/langs/zh_CN.js`

let fullEditor = {
  // language_url: EDITOR_LANGUAGE,
  height: 500,
  plugins: 'print preview searchreplace autolink directionality visualblocks visualchars fullscreen link template codesample table charmap hr pagebreak nonbreaking anchor toc insertdatetime advlist lists textcolor wordcount imagetools contextmenu colorpicker textpattern help',
  toolbar1: 'formatselect | bold italic strikethrough forecolor backcolor | link | alignleft aligncenter alignright alignjustify  | numlist bullist outdent indent  | removeformat',
}

let textEditor = {
  // language_url: EDITOR_LANGUAGE,
  height: 500,
  menubar: false,
  plugins: [
    'advlist autolink lists link charmap print preview anchor textcolor colorpicker',
    'searchreplace visualblocks code fullscreen',
    'insertdatetime media table contextmenu paste image code help'
  ],
  toolbar: 'undo redo |  formatselect | bold italic backcolor forecolor | link image | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | removeformat | preview | help',
  automatic_uploads: false,
  image_title: false,
  image_description: false,
  images_upload_base_path: 'article',
  file_picker_types: 'file image media',
  images_upload_handler: (blobInfo, success, failure) => {
      const handler = async () => {
          let token = await network.getData('file/token');

          let params = new FormData()
          params.append('file', blobInfo.blob())
          params.append('uploadToken', token)
          await network.postData('ad/upload', params).then(response => {
              let imageUrl = tool.getArImage(response, '/files/');
              success(imageUrl)
          }).catch(error => {
              failure(error)
          })
      }

      handler();
  },
  file_picker_callback: (callback, value, meta) => {
      // 模拟出一个input用于添加本地文件
      let inputElem = document.createElement('input');
      inputElem.setAttribute('type', 'file');
      inputElem.click();
      inputElem.onchange = () => {
          const handler = async () => {
              let token = await network.getData('file/token');
              let file = inputElem.files[0];

              let params = new FormData()
              params.append('file', file);
              params.append('uploadToken', token);
              await network.postData('article/upload', params).then(response => {
                  let fileUrl = tool.getArImage(response, '/files/');
                  callback(fileUrl, {text: response})
              }).catch(error => {
                  console.log(error)
              })
          }

          handler();
      }
  },
}

export {
  fullEditor,
  textEditor,
  EDITOR_ROOT_URL
}
