import { EditorState, convertFromRaw, convertToRaw, CompositeDecorator } from 'draft-js';
import { stateToHTML } from 'draft-js-export-html';
import moment from 'moment';
import React from 'react';

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;/gi, ''); //去掉npsp
  return msg;
}

export function changeToDraftState(blocks) {
  if (blocks == null || blocks == '') {
    return EditorState.createEmpty(decorator);
  }
  let x;
  if (typeof blocks === 'string' && blocks) {
    try {
      x = JSON.parse(blocks);
    } catch (e) {
      return EditorState.createEmpty(decorator);
    }
  } else {
    x = blocks;
  }

  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) {
  if (editorState == null) return;
  const x = editorState.getCurrentContent();
  const blocks = convertToRaw(x);

  return blocks;
}

export function preHandle(values) {
  // console.trace('123');
  for (var key in values) {
    if (!values[key]) continue;
    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;
        } else if (values[key] instanceof Object && key != 'defaultValues') {
          //处理子表单中的日期值
          let objValues = values[key];
          for (let k in objValues) {
            if (k != '' && objValues[k] instanceof Object) {
              let childObj = objValues[k];
              for (let j in childObj) {
                // 我写的代码
                if (j.indexOf('$') > -1 && Array.isArray(childObj[j]) && childObj[j].length === 2) {
                  j.split('$').map((g, index) => {
                    if (moment.isMoment(childObj[j][index])) {
                      childObj[g] = childObj[j][index].valueOf();
                    }
                  });
                  delete childObj[j];
                  // 我写的代码

                  // 欢哥写的代码.
                  // for (var i = 0; i < xxx.length; i++) {
                  // 	if (childObj[j][i] instanceof moment) {
                  // 		values[key][k][xxx[i]] = values[key][k][j][i].valueOf();
                  // 	} else {
                  // 		values[key][k][xxx[i]] = values[key][k][j][i];
                  // 	}
                  // }
                  //delete values[key][k][j];
                } else {
                  if (childObj[j] != null) {
                    if (childObj[j] instanceof moment) {
                      values[key][k][j] = values[key][k][j].valueOf();
                    } else if (childObj[j] instanceof Date) {
                      values[key][k][j] = values[key][k][j].valueOf();
                    } else if (childObj[j] instanceof Boolean) {
                      values[key][k][j] = values[key][k][j] ? 0 : 1;
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}

/**
 * 深拷贝函数 一站式使用
 * */
export function deepCopy(obj, parent = null) {
  if (React.isValidElement(obj)) {
    return React.cloneElement(obj);
  }
  // if(moment.isMoment(obj)){
  //   return moment().clone)
  // }
  if (['boolean', 'string', 'number'].indexOf(typeof obj) > -1 || !obj) {
    return obj;
  }
  let result;
  if (obj.constructor === Array) {
    result = [];
  } else {
    result = {};
  }
  let keys = Object.keys(obj),
    key = null,
    temp = null,
    _parent = parent;
  // 该字段有父级则需要追溯该字段的父级
  while (_parent) {
    // 如果该字段引用了它的父级则为循环引用
    if (_parent.originalParent === obj) {
      // 循环引用直接返回同级的新对象
      return _parent.currentParent;
    }
    _parent = _parent.parent;
  }
  for (let i = 0; i < keys.length; i++) {
    key = keys[i];
    temp = obj[key];
    if (temp && moment.isMoment(temp)) {
      result[key] = temp.clone();
    } else if (temp && typeof temp === 'object') {
      // 如果字段的值也是一个对象
      // 递归执行深拷贝 将同级的待拷贝对象与新对象传递给 parent 方便追溯循环引用
      result[key] = deepCopy(temp, {
        originalParent: obj,
        currentParent: result,
        parent: parent,
      });
    } else {
      result[key] = temp;
    }
  }
  return result;
}
