import _defineProperty from "@babel/runtime/helpers/defineProperty";
import _toConsumableArray from "@babel/runtime/helpers/toConsumableArray";
import _objectSpread from "@babel/runtime/helpers/objectSpread2";
import _isArray from "lodash/isArray";
import _isBoolean from "lodash/isBoolean";
import _omit from "lodash/omit";
import _isPlainObject from "lodash/isPlainObject";
import _cloneDeep from "lodash/cloneDeep";

/*eslint-disable*/
import shortid from "shortid";
import invariant from "invariant";
import { set } from "dot-prop-immutable";
import styled from "styled-components";
import { i18n } from '@fishx/i18n';
import { getPlugin, getPlugins, plugins } from "../plugins";
import { getContent } from "./selectors";
import models from "../models/index";
export var idCharacters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_$';
export var excludeKeys = ["id", "path"];
export var characterShortId = function characterShortId(shortId) {
  shortId.characters(idCharacters);
};
characterShortId(shortid);
export var updateChildPaths = function updateChildPaths(element, eles) {
  if (!element.id) {
    element.id = shortid.generate();
  }

  if (!element.path) {
    element.path = "0";
  }

  if (eles && !eles[element.id]) {
    eles[element.id] = _objectSpread(_objectSpread({}, element), {}, {
      elements: []
    });
  }

  if (Array.isArray(element.elements)) {
    // Process children only if "elements" is an array of objects.
    // We may get an array of strings when working with shallow element copies.
    if (_isPlainObject(element.elements[0])) {
      element.elements.forEach(function (el, index) {
        if (!el.id) {
          el.id = shortid.generate();
        }

        el.path = element.path + "." + index;

        if (eles) {
          eles[element.id].elements.push(el.id);

          if (!eles[el.id]) {
            eles[el.id] = _objectSpread(_objectSpread({}, el), {}, {
              elements: []
            });
          }
        }

        if (el.elements && el.elements.length) {
          updateChildPaths(el, eles);
        }
      });
    }
  }
};
export var addElementToParent = function addElementToParent(element, parent, position) {
  var newParent;

  if (position === null || position === undefined) {
    newParent = set(parent, "elements", [].concat(_toConsumableArray(parent.elements), [element]));
  } else {
    newParent = set(parent, "elements", [].concat(_toConsumableArray(parent.elements.slice(0, position)), [element], _toConsumableArray(parent.elements.slice(position))));
  } // updateChildPaths(newParent);


  return newParent;
}; // 根据path路径添加元素

export var addElementByPath = function addElementByPath(element, parent, path) {
  if (path.length <= 0) {
    return parent;
  }

  var newParent;
  var pathArr = path.split(".");
  pathArr.splice(0, 1);
  pathArr.forEach(function (path, index) {
    var num = Number(path);

    if (index === pathArr.length - 1) {
      if (newParent) {
        if (!newParent.elements) {
          newParent.elements = [];
        }

        var _newParent = newParent,
            elements = _newParent.elements;
        elements.splice(num, 0, element);
      }
    } else {
      if (!newParent) {
        newParent = parent.elements[num];
      } else {
        newParent = newParent.elements[num];
      }
    }
  });
  return parent;
};
export var addNameForElement = function addNameForElement(element) {
  var _element$data, _element$data2, _element$data2$compon;

  var type = element.type;

  if (type === 'text') {
    return element;
  }

  var id = shortid.generate();
  var name = "".concat(type, "_").concat(id);

  if (element.type === 'form') {
    element.data.formSettings.name = name;
  } else if ((_element$data = element.data) !== null && _element$data !== void 0 && _element$data.formItemSettings && !element.data.formItemSettings.name) {
    element.data.formItemSettings.name = name;
  } else if (!((_element$data2 = element.data) !== null && _element$data2 !== void 0 && (_element$data2$compon = _element$data2.componentSettings) !== null && _element$data2$compon !== void 0 && _element$data2$compon.name)) {
    element.data.componentSettings.name = name;
  }

  return element;
};
export var createElement = function createElement(type) {
  var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  var parent = arguments.length > 2 ? arguments[2] : undefined;
  var plugin = getPlugins("pb-editor-page-element").find(function (pl) {
    return pl.elementType === type;
  });
  invariant(plugin, "Missing element plugin for type \"".concat(type, "\"!"));
  var id = shortid.generate();

  var ele = _cloneDeep(plugin.create(options, parent)); // 默认为元素添加name属性


  ele = addNameForElement(ele); // if (ele.data && ele.data.formSettings && !ele.data.formSettings.name) {
  //   ele.data.formSettings.name = `${type}_${id}`;
  // }

  return _objectSpread({
    id: id,
    data: {},
    elements: [],
    path: "",
    type: type
  }, ele);
};
export var getNameofElement = function getNameofElement(element) {
  var _element$data3, _element$data3$formSe, _element$data4, _element$data4$formIt, _element$data5, _element$data5$compon;

  if (!element) {
    return '';
  }

  if (element.name) {
    return element.name;
  }

  if ((_element$data3 = element.data) !== null && _element$data3 !== void 0 && (_element$data3$formSe = _element$data3.formSettings) !== null && _element$data3$formSe !== void 0 && _element$data3$formSe.name) {
    return element.data.formSettings.name;
  }

  if ((_element$data4 = element.data) !== null && _element$data4 !== void 0 && (_element$data4$formIt = _element$data4.formItemSettings) !== null && _element$data4$formIt !== void 0 && _element$data4$formIt.name) {
    return element.data.formItemSettings.name;
  }

  if ((_element$data5 = element.data) !== null && _element$data5 !== void 0 && (_element$data5$compon = _element$data5.componentSettings) !== null && _element$data5$compon !== void 0 && _element$data5$compon.name) {
    return element.data.componentSettings.name;
  }

  return element.type;
};
export var createBlock = function createBlock() {
  var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  var parent = arguments.length > 1 ? arguments[1] : undefined;
  return createElement("block", options, parent);
};
export var createForm = function createForm() {
  var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  var parent = arguments.length > 1 ? arguments[1] : undefined;
  return createElement("form", options, parent);
};
export var createRow = function createRow() {
  var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  var parent = arguments.length > 1 ? arguments[1] : undefined;
  return createElement("row", options, parent);
};
export var createColumn = function createColumn() {
  var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  var parent = arguments.length > 1 ? arguments[1] : undefined;
  return createElement("column", options, parent);
}; // 创建表格

