import _regeneratorRuntime from "@babel/runtime/regenerator";
import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator";
import _objectSpread from "@babel/runtime/helpers/objectSpread2";

/*eslint-disable*/
import cloneDeep from 'lodash/cloneDeep';
import moment from 'moment';
import get from "lodash/get";
import dotProp, { set } from 'dot-prop-immutable';
import { i18n } from '@fishx/i18n';
import { cloneElement, createElement, updateChildPaths } from "../editor/utils";
import { getParentElementWithChildren } from "../editor/selectors";
import previewDeviceConfig from "../config/previewDeviceConfig";
import { defaultCols, noGridTarget } from "../config/pluginConfig";
import { ElementGroup } from "../constant/index";
var PC = previewDeviceConfig.PC;
export var flattenContent = function flattenContent(el) {
  var els = {};
  el.elements = Array.isArray(el.elements) && el.elements.map(function (child) {
    els = _objectSpread(_objectSpread({}, els), flattenContent(child));
    return child.id;
  });
  els[el.id] = el;
  return els;
};
export var distributeColumnWidths = function distributeColumnWidths(row) {
  var span = Math.round(24 / row.elements.length * 24) / 24;
  var columns = row.elements.map(function (el) {
    var _el$data$settings = el.data.settings,
        settings = _el$data$settings === void 0 ? {} : _el$data$settings;

    if (!settings.cols) {
      settings.cols = {};
    }

    settings.cols.span = Math.floor(span);
    set(el, 'data.settings', settings);
    return el;
  });
  return set(row, 'elements', columns);
};
export var getFlattenElements = function getFlattenElements(state) {
  if (!state.page.content) {
    return state;
  } // TODO


  var content = dotProp.get(state, 'page.content') || null;

  if (!content) {
    return state;
  }

  var elements = flattenContent(cloneDeep(content));
  return elements;
};
export var getNewState = function getNewState(state, element) {
  var statePath;
  var elements = {};

  if (element.type === 'document') {
    statePath = 'page.content';
  } else {
    statePath = "page.content.".concat(element.path.replace(/\./g, '.elements.').slice(2));
  }

  updateChildPaths(element, elements);
  var prevElements = state.elements;
  var matchReg = statePath === 'page.content' ? statePath : 'page.content.elements';
  var matchPath = statePath.replace(matchReg, "0").replace(/elements./g, '');
  Object.keys(prevElements).forEach(function (key) {
    var path = prevElements[key].path;

    if (path.length <= matchPath.length) {
      if (path !== matchPath) {
        elements[key] = prevElements[key];
      }
    }

    if (path.length > matchPath.length) {
      if (!path.startsWith(matchPath)) {
        elements[key] = prevElements[key];
      }
    }
  });
  var newState = dotProp.set(state, statePath, element);
  newState = dotProp.set(newState, "elements", elements);
  return newState;
};
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.elements[item] || {}; // if (newItem.type === 'headerCell') {
        // 更新表格时，需要更新3级

        updateElements(state, newItem); // }

        return newItem;
      } else {
        return item;
      }
    });
  }
}; // get fromdata from element

export var jsonToFromElement = function jsonToFromElement(content) {
  var getForm = {};

  var mapJson = function mapJson(elements, formId, obj) {
    if (Array.isArray(elements) && elements.length > 0) {
      elements.forEach(function (child) {
        var _child$data;

        if (child.type === 'form') {
          obj[child.id] = [];
          mapJson(child.elements, child.id, obj);
        } else if ((_child$data = child.data) !== null && _child$data !== void 0 && _child$data.formSettings) {
          var _child$data$formSetti = child.data.formSettings,
              name = _child$data$formSetti.name,
              label = _child$data$formSetti.label;
          obj[formId].push({
            name: name,
            type: child.type,
            label: label || child.type
          });
        } else if (child.elements) {
          mapJson(child.elements, formId, obj);
        }
      });
    }
  };

  mapJson(content.elements, null, getForm);
  return getForm;
}; // get fromdata from json

