import {
  EditorState, convertFromRaw, convertToRaw, CompositeDecorator,
} from 'draft-js';
import { message } from 'antd'
import { stateToHTML } from 'draft-js-export-html';

import moment from 'moment';
function findLinkEntities(contentBlock, callback, contentState) {
  contentBlock.findEntityRanges(
    (character) => {
      const entityKey = character.getEntity();
      return (
        entityKey !== null &&
        contentState.getEntity(entityKey).getType() === 'LINK'
      );
    },
    function () {
      console.log(arguments);
      callback(...arguments);
    }

  );
}

const Link = (props) => {

  const { url } = props.contentState.getEntity(props.entityKey).getData();

  return (
    <a href={url} target="_blank">
      {props.children}
    </a>
  );
};

const decorator = new CompositeDecorator([
  {
    strategy: findLinkEntities,
    component: Link
  }
]);
export function changeHtml(msg) {
  var msg = msg.replace(/<\/?[^>]*>/g, ''); //去除HTML Tag
  msg = msg.replace(/[|]*\n/, '') //去除行尾空格
  msg = msg.replace(/&npsp;/ig, ''); //去掉npsp
  return msg;
}
export function changeToDraftState(blocks) {

  if (blocks == null || blocks == "") {
    return EditorState.createEmpty(decorator)
  }
  let x;
  try{
     x = JSON.parse(blocks)
  }catch(e){
    return EditorState.createEmpty(decorator)
  }
  if(!x.blocks){
    return EditorState.createEmpty(decorator)
    
  }
  

  const b = convertFromRaw(x);
  return EditorState.createWithContent(b, decorator)
}
export function changeFromDraftState(editorState) {
  const x = editorState.getCurrentContent()
  const blocks = JSON.stringify(convertToRaw(x))
  const content = stateToHTML(x)

  return { content, blocks }
}
export function changeToDraftState2(blocks) {


  const b = convertFromRaw(blocks);
  return EditorState.createWithContent(b, decorator)
}
export function changeFromDraftState2(editorState) {
  const x = editorState.getCurrentContent()
  const blocks = convertToRaw(x)

  return blocks
}
export function preHandle(values) {

  for (var key in values) {

    if(!values[key]) continue;
    if (key.indexOf("img") > -1) {

      var xx = key.split("$")

        values[xx[1]] = values[key].response


      delete values[key]
    } else if (key.indexOf("$") > -1) {
      var xx = key.split("$")
      for (var i = 0; i < xx.length; i++) {

        if (values[key][i] instanceof moment) {
          values[xx[i]] = values[key][i].valueOf()
        } else {
          values[xx[i]] = values[key][i]
        }
      }
      delete values[key]
    } else {

      if (values[key] != null) {
        if (values[key] instanceof moment) {
          values[key] = values[key].valueOf()
        }else if (values[key] instanceof Date) {
          values[key] = values[key].valueOf()
        } else if (values[key] instanceof Boolean) {
          values[key] = values[key] ? 0 : 1
        }
      }
    }

  }

}