export var createTable = function createTable() {
  var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  var parent = arguments.length > 1 ? arguments[1] : undefined;
  return createElement("table", options, parent);
};
export var createText = function createText() {
  var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  var parent = arguments.length > 1 ? arguments[1] : undefined;
  return createElement("text", options, parent);
}; // 创建表格头

export var createTableHeaderRow = function createTableHeaderRow() {
  var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  var parent = arguments.length > 1 ? arguments[1] : undefined;
  return createElement("headerRow", options, parent);
}; // 创建表格body单元格

export var createTableRowCell = function createTableRowCell() {
  var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  var parent = arguments.length > 1 ? arguments[1] : undefined;
  return createElement("rowCell", options, parent);
}; // 创建表格头部单元格

export var createTableHeaderCell = function createTableHeaderCell() {
  var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  var parent = arguments.length > 1 ? arguments[1] : undefined;
  return createElement("headerCell", options, parent);
}; // 创建面板，可用于折叠子面板

export var createCard = function createCard() {
  var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  var parent = arguments.length > 1 ? arguments[1] : undefined;
  return createElement("card", options, parent);
}; // 创建tab面板

export var createTabPane = function createTabPane() {
  var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  var parent = arguments.length > 1 ? arguments[1] : undefined;
  var block = createBlock({
    elements: [createRow({
      elements: [createColumn()]
    })]
  });
  return block;
}; // 创建expression表达式

export var createExpression = function createExpression() {
  var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  var parent = arguments.length > 1 ? arguments[1] : undefined;
  return createElement("expression", options, parent);
};
export var createBlockElements = function createBlockElements(name) {
  var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  var parent = arguments.length > 2 ? arguments[2] : undefined;
  var plugin = getPlugin(name);
  invariant(plugin, "Missing block plugin \"".concat(name, "\"!"));
  return _objectSpread({
    id: shortid.generate(),
    data: {},
    elements: [],
    path: ""
  }, plugin.create(options, parent));
};
export var createDocument = function createDocument() {
  return {
    id: shortid.generate(),
    data: {},
    elements: [],
    path: '0',
    type: 'document'
  };
};
export var cloneElement = function cloneElement(element, includes) {
  var excludes = [];

  if (includes && Array.isArray(includes) && includes.length > 0) {
    excludeKeys.map(function (v) {
      if (!includes.includes(v)) {
        excludeKeys.push(v);
      }
    });
  } else {
    excludes = excludeKeys;
  }

  var clone = _omit(element, excludes);

  clone.elements = clone.elements.map(function (el) {
    return cloneElement(el);
  });
  return clone;
}; // 将普通组件加入空容器内

export var addElementToEmptyContainer = function addElementToEmptyContainer(container, element) {
  var recursionFun = function recursionFun(con, ele) {
    var _con$elements = con.elements,
        elements = _con$elements === void 0 ? [] : _con$elements;

    if (con.type === 'column' && elements.length <= 0) {
      con.elements.push(ele);
      return;
    }

    elements.forEach(function (child) {
      recursionFun(child, ele);
    });
  };

  recursionFun(container, element);
  return container;
}; // 将布局组件加入空容器内