export var jsonToFromSetting = function jsonToFromSetting(content) {
  var getFormElementInfo = {};

  if (content && content.type === 'document') {
    if (content.elements.length > 0) {
      content.elements.map(function (v) {
        if (v.type === 'form') {
          if (v.elements.length > 0) {
            getFormElementInfo[v.id] = v;
          }
        }
      });
    }
  }

  return getFormElementInfo;
}; // 删除formInstance实例

export var deleteFormInstance = function deleteFormInstance(content) {
  var type = content.type,
      _content$elements = content.elements,
      elements = _content$elements === void 0 ? [] : _content$elements;

  if (type === 'document' && elements.length > 0) {
    elements.forEach(function (formElement, index) {
      if (formElement.data.formInstance) {
        content.elements[index] = set(content.elements[index], 'data.formInstance', null);
      }
    });
  }

  return content;
};
export var mapElements = function mapElements(elements, values) {
  if (elements && elements.length > 0) {
    elements.forEach(function (element) {
      if (['document', 'form', 'row', 'column'].includes(element.type)) {
        mapElements(element.elements, values);
      } else {
        var type = element.type,
            _element$data = element.data,
            _element$data$formSet = _element$data.formSettings,
            formSettings = _element$data$formSet === void 0 ? {} : _element$data$formSet,
            _element$data$formIte = _element$data.formItemSettings,
            formItemSettings = _element$data$formIte === void 0 ? {} : _element$data$formIte;
        var name = formSettings.name;

        if (['upload', 'imageUpload'].includes(type)) {
          var fileIdName = formItemSettings.fileIdName,
              _formItemSettings$fil = formItemSettings.fileList,
              fileList = _formItemSettings$fil === void 0 ? [] : _formItemSettings$fil;

          if (fileList.length > 0) {
            var ids = fileList.map(function (v) {
              return v.url.split("".concat(fileIdName, "="))[1];
            });
            values[name] = ids;
          }
        }
      }
    });
  }
};
export var handleValues = function handleValues(values, data) {
  mapElements(data.elements || [], values);
  return values;
};
export var tagNameMaps = {
  Column: 'Col',
  TextArea: 'Input.TextArea',
  RadioGroup: 'Radio.Group',
  CheckBoxGroup: 'Checkbox.Group',
  HeaderCell: 'Table.Column',
  ListItem: 'List.Item'
}; // xml内需要转义的字符

export var transformCharMaps = {
  '&': '&amp;',
  '>': '&gt;',
  '<': '&lt;'
};
export var endWidth = function endWidth(regStr, str) {
  var reg = new RegExp("".concat(regStr, "$"));
  return reg.test(str);
};
export var createOrCloneElemet = function createOrCloneElemet(source, target) {
  var element;

  if (source.path) {
    element = cloneElement(source, ['id']);
  } else {
    element = createElement(source.type, {}, target);
  }

  return element;
}; // 子column内元素数量<=1 需要提取elements并删除该column

