import _toConsumableArray from "@babel/runtime/helpers/toConsumableArray";
import _slicedToArray from "@babel/runtime/helpers/slicedToArray";
import React, { useState, useEffect } from "react";
import { connect } from "../../../redux";
import shortid from "shortid";
import { i18n } from '@fishx/i18n';
import { set } from "dot-prop-immutable";
import { getActiveElement } from "../../../selectors";
import { Table, Icon } from '@whalecloud/fdx';
import { characterShortId, getDeepPropByKeys } from "../../../utils";

var StaticOptionSettings = function StaticOptionSettings(props) {
  var updateElement = props.updateElement,
      element = props.element,
      sourceKey = props.sourceKey,
      targetKey = props.targetKey;
  var type = element.type;
  var isDependency = sourceKey.indexOf('dependency') > -1; // const { data: { formItemSettings = [] } = {}, type } = element;

  var targetSetting = getDeepPropByKeys(sourceKey.split('.'), element) || {};
  var staticOptions = targetSetting.staticOptions,
      remoteMode = targetSetting.remoteMode;

  if (!staticOptions) {
    staticOptions = targetSetting.options || [];
  }

  var options = targetSetting[targetKey];

  if (isDependency) {
    var _element$data$formSet = element.data.formSettings;
    _element$data$formSet = _element$data$formSet === void 0 ? {} : _element$data$formSet;
    var _element$data$formSet2 = _element$data$formSet.dependency;
    _element$data$formSet2 = _element$data$formSet2 === void 0 ? {} : _element$data$formSet2;
    var _element$data$formSet3 = _element$data$formSet2.source,
        source = _element$data$formSet3 === void 0 ? {} : _element$data$formSet3;
    var key = sourceKey.substring(sourceKey.lastIndexOf('.') + 1);
    var _source$ = source["".concat(key, "_metadata")];
    _source$ = _source$ === void 0 ? {} : _source$;
    var _source$$staticOption = _source$.staticOptions,
        so = _source$$staticOption === void 0 ? [] : _source$$staticOption,
        rm = _source$.remoteMode;
    staticOptions = so;
    remoteMode = rm;
  }

  var valueKey = sourceKey;
  var valueKeyMetaData = !isDependency ? sourceKey : "".concat(sourceKey, "_metadata");
  characterShortId(shortid);

  var uuid = function uuid() {
    return shortid.generate();
  };

  var optionArr = [];

  if (type === 'select') {
    optionArr = staticOptions && staticOptions.map(function (opt) {
      opt.key = uuid();
      return opt;
    });
  } else {
    optionArr = options && options.map(function (opt) {
      opt.key = uuid();
      return opt;
    });
  }

  useEffect(function () {
    hanldeEleUpdate(optionArr);
  }, [remoteMode]);

  var _useState = useState(optionArr || []),
      _useState2 = _slicedToArray(_useState, 2),
      dataSource = _useState2[0],
      setDataSource = _useState2[1];

  var _useState3 = useState(''),
      _useState4 = _slicedToArray(_useState3, 2),
      editingKey = _useState4[0],
      setEditingKey = _useState4[1];

  var _useState5 = useState(false),
      _useState6 = _slicedToArray(_useState5, 2),
      addRowState = _useState6[0],
      setAddRowState = _useState6[1];

  var columns = [{
    title: i18n('PAGEBUIDER_SETTINGS_LABEL'),
    dataIndex: "label",
    width: '45%',
    editable: true,
    editRules: [{
      required: true,
      message: "Please Input label!"
    }]
  }, {
    title: i18n('PAGEBUIDER_SETTINGS_VALUE'),
    dataIndex: "value",
    width: '30%',
    editable: true,
    editRules: [{
      required: true,
      message: "Please Input value!"
    }]
  }, {
    title: i18n('PAGEBUIDER_SETTINGS_OPERATION'),
    dataIndex: "edit",
    width: '25%',
    editable: true,
    render: function render(text, record) {
      return /*#__PURE__*/React.createElement("a", {
        onClick: function onClick() {
          delRow(record.key);
        }
      }, /*#__PURE__*/React.createElement(Icon, {
        type: "delete"
      }));
    },
    editContent: function editContent() {
      return /*#__PURE__*/React.createElement(Icon, {
        type: "edit"
      });
    },
    saveContent: function saveContent() {
      return /*#__PURE__*/React.createElement(Icon, {
        type: "save"
      });
    },
    cancelContent: function cancelContent() {
      return /*#__PURE__*/React.createElement(Icon, {
        type: "stop"
      });
    }
  }];

  var delRow = function delRow(key) {
    var newData = dataSource.filter(function (item) {
      return item.key !== key;
    });
    setDataSource(newData);
    hanldeEleUpdate(newData);
  };

  var addRow = function addRow() {
    var id = uuid();
    var data = dataSource.concat({
      key: id,
      label: "option_".concat(id),
      value: id
    });
    setDataSource(data);
    setEditingKey(id);
    setAddRowState(true);
  };

  var onSaveRowEdit = function onSaveRowEdit(record, newData) {
    setDataSource(newData);
    setEditingKey('');
    hanldeEleUpdate(newData);
  };

  var onCancelRowEdit = function onCancelRowEdit() {
    if (addRowState) {
      dataSource.pop();
      setDataSource(_toConsumableArray(dataSource));
      hanldeEleUpdate(_toConsumableArray(dataSource));
    }

    setAddRowState(false);
  };

  var hanldeEleUpdate = function hanldeEleUpdate(elements) {
    var newOptionArr = elements.map(function (ele) {
      var eleObj = {};
      Object.keys(ele).forEach(function (key) {
        if (key !== 'key') {
          eleObj[key] = ele[key];
        }
      });
      return eleObj;
    });

    if (!isDependency || isDependency && newOptionArr.length > 0) {
      // let newElement = set(element, isDependency ? valueKey : `${valueKey}.options`, newOptionArr);
      var newElement = set(element, isDependency ? valueKey : "".concat(valueKey, ".").concat(targetKey), newOptionArr);

      if (type === 'select') {
        if (remoteMode) {
          isDependency && (newElement = set(newElement, "".concat(valueKeyMetaData, ".remoteMode"), false));
        }

        newElement = set(newElement, "".concat(valueKeyMetaData, ".staticOptions"), newOptionArr);
      }

      updateElement({
        element: newElement
      });
    }
  };

  var footer = function footer() {
    return /*#__PURE__*/React.createElement("a", {
      onClick: addRow
    }, i18n('PAGEBUIDER_SETTINGS_ADD_NEW_OPTION'));
  };

  return /*#__PURE__*/React.createElement("div", null, /*#__PURE__*/React.createElement(Table, {
    columns: columns,
    dataSource: dataSource,
    scroll: {
      y: 180
    },
    editRow: true,
    editingKey: editingKey,
    onSaveRowEdit: onSaveRowEdit,
    onCancelRowEdit: onCancelRowEdit,
    footer: footer,
    className: "formbuild-setting-table"
  }));
};

var mapDispatchToProps = function mapDispatchToProps(dispatch) {
  return {
    updateElement: function updateElement(payload) {
      dispatch({
        type: 'appBuilder/updateAndFlattenElement',
        payload: payload
      });
    }
  };
};

export default connect(function (state) {
  return {
    element: getActiveElement(state)
  };
}, mapDispatchToProps)(StaticOptionSettings);
//# sourceMappingURL=StaticOptionSettings.js.map