export var addLayoutElementToEmptyContainer = function addLayoutElementToEmptyContainer(container, element, elementType) {
  if (['row', 'column'].includes(elementType)) {
    return container;
  }

  var recursionFun = function recursionFun(con, ele) {
    if (['form', 'block'].includes(con.type)) {
      con.elements = [ele];
      return;
    }

    var _con$elements2 = con.elements,
        elements = _con$elements2 === void 0 ? [] : _con$elements2;
    elements.forEach(function (child) {
      recursionFun(child, ele);
    });
  };

  recursionFun(container, element);
  return container;
};
export var userSettingsPlugins = function userSettingsPlugins(elementType) {
  return plugins.byType("pb-editor-page-element-settings").filter(function (pl) {
    if (typeof pl.elements === "boolean") {
      return pl.elements === true;
    }

    if (Array.isArray(pl.elements)) {
      return pl.elements.includes(elementType);
    }

    return false;
  }).map(function (pl) {
    return pl.name;
  });
};
export var handleElementSetting = function handleElementSetting(element, data) {
  var _data$formSettings = data.formSettings,
      formSettings = _data$formSettings === void 0 ? {} : _data$formSettings,
      _data$formItemSetting = data.formItemSettings,
      formItemSettings = _data$formItemSetting === void 0 ? {} : _data$formItemSetting,
      _data$settings = data.settings,
      settings = _data$settings === void 0 ? {} : _data$settings;
  element.data.formSettings = _objectSpread(_objectSpread({}, element.data.formSettings), formSettings);
  element.data.formItemSettings = _objectSpread(_objectSpread({}, element.data.formItemSettings), formItemSettings);
  element.data.settings = _objectSpread(_objectSpread({}, element.data.settings), settings);
};
export var cssToJs = function cssToJs(css) {
  var re = /(-)(\w)/g;
  return css.replace(re, function ($0, $1, $2) {
    return $2.toUpperCase();
  });
};
export var toolFormAttr = {
  size: "small",
  labelCol: {
    span: 6
  },
  wrapperCol: {
    span: 18
  }
};
export var toolCollapseAttr = {
  bordered: false,
  expandIconPosition: 'right',
  className: 'formbuild-collapse'
};
export var defaultMenus = [{
  label: '1st menu item',
  value: '1'
}, {
  label: '2nd menu item',
  value: '2'
}, {
  label: '3rd menu item',
  value: '3'
}];
export var defaultList = [{
  label: 'Racing car sprays burning fuel into crowd.',
  value: 0
}, {
  label: 'Japanese princess to wed commoner.',
  value: 1
}, {
  label: 'Australian walks 100km after outback crash.',
  value: 2
}, {
  label: 'Man charged over missing wedding girl.',
  value: 3
}, {
  label: 'Los Angeles battles huge wildfires.',
  value: 4
}];
export var sortableList = [{
  text: 'Racing car sprays burning fuel into crowd.',
  id: 0
}, {
  text: 'Japanese princess to wed commoner.',
  id: 1
}, {
  text: 'Australian walks 100km after outback crash.',
  id: 2
}, {
  text: 'Man charged over missing wedding girl.',
  id: 3
}, {
  text: 'Los Angeles battles huge wildfires.',
  id: 4
}];
export var renderTypes = function renderTypes() {
  return [{
    label: i18n('PAGEBUILDER_ROWCELL_RENDERLIST_TEXT'),
    value: 'text'
  }, {
    label: i18n('PAGEBUILDER_ROWCELL_RENDERLIST_BUTTON'),
    value: 'button'
  }, {
    label: i18n('PAGEBUILDER_ROWCELL_RENDERLIST_ICON'),
    value: 'icon'
  }, {
    label: i18n('PAGEBUILDER_ROWCELL_RENDERLIST_LINK'),
    value: 'link'
  }, {
    label: i18n('PAGEBUILDER_ROWCELL_RENDERLIST_CHECKBOX'),
    value: 'checkbox'
  }, // { label: '标签', value: 'tag' },
  {
    label: i18n('PAGEBUILDER_ROWCELL_RENDERLIST_CUSTOM'),
    value: 'other'
  }];
};
export var buttonTypes = function buttonTypes() {
  return [{
    label: i18n('PAGEBUIDER_SETTINGS_BTN_TYPE_STYLE_DEFAULT'),
    value: null
  }, {
    label: i18n('PAGEBUIDER_SETTINGS_BTN_TYPE_STYLE_PRIMARY'),
    value: 'primary'
  }, {
    label: i18n('PAGEBUIDER_SETTINGS_BTN_TYPE_STYLE_DASHED'),
    value: 'dashed'
  }, {
    label: i18n('PAGEBUIDER_SETTINGS_BTN_TYPE_STYLE_DANGER'),
    value: 'danger'
  }, {
    label: i18n('PAGEBUIDER_SETTINGS_BTN_TYPE_STYLE_LINK'),
    value: 'link'
  }];
};
export var buttonSizes = function buttonSizes() {
  return [{
    label: i18n('PAGEBUIDER_SETTINGS_SMALL'),
    value: 'small'
  }, {
    label: i18n('PAGEBUIDER_SETTINGS_MIDDLE'),
    value: 'middle'
  }, {
    label: i18n('PAGEBUIDER_SETTINGS_LARGE'),
    value: 'large'
  }];
};
export var parseTableColumns = function parseTableColumns(tableElement) {
  var _tableElement$element = tableElement.elements,
      elements = _tableElement$element === void 0 ? [] : _tableElement$element;
  var columns = [];
  elements.forEach(function (element) {
    if (element.type === 'headerCell') {
      var componentSettings = element.data.componentSettings;
      columns.push(_objectSpread({}, componentSettings));
    }
  });
  return columns;
};
export var updateElements = function updateElements(state, element) {
  if (Array.isArray(element.elements)) {
    element.elements = element.elements.map(function (item) {
      if (typeof item === 'string') {
        var newItem = state.appBuilder.elements[item] || {};
        updateElements(state, newItem);
        return newItem;
      } else {
        return item;
      }
    });
  }
}; // 转换dependency relates,inputs字段