export var hendleInnerColumnByParent = function hendleInnerColumnByParent(target, child) {
  var children = [];
  var childIndex = target.elements.findIndex(function (el) {
    return el.id === child.id;
  });

  if (childIndex > -1) {
    if (child.elements.length <= 1) {
      // column内组件数量 <=1 提取elements并删除column
      child.elements.forEach(function (child) {
        children.push(cloneElement(child));
      });
      target = dotProp.delete(target, "elements.".concat(childIndex));

      if (children.length > 0) {
        var _target$elements;

        (_target$elements = target.elements).splice.apply(_target$elements, [childIndex, 0].concat(children));
      }
    } else {
      target.elements[childIndex] = child;
    }
  }

  return target;
};
export var judgeIfButtonElement = function judgeIfButtonElement(element) {
  if (element) {
    if (element.type && element.type.indexOf('button') > -1) {
      return true;
    }

    if (typeof element === 'string' && element.indexOf('button') > -1) {
      return true;
    }

    return false;
  }

  return false;
};
export var ifCompare = function ifCompare(object1, object2) {
  var o1keys = Object.keys(object1);
  var o2keys = Object.keys(object2);

  if (o2keys.length !== o1keys.length) {
    return false;
  }

  for (var i = 0; i <= o1keys.length - 1; i++) {
    var key = o1keys[i];

    if (key === "elements" && object1["elements"].length > 0) {
      return ifCompare(object1[key], object2[key]);
    } else {
      if (!o2keys.includes(key)) return false;
      if (object2[key] !== object1[key]) return false;
    }
  }

  return true;
};
export var getElementGroupTitle = function getElementGroupTitle(group) {
  var name = group;

  switch (group) {
    case ElementGroup.BASIC:
      name = i18n('PAGEBUIDER_ELEMENT_GROUP_BASIC');
      break;

    case ElementGroup.CONTAINER:
      name = i18n('PAGEBUIDER_ELEMENT_GROUP_CONTAINER');
      break;

    case ElementGroup.LAYOUT:
      name = i18n('PAGEBUIDER_ELEMENT_GROUP_LAYOUT');
      break;

    case ElementGroup.INPUT:
      name = i18n('PAGEBUIDER_ELEMENT_GROUP_FORM_INPUT');
      break;

    case ElementGroup.SELECT:
      name = i18n('PAGEBUIDER_ELEMENT_GROUP_FORM_SELECT');
      break;

    case ElementGroup.COMPLEX:
      name = i18n('PAGEBUIDER_ELEMENT_GROUP_FORM_COMPLEX');
      break;

    case ElementGroup.CHART:
      name = i18n('PAGEBUIDER_ELEMENT_GROUP_FORM_CHART');
      break;

    case ElementGroup.CUSTOM:
      name = i18n('PAGEBUIDER_ELEMENT_GROUP_FORM_CUSTOM');
      break;

    case ElementGroup.SAVE:
      name = i18n('PAGEBUIDER_ELEMENT_GROUP_SAVE');
      break;

    default:
      break;
  }

  return name;
};
export var getFormInitialValues = function getFormInitialValues(dataSource) {
  var getDataSource = {};
  var timeFormat = 'HH:mm:ss';
  var dateFormat = 'YYYY-MM-DD';

  if (dataSource && dataSource.length > 0) {
    dataSource.map(function (v) {
      var name = v.name,
          defaultValue = v.defaultValue,
          type = v.type;

      if (type && type === 'timePicker') {
        getDataSource[name] = moment(defaultValue, timeFormat);
      } else if (type && type === 'datePicker') {
        getDataSource[name] = moment(defaultValue, dateFormat);
      } else getDataSource[name] = defaultValue;
    });
  }

  return getDataSource;
}; // handleInputType