export var transformDependencyValues = function transformDependencyValues(allValues) {
  var values = {};

  if (!allValues.relates) {
    return null;
  }

  Object.keys(allValues).forEach(function (key) {
    if (key === 'relates') {
      values[key] = allValues[key].split(',');
    } else if (key === 'inputs') {
      var inputs = allValues[key];

      if (!_isBoolean(inputs)) {
        values[key] = inputs.split(',').map(function (v) {
          return [v];
        });
      } else {
        values[key] = [[inputs]];
      }
    } else {
      values[key] = allValues[key];
    }
  });
  return values;
};
export var isSingleBoolen = function isSingleBoolen(value) {
  if (_isArray(value)) {
    var inputs = value[0] && value[0][0];
    return _isBoolean(inputs);
  } else {
    return false;
  }
};
export var elementDefaultTargets = ["column", "row", "form"];
export var editorSettingKeyPrefix = 'pb-editor-page-element-settings';
export var getAllNamesFromForm = function getAllNamesFromForm(formInstance, element) {
  var names = [];

  if (formInstance) {
    var name = element.data.formSettings.name;
    var values = formInstance.getFieldsValue();
    Object.keys(values).forEach(function (key) {
      if (key !== name) {
        names.push(key);
      }
    });
  }

  return names;
};
export var registerFormBuilderModels = function registerFormBuilderModels() {
  models.forEach(function (model) {
    var targetModel = typeof model === 'function' ? model() : model;
    var load = window.g_app._models.findIndex(function (v) {
      return v.namespace === targetModel.namespace;
    }) > -1;

    if (!load) {
      window.g_app.model(targetModel);
    }
  });
};
export var resetFormBuilder = function resetFormBuilder() {
  var _window$g_app$_store$ = window.g_app._store.getState(),
      appBuilder = _window$g_app$_store$.appBuilder;

  if (appBuilder) {
    appBuilder.resetFlag = true;
  }
};
export var resetFormRender = function resetFormRender() {
  var nameSpace = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "appRender";

  window.g_app._store.dispatch({
    type: "".concat(nameSpace, "/reset")
  });
};
export var getContentElement = function getContentElement() {
  var state = window.g_app._store.getState();

  return getContent(state);
};
export var getEvents = function getEvents() {
  var _window$g_app$_store$2 = window.g_app._store.getState(),
      _window$g_app$_store$3 = _window$g_app$_store$2.appRender,
      appRender = _window$g_app$_store$3 === void 0 ? {} : _window$g_app$_store$3;

  return appRender.events;
};
export var PreviewBox = /*#__PURE__*/styled("div", {
  target: "e161nihc0",
  label: "PreviewBox"
})({
  textAlign: "center",
  height: 50,
  svg: {
    height: 50,
    width: 50
  }
}); // css decode

export var cssDecode = function cssDecode(code) {
  code = code.replace(/(\s){2,}/ig, '$1');
  code = code.replace(/(\S)\s*\{/ig, '$1 {');
  code = code.replace(/\*\/(.[^\}\{]*)}/ig, '\*\/\n$1}');
  code = code.replace(/\/\*/ig, '\n\/\*');
  code = code.replace(/;\s*(\S)/ig, ';\n\t$1');
  code = code.replace(/\}\s*(\S)/ig, '\}\n$1');
  code = code.replace(/\n\s*\}/ig, '\n\}');
  code = code.replace(/\{\s*(\S)/ig, '\{\n\t$1');
  code = code.replace(/(\S)\s*\*\//ig, '$1\*\/');
  code = code.replace(/\*\/\s*([^\}\{]\S)/ig, '\*\/\n\t$1');
  code = code.replace(/(\S)\}/ig, '$1\n\}');
  code = code.replace(/(\n){2,}/ig, '\n');
  code = code.replace(/:/ig, ':');
  code = code.replace(/ {2}/ig, ' ');
  return code;
}; // to source

var toSourceCode = function toSourceCode(flag) {
  var code = '';
  Object.keys(flag).map(function (v) {
    code += "".concat(v, ": ").concat(flag[v], ";");
  });
  return code;
}; // style setting to code