export var handleInputType = function handleInputType(element, propName, value, state, valueKey, formKey) {
  var oldObj = element.data.formSettings;
  var keyArr = ['text', 'password', 'email', 'url', 'tel'];
  var newElement = element;
  var getElement;

  if (keyArr.includes(value) && element.type === 'input') {
    newElement = set(newElement, propName, value);
  } else if (keyArr.includes(value) && element.type !== 'input') {
    var parentElement = getParentElementWithChildren(state, element.id);
    newElement = createElement('input');
    newElement = set(newElement, propName, value);
    getElement = newElement;
    newElement = set(parentElement, 'elements', [newElement]);
  } else if (value === 'dateTime') {
    var _parentElement = getParentElementWithChildren(state, element.id);

    newElement = createElement('datePicker');
    newElement = set(newElement, "".concat(valueKey, ".showTime"), true);
    newElement = set(newElement, "".concat(valueKey, ".format"), 'YYYY-MM-DD HH:mm:ss');
    newElement = set(newElement, "".concat(formKey, ".name"), oldObj === null || oldObj === void 0 ? void 0 : oldObj.name);
    newElement = set(newElement, "".concat(formKey, ".label"), oldObj === null || oldObj === void 0 ? void 0 : oldObj.label);
    getElement = newElement;
    newElement = set(_parentElement, 'elements', [newElement]);
  } else {
    var _parentElement2 = getParentElementWithChildren(state, element.id);

    newElement = createElement(value);
    newElement = set(newElement, "".concat(formKey, ".name"), oldObj === null || oldObj === void 0 ? void 0 : oldObj.name);
    newElement = set(newElement, "".concat(formKey, ".label"), oldObj === null || oldObj === void 0 ? void 0 : oldObj.label);
    getElement = newElement;
    newElement = set(_parentElement2, 'elements', [newElement]);
  }

  return {
    newElement: newElement,
    getElement: getElement
  };
}; // temp
// 计算表格scroll

export var calculateScrollWidth = function calculateScrollWidth(formElement, element, len, isEdit, mode) {
  var _formElement$data;

  if (!((_formElement$data = formElement.data) !== null && _formElement$data !== void 0 && _formElement$data.formSettings)) {
    var _tableId = element.id;
    var blockId = formElement.id;

    var _tableElement = document.getElementById(_tableId);

    if (!_tableElement) return null;
    var _formEl = document.getElementsByClassName('webiny-pb-editor-content-preview')[0];

    var _formStyle = window.getComputedStyle(_formEl, null);

    var _defaultThWidth = 164;
    var _lableDefaultPadding = 38;

    var _getTableWidth = parseInt(_formStyle.width, 10) - _lableDefaultPadding;

    _tableElement.style.width = 'auto';

    var _getDefaultWidth = (!isEdit ? len : len + 1) * _defaultThWidth;

    var _getScrollWidth;

    if (_getDefaultWidth > _getTableWidth) {
      _tableElement.style.width = _getTableWidth + 'px';
      _getScrollWidth = _getDefaultWidth;
    } else {
      _getScrollWidth = 0;
    }

    return _getScrollWidth;
  }

  var prefix = mode === 'render' ? 'render_' : '';
  var _formElement$data$for = formElement.data.formSettings,
      name = _formElement$data$for.name,
      labelWidth = _formElement$data$for.labelWidth;
  var tableId = element.data.formSettings.name;
  var tableElement = document.getElementById("".concat(prefix).concat(name, "_").concat(tableId));
  if (!tableElement) return null;
  var formEl = document.getElementById("".concat(prefix).concat(name));
  var formStyle = window.getComputedStyle(formEl, null);
  var defaultThWidth = 164;
  var lableDefaultPadding = 12;
  var getTableWidth = parseInt(formStyle.width, 10) - lableDefaultPadding - labelWidth;
  tableElement.style.width = 'auto';
  var getDefaultWidth = (!isEdit ? len : len + 1) * defaultThWidth;
  var getScrollWidth;

  if (getDefaultWidth > getTableWidth) {
    tableElement.style.width = getTableWidth + 'px';
    getScrollWidth = getDefaultWidth;
  } else {
    getScrollWidth = 0;
  }

  return getScrollWidth;
}; // 表格校验