export var createStyleSettingCode = function createStyleSettingCode(eleType) {
  var dataSource = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  var flag = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  var customClass = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : ':root';
  var temporaryClassName = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : '';
  var _dataSource$rootState = dataSource.rootState,
      rootState = _dataSource$rootState === void 0 ? '0' : _dataSource$rootState,
      _dataSource$cssDefaul = dataSource.cssDefaultCodeRoot,
      cssDefaultCodeRoot = _dataSource$cssDefaul === void 0 ? {} : _dataSource$cssDefaul,
      _dataSource$cssDefaul2 = dataSource.cssDefaultCodeRootHover,
      cssDefaultCodeRootHover = _dataSource$cssDefaul2 === void 0 ? {} : _dataSource$cssDefaul2,
      _dataSource$cssDefaul3 = dataSource.cssDefaultCodeRootFocus,
      cssDefaultCodeRootFocus = _dataSource$cssDefaul3 === void 0 ? {} : _dataSource$cssDefaul3,
      _dataSource$cssDefaul4 = dataSource.cssDefaultCodeRootActive,
      cssDefaultCodeRootActive = _dataSource$cssDefaul4 === void 0 ? {} : _dataSource$cssDefaul4,
      setCSSDefaultCodeRoot = dataSource.setCSSDefaultCodeRoot,
      setCSSDefaultCodeRootHover = dataSource.setCSSDefaultCodeRootHover,
      setCSSDefaultCodeRootFocus = dataSource.setCSSDefaultCodeRootFocus,
      setCSSDefaultCodeRootActive = dataSource.setCSSDefaultCodeRootActive;
  var updateCode;
  var code = '';
  var codeDefault = '';
  var codeHover = '';
  var codeFocus = '';
  var codeActive = '';
  var codeDefaultExtra = '';
  var codeHoverExtra = '';
  var codeFocusExtra = '';
  var codeActiveExtra = '';
  var cloneCode = '';

  var updateObj = function updateObj(param) {
    if (Object.keys(flag).length > 0) {
      updateCode = _objectSpread(_objectSpread({}, updateCode), flag);
    }

    switch (param) {
      case '0':
        if (temporaryClassName && Object.keys(updateCode).includes('text-decoration')) {
          codeDefaultExtra = ".".concat(temporaryClassName, " > * { text-decoration: underline }");
        } else {
          codeDefaultExtra = '';
        }

        break;

      case '1':
        if (temporaryClassName && Object.keys(updateCode).includes('text-decoration')) {
          codeHoverExtra = ".".concat(temporaryClassName, ":hover > * { text-decoration: underline }");
        } else {
          codeHoverExtra = '';
        }

        break;

      case '2':
        if (temporaryClassName && Object.keys(updateCode).includes('text-decoration')) {
          codeFocusExtra = ".".concat(temporaryClassName, ":focus > * { text-decoration: underline }");
        } else {
          codeFocusExtra = '';
        }

        break;

      case '3':
        if (temporaryClassName && Object.keys(updateCode).includes('text-decoration')) {
          codeActiveExtra = ".".concat(temporaryClassName, ":active > * { text-decoration: underline }");
        } else {
          codeActiveExtra = '';
        }

        break;

      default:
        break;
    }
  };

  switch (rootState) {
    case '0':
      updateCode = cssDefaultCodeRoot;
      updateObj('0');
      setCSSDefaultCodeRoot(updateCode);
      code = toSourceCode(updateCode);
      cloneCode = _cloneDeep(code);

      if (!eleType) {
        code = "".concat(customClass, "{").concat(code, "}");
      }

      if (eleType && temporaryClassName) {
        code = "".concat(customClass, " ").concat(eleType, " {").concat(cloneCode, "}");
      }

      codeHover = toSourceCode(cssDefaultCodeRootHover);
      codeFocus = toSourceCode(cssDefaultCodeRootFocus);
      codeActive = toSourceCode(cssDefaultCodeRootActive);
      break;

    case '1':
      updateCode = cssDefaultCodeRootHover;
      updateObj('1');
      setCSSDefaultCodeRootHover(updateCode);
      code = toSourceCode(updateCode);
      cloneCode = _cloneDeep(code);

      if (!eleType) {
        code = "".concat(customClass, ":hover{").concat(code, "}");
      }

      if (eleType && temporaryClassName) {
        code += "".concat(customClass, ":hover ").concat(eleType, " {").concat(cloneCode, "}");
      }

      codeDefault = toSourceCode(cssDefaultCodeRoot);
      codeFocus = toSourceCode(cssDefaultCodeRootFocus);
      codeActive = toSourceCode(cssDefaultCodeRootActive);
      break;

    case '2':
      updateCode = cssDefaultCodeRootFocus;
      updateObj('2');
      setCSSDefaultCodeRootFocus(updateCode);
      code = toSourceCode(updateCode);
      cloneCode = _cloneDeep(code);

      if (!eleType) {
        code = "".concat(customClass, ":focus{").concat(code, "}");
      }

      if (eleType && temporaryClassName) {
        code += "".concat(customClass, ":focus ").concat(eleType, " {").concat(cloneCode, "}");
      }

      codeDefault = toSourceCode(cssDefaultCodeRoot);
      codeHover = toSourceCode(cssDefaultCodeRootHover);
      codeActive = toSourceCode(cssDefaultCodeRootActive);
      break;

    case '3':
      updateCode = cssDefaultCodeRootActive;
      updateObj('3');
      setCSSDefaultCodeRootActive(updateCode);
      code = toSourceCode(updateCode);
      cloneCode = _cloneDeep(code);

      if (!eleType) {
        code = "".concat(customClass, ":active{").concat(code, "}");
      }

      if (eleType && temporaryClassName) {
        code += "".concat(customClass, ":active ").concat(eleType, " {").concat(cloneCode, "}");
      }

      codeDefault = toSourceCode(cssDefaultCodeRoot);
      codeHover = toSourceCode(cssDefaultCodeRootHover);
      codeFocus = toSourceCode(cssDefaultCodeRootFocus);
      break;

    default:
      break;
  }

  if (codeDefault) {
    code += "".concat(customClass, "{").concat(codeDefault, "}");
  }

  if (codeHover) {
    code += "".concat(customClass, ":hover{").concat(codeHover, "}");
  }

  if (codeFocus) {
    code += "".concat(customClass, ":focus{").concat(codeFocus, "}");
  }

  if (codeActive) {
    code += "".concat(customClass, ":active{").concat(codeActive, "}");
  }

  if (codeDefaultExtra) {
    code += codeDefaultExtra;
  }

  if (codeHoverExtra) {
    code += codeHoverExtra;
  }

  if (codeFocusExtra) {
    code += codeFocusExtra;
  }

  if (codeActiveExtra) {
    code += codeActiveExtra;
  }

  return code.replace(/\$/g, '\\$');
}; // isGroupInput