export var tableRegExp = /*#__PURE__*/function () {
  var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(rule, value) {
    var dataSource,
        userRule,
        _args = arguments;
    return _regeneratorRuntime.wrap(function _callee$(_context) {
      while (1) {
        switch (_context.prev = _context.next) {
          case 0:
            dataSource = _args.length > 2 && _args[2] !== undefined ? _args[2] : [];
            userRule = _args.length > 3 ? _args[3] : undefined;
            return _context.abrupt("return", new Promise(function (resolve, reject) {
              setTimeout(function () {
                if (dataSource.length > 0) {
                  resolve();
                }

                reject(userRule.message);
              }, 100);
            }));

          case 3:
          case "end":
            return _context.stop();
        }
      }
    }, _callee);
  }));

  return function tableRegExp(_x, _x2) {
    return _ref.apply(this, arguments);
  };
}();
export var getSpansAllFromElements = function getSpansAllFromElements(elements) {
  var value = 0;

  if (Array.isArray(elements)) {
    elements.forEach(function (element) {
      var _element$data2;

      var _ref2 = ((_element$data2 = element.data) === null || _element$data2 === void 0 ? void 0 : _element$data2.settings) || {},
          _ref2$cols = _ref2.cols,
          cols = _ref2$cols === void 0 ? defaultCols : _ref2$cols;

      if (noGridTarget.includes(element.type)) {
        cols = {
          span: 1,
          offset: 0
        };
      }

      var _cols = cols,
          span = _cols.span,
          _cols$offset = _cols.offset,
          offset = _cols$offset === void 0 ? 0 : _cols$offset;
      value += span + offset;
    });
  }

  return value;
}; // 根据栅格将容器内的子元素分组

export var divideBlockChildrenWidthSpan = function divideBlockChildrenWidthSpan(children) {
  var eles = [];

  if (Array.isArray(children)) {
    children.forEach(function (element) {
      var _element$data3;

      var _ref3 = ((_element$data3 = element.data) === null || _element$data3 === void 0 ? void 0 : _element$data3.settings) || {},
          _ref3$cols = _ref3.cols,
          cols = _ref3$cols === void 0 ? defaultCols : _ref3$cols;

      if (noGridTarget.includes(element.type)) {
        cols = {
          span: 1,
          offset: 0
        };
      }

      var _cols2 = cols,
          span = _cols2.span,
          _cols2$offset = _cols2.offset,
          offset = _cols2$offset === void 0 ? 0 : _cols2$offset;

      if (span + offset >= 24 || eles.length <= 0) {
        eles.push([element]);
      } else {
        var canInsert = false;

        for (var i = 0; i < eles.length; i += 1) {
          var item = eles[i];
          var currentSpan = getSpansAllFromElements(item);

          if (currentSpan + span + offset <= 24) {
            eles[i].push(element);
            canInsert = true;
            break;
          }
        }

        if (!canInsert) {
          eles.push([element]);
        }
      }
    });
  }

  return eles;
};
export var getElementCols = function getElementCols(element) {
  var previewDevice = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : PC;
  var colProps = {};
  var cols = get(element.data, "settings.cols") || defaultCols;
  colProps.span = cols.span || 24;
  colProps.offset = cols.offset || 0;
  colProps.xs = 24;
  colProps.sm = 24;
  colProps.md = 24;
  var isDesktop = previewDevice === PC;
  colProps.lg = isDesktop ? colProps.span : 24;
  colProps.xl = isDesktop ? colProps.span : 24;
  colProps.xxl = isDesktop ? colProps.span : 24;
  return colProps;
};
/**
 * 数据类型与前端控件类型转化
 * @param flag 
 */

export var transformComponentByType = function transformComponentByType(flag) {
  switch (flag) {
    case 'Integer':
      return 'inputNumber';

    case 'Long':
      return 'inputNumber';

    case 'Boolean':
      return 'switch';

    case 'String':
      return 'input';

    case 'Time':
      return 'timePicker';

    case 'Data':
      return 'datePicker';

    case 'DateTime':
      return 'datePicker';

    case 'Float':
      return 'inputNumber';

    case 'Double':
      return 'inputNumber';

    case 'Picklist':
      return 'select';

    case 'Picklist(Multi-Select)':
      return 'multiselect';

    case 'Text':
      return 'input';

    case 'TextArea':
      return 'textArea';

    case 'EncryptedText':
      // 密码框
      return 'password';

    case 'LongText':
      return 'textArea';

    case 'RichText':
      // 超文本
      return 'textArea';

    case 'PhoneNumber':
      return 'input';

    case 'Binary':
      // 二进制
      return 'upload';

    case 'Decimal':
      //十进制
      return 'input';

    case 'Currency':
      //货币
      return 'inputNumber';

    case 'Icon':
      return 'input';

    case 'Image':
      return 'input';

    case 'Email':
      return 'input';

    case 'URL':
    default:
      return 'input';
  }
};
/**
 * 
 * @param flag 查询当前类型是否时基础类型
 */

export var isBaseType = function isBaseType(flag) {
  var dataType = ['Integer', 'Long', 'inputNumber', 'Boolean', 'String', 'Time', 'Date', 'DateTime', 'Text', 'TextArea', 'EncryptedText', 'LongText', 'RichText', 'Float', 'Double', 'Decimal', 'Binary', 'Currency', 'PhoneNumber', 'Email', 'Icon', 'Image', 'URL'];
  var found = dataType.find(function (element) {
    return element === flag;
  });

  if ((found === null || found === void 0 ? void 0 : found.length) > 0) {
    return true;
  }

  return false;
};
/**
 * 
 * @param flag 查询当前类型是否时基础类型
 */

export var getDisplayControl = function getDisplayControl(flag) {
  var dataType = [{
    "key": "input",
    "value": "input"
  }, {
    "key": "textArea",
    "value": "textArea"
  }, {
    "key": "inputNumber",
    "value": "inputNumber"
  }, {
    "key": "timePicker",
    "value": "timePicker"
  }, {
    "key": "dataPicker",
    "value": "dataPicker"
  }, {
    "key": "select",
    "value": "select"
  }, {
    "key": "multiselect",
    "value": "multiselect"
  }, {
    "key": "upload",
    "value": "upload"
  }];
  return dataType;
};
export var getDefultLength = function getDefultLength(type) {
  var typeMap = {
    'text': {
      'length': 128
    },
    'encryptedtext': {
      'length': 128
    },
    'phonenumber': {
      'length': 20
    },
    'email': {
      'length': 250
    },
    'textarea': {
      'length': 4000
    }
  };
  return type ? typeMap[type.toLowerCase()] : false;
};
export var getAccuracy = function getAccuracy(type) {
  var typeMap = {
    'currency': {
      'accuracy': 2
    },
    'float': {
      'accuracy': 6
    },
    'double': {
      'accuracy': 16
    }
  };
  return type ? typeMap[type.toLowerCase()] : false;
};
/**
 * 类名 AppApply 转化成 APP_APPLY
 * 属性名 userId 转化成 USER_ID
 * @param str 
 */

export var getFormartCode = function getFormartCode(str) {
  var reStr = str.replace(/([A-Z])/g, '_$1').toUpperCase();

  if (reStr.substr(0, 1) === '_') {
    reStr = reStr.substr(1);
  }

  return reStr;
};
/**
 * 获取当前默认名称
 * @param oldObjectList 
 * @param nameStr 
 */

export var getObjectName = function getObjectName(oldObjectList, nameStr) {
  var objectName = '';
  var count = 0;

  while (true) {
    var _object = oldObjectList.find(function (item) {
      return item.name === "".concat(nameStr).concat(count);
    });

    if (!_object) {
      objectName = "".concat(nameStr).concat(count);
      break;
    }

    count++;
  }

  return objectName;
};
/**
 * theme var 
 */

export var getThemeVar = {
  '@primary-color': '#4477ee',
  '@theme-page-bg': '#ffffff',
  '@theme-header-bg': '#ffffff',
  '@theme-font-family': 'nunitosans',
  '@theme-font-size': '12px',
  '@theme-space-base': '4px',
  '@theme-header-size': '40px',
  '@theme-border-radius': '3px',
  '@theme-box-shadow-state': false
};
//# sourceMappingURL=util.js.map