export var isGroupInput = function isGroupInput(type) {
  var inputGroup = ['input', 'password', 'checkBoxGroup', 'radioGroup', 'timePicker', 'datePicker', 'rangePicker', 'cascader', 'select', 'slider', 'rate', 'imageUpload', 'treeSelect'];
  return inputGroup.includes(type);
}; // imgUrlToPath

export var imgUrlToPath = function imgUrlToPath(url) {
  if (url && url.includes('url(')) {
    return url.replace('url(', '').replace(')', '').replace(/\'/g, '').replace(/\"/g, '');
  } else {
    return url;
  }
}; // css加到brower

export var createCSSToBrower = function createCSSToBrower(flag) {
  // 先删除
  var getBrowerCSS = document.getElementsByClassName('css_import_json');
  if (getBrowerCSS.length > 0) getBrowerCSS[0].remove(); // 再生成

  var headTag = document.getElementsByTagName("body");
  var para = document.createElement("style"); // 创建需要增加的元素节点

  para.setAttribute('class', 'css_import_json');
  var node = document.createTextNode(flag); // 创建文本节点

  para.appendChild(node); // 将文本节点增加至创建的元素中

  headTag[0].appendChild(para);
}; // build css

export var buildCSSToString = function buildCSSToString() {
  var customStyle = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  var temporaryStyle = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  var pageStyle = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  var buldCSSCode = '';

  if (customStyle && Object.keys(customStyle).length > 0 && Object.keys(customStyle)[0]) {
    Object.keys(customStyle).map(function (v) {
      var _Object$keys;

      var itemCode = '';
      (_Object$keys = Object.keys(customStyle[v])) === null || _Object$keys === void 0 ? void 0 : _Object$keys.map(function (item) {
        itemCode += "".concat(item, ":").concat(customStyle[v][item], ";");
      });
      var len = Object.keys(customStyle[v]).length;

      if (len > 0) {
        buldCSSCode += "".concat(v, "{").concat(itemCode, "}");
      }
    });
  }

  if (pageStyle && Object.keys(pageStyle).length > 0 && Object.keys(pageStyle)[0]) {
    Object.keys(pageStyle).map(function (v) {
      var _Object$keys2;

      var itemCode = '';
      (_Object$keys2 = Object.keys(pageStyle[v])) === null || _Object$keys2 === void 0 ? void 0 : _Object$keys2.map(function (item) {
        itemCode += "".concat(item, ":").concat(pageStyle[v][item], ";");
      });
      var len = Object.keys(pageStyle[v]).length;

      if (len > 0) {
        buldCSSCode += "".concat(v, "{").concat(itemCode, "}");
      }
    });
  }

  if (temporaryStyle && Object.keys(temporaryStyle).length > 0 && Object.keys(temporaryStyle)[0]) {
    Object.keys(temporaryStyle).map(function (v) {
      var _Object$keys3;

      var itemCode = '';
      (_Object$keys3 = Object.keys(temporaryStyle[v])) === null || _Object$keys3 === void 0 ? void 0 : _Object$keys3.map(function (item) {
        itemCode += "".concat(item, ":").concat(temporaryStyle[v][item], ";");
      });
      var len = Object.keys(temporaryStyle[v]).length;

      if (len > 0) {
        buldCSSCode += "".concat(v, "{").concat(itemCode, "}");
      }
    });
  }

  return buldCSSCode.replace(/\$/g, '\\$');
}; // css to json

export var cssToJson = function cssToJson(cssCode) {
  // 移除CSS所有注释
  var open = cssCode.indexOf("/*");
  var close = cssCode.indexOf("*/");

  while (open !== -1 && close !== -1) {
    cssCode = cssCode.substring(0, open) + cssCode.substring(close + 2);
  } // 初始化返回值


  var json = {};

  var _loop = function _loop() {
    // 存储第一个左/右花括号的下标
    var lbracket = cssCode.indexOf('{');
    var rbracket = cssCode.indexOf('}'); // 第一步：将声明转换为Object

    var toObject = function toObject(array) {
      var ret = {};
      array.forEach(function (e) {
        var index = e.indexOf(':');
        var property = e.substring(0, index).trim();
        var value = e.substring(index + 1).trim();
        ret[property] = value;
      });
      return ret;
    }; // 切割声明块并移除空白符，然后放入数组中


    var declarations = cssCode.substring(lbracket + 1, rbracket).split(";").map(function (e) {
      return e.trim();
    }).filter(function (e) {
      return e.length > 0;
    }); // 移除所有""空值
    // 转为Object对象

    declarations = toObject(declarations); // 第二步：选择器处理，每个选择器会与它对应的声明相关联

    var selectors = cssCode.substring(0, lbracket).split(",").map(function (selector) {
      return selector.replace(/\\/g, '').trim();
    }); // 迭代赋值

    selectors.forEach(function (selector) {
      // 若不存在，则先初始化
      if (!json[selector]) json[selector] = {}; // 赋值到JSON

      Object.keys(declarations).forEach(function (key) {
        json[selector][key] = declarations[key];
      });
    }); // 继续下个声明块

    cssCode = cssCode.slice(rbracket + 1).trim();
  };

  while (cssCode.length > 0) {
    _loop();
  } // 返回JSON形式的结果串


  return json;
}; // 样式分类型加载到browser

var loadStyleByTypeToBrowser = function loadStyleByTypeToBrowser() {
  var code = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
  var type = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
  // 先删除
  var getBrowerCSS = document.getElementsByClassName(type);

  if (getBrowerCSS.length > 0) {
    new Array(getBrowerCSS.length).fill('1').map(function (v, index) {
      getBrowerCSS[0].remove();
    });
  } // 再生成


  if (code) {
    var headTag = document.getElementsByTagName("body");
    var para = document.createElement("style");
    para.setAttribute('class', type);
    var node = document.createTextNode(code);
    para.appendChild(node);
    headTag[0].appendChild(para);
  }
}; // css to setting


export var cssToSetting = function cssToSetting(cssCode) {
  var currentPage = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
  // createCSSToBrower(cssCode);
  var codeJson = cssToJson(cssCode);
  var custom = {};
  var temporary = {};
  var page = {};
  Object.keys(codeJson).map(function (v) {
    if (v.includes('_css_')) {
      temporary[v] = codeJson[v];
    } else if (v.includes("".concat(currentPage, "_"))) {
      page[v] = codeJson[v];
    } else {
      custom[v] = codeJson[v];
    }
  }); // 编译到页面，
  // 自定义(全局)

  var cssCustom = buildCSSToString(custom, {}, {});
  loadStyleByTypeToBrowser(cssCustom, 'css_custom'); // temporary
  // 先删除

  Object.keys(temporary).map(function (vl) {
    var cssTemp = buildCSSToString({}, _defineProperty({}, vl, temporary[vl]), {});
    loadStyleByTypeToBrowser(cssTemp, "css_temporary_".concat(vl.replace('.desktop .', '').replace('.mobile .', '').replace('.pad .', '')));
  }); // page

  var cssPage = buildCSSToString({}, {}, page);
  loadStyleByTypeToBrowser(cssPage, 'css_page');
  return {
    temporary: temporary,
    custom: custom,
    page: page
  };
}; // device math css prefix

export var matchCodePrefix = {
  PC: 'desktop',
  Mobile: 'mobile',
  Pad: 'pad'
}; // 注册主题

export var registryTheme = function registryTheme() {
  var name = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
  var title = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
  var url = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : '';

  window.g_app._store.dispatch({
    type: 'style/saveAllThemes',
    payload: {
      name: name,
      title: title,
      url: url
    }
  });
}; // loadTheme

export var loadTheme = function loadTheme() {
  var name = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
  var url = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
  var getThemeNode = document.getElementById('globalTheme');
  var themeType = name && name !== 'pto' ? name : '';
  if (getThemeNode) getThemeNode.setAttribute('href', themeType ? url : '/css/pto.min.css');
}; // 判断是否存在容器

export var judgeIfContainContainer = function judgeIfContainContainer() {
  var content = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};

  if (Object.keys(content).length <= 0) {
    return false;
  }

  var recursionFun = function recursionFun(element) {
    if (['form', 'block'].includes(element.type)) {
      return true;
    }

    var _element$elements = element.elements,
        elements = _element$elements === void 0 ? [] : _element$elements;

    for (var i = 0; i < elements.length; i += 1) {
      if (['form', 'block'].includes(elements[i].type)) {
        return true;
      }

      return recursionFun(elements[i]);
    }
  };

  return recursionFun(content);
};
export var defaultColumns = [{
  key: "0",
  title: 'Name',
  dataIndex: 'name'
}, {
  key: "1",
  title: 'Age',
  dataIndex: 'age'
}, {
  key: "2",
  title: 'Address',
  dataIndex: 'address'
}];
export var defaultDataSource = [{
  key: '1',
  name: 'Lucy',
  age: 12,
  address: 'XXXXX'
} // {
//   key: '2',
//   name: 'Jack',
//   age: 11,
//   address: 'XXXXXXX',
// }
];
export var getDeepPropByKeys = function getDeepPropByKeys() {
  var keys = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
  var target = arguments.length > 1 ? arguments[1] : undefined;
  var value;
  keys.forEach(function (key) {
    value = value ? value[key] : target[key];
  });
  return value;
}; // enable class

export var enableClass = {
  'flex Justify': ['flex', 'flex justify-start', 'flex justify-center', 'flex justify-end', 'flex justify-between', 'flex justify-around'],
  'Justify Content': ['justify-start', 'justify-center', 'justify-end', 'justify-between', 'justify-around'],
  'Text Color': ['text-black', 'text-white', 'text-gray-400', 'text-gray-500', 'text-gray-600', 'text-red-400', 'text-red-500', 'text-red-600', 'text-orange-400', 'text-orange-500', 'text-orange-600', 'text-yellow-400', 'text-yellow-500', 'text-yellow-600', 'text-green-400', 'text-green-500', 'text-green-600', 'text-teal-400', 'text-teal-500', 'text-teal-600', 'text-blue-400', 'text-blue-500', 'text-blue-600', 'text-indigo-400', 'text-indigo-500', 'text-indigo-600', 'text-purple-400', 'text-purple-500', 'text-purple-600', 'text-pink-400', 'text-pink-500', 'text-pink-600'],
  'Font Size': ['text-xs', 'text-sm', 'text-base', 'text-lg', 'text-xl', 'text-2xl', 'text-3xl', 'text-4xl', 'text-5xl', 'text-6xl'],
  'Font Weight': ['font-light', 'font-normal', 'font-bold', 'font-black'],
  Block: ['hidden', 'block', 'inline-block', 'flex'],
  Float: ['float-right', 'float-left', 'float-none', 'clearfix'],
  Italic: ['italic', 'not-italic'],
  'Text Decoration': ['underline', 'line-through', 'no-underline'],
  'Text Alignment': ['text-left', 'text-center', 'text-right', 'text-justify'],
  Width: ['w-16', 'w-20', 'w-24', 'w-32', 'w-40', 'w-48'],
  Height: ['h-16', 'h-20', 'h-24', 'h-32', 'h-40', 'h-48'],
  Margin: ['m-16', 'm-20', 'm-24', 'm-32', 'm-40', 'm-48'],
  Padding: ['p-16', 'p-20', 'p-24', 'p-32', 'p-40', 'p-48'],
  Shadow: ['shadow-xs', 'shadow-sm', 'shadow', 'shadow-md', 'shadow-lg', 'shadow-xl', 'shadow-2xl']
}; // 删除block容器内表单formItem相关设置

export var deleteFormSettingsInBlockElement = function deleteFormSettingsInBlockElement(element) {
  var _element$data6;

  if ((_element$data6 = element.data) !== null && _element$data6 !== void 0 && _element$data6.formSettings && element.type !== 'form') {
    var _element$data7, _element$data8, _element$data9;

    var name = element.data.formSettings.name;

    if ((_element$data7 = element.data) !== null && _element$data7 !== void 0 && _element$data7.formItemSettings) {
      element.data.formItemSettings.name = name;
    }

    if ((_element$data8 = element.data) !== null && _element$data8 !== void 0 && _element$data8.componentSettings) {
      element.data.componentSettings.name = name;
    }

    (_element$data9 = element.data) === null || _element$data9 === void 0 ? true : delete _element$data9.formSettings;
  }

  return element;
}; // string format

export var strFormat = function strFormat(str) {
  return str.replace(/\s+/g, '');
}; // 根据表格绑定数据源信息获取commonSql字段

export var getCommonColumnsByVariable = function getCommonColumnsByVariable(dataSourceVariable, projectData) {
  var datas = [];

  if (dataSourceVariable) {
    var variableArr = dataSourceVariable.split('/');

    if (variableArr.length === 4) {
      var pageName = variableArr[2];
      var sqlName = variableArr[3];

      if (projectData[pageName] && projectData[pageName].commonSql) {
        var targetSql = projectData[pageName].commonSql.find(function (v) {
          return v.name === sqlName;
        });

        if (targetSql) {
          var _JSON$parse = JSON.parse(targetSql.data),
              _JSON$parse$sources = _JSON$parse.sources,
              sources = _JSON$parse$sources === void 0 ? [] : _JSON$parse$sources,
              _JSON$parse$columns = _JSON$parse.columns,
              columns = _JSON$parse$columns === void 0 ? [] : _JSON$parse$columns;

          var calcColumns = columns.filter(function (v) {
            return v.label && v.expression;
          }); // 计算属性列

          sources.forEach(function (source) {
            var children = columns.filter(function (v) {
              return v.object === source;
            }).map(function (v) {
              return {
                name: v.label,
                value: v.field,
                key: "".concat(source, ".").concat(v.field)
              };
            });
            datas.push({
              name: source,
              value: source,
              key: source,
              children: children
            });
          });

          if (calcColumns.length > 0) {
            calcColumns.forEach(function (column) {
              datas.push({
                name: column.label,
                value: column.expression,
                key: column.label,
                title: column.label,
                iconType: 'expression',
                children: []
              });
            });
          }
        }
      }
    }
  }

  return datas;
};
//# sourceMappingURL=utils.js.map