import _toConsumableArray from "@babel/runtime/helpers/toConsumableArray";
import _regeneratorRuntime from "@babel/runtime/regenerator";
import _objectSpread from "@babel/runtime/helpers/objectSpread2";
import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator";
import _slicedToArray from "@babel/runtime/helpers/slicedToArray";
import React, { useState, useEffect } from "react";
import { connect } from "../../../redux";
import styled from "styled-components";
import { set, get } from "dot-prop-immutable";
import { i18n } from '@fishx/i18n';
import { Button, SimpleForm as Form, Select, Row, Col, message } from '@whalecloud/fdx';
import { isGroupInput, buildCSSToString, matchCodePrefix } from "../../../utils";
import { getActiveElementWithChildren } from "../../../selectors";
import { getContent } from "../../../selectors";
import ModalAddClass from "./components/ModalAddClass";
import ModalStyleSheet from "./components/ModalStyleSheet";
import SettingStyle from "./components/SettingStyle";
import "./index.module.less";
/**
 * styleSet
 * 设置样式属性
 */

var Option = Select.Option;
var FormContainer = /*#__PURE__*/styled("div", {
  target: "eydx1v0",
  label: "FormContainer"
})({
  padding: 5
}); // const matchDevice = {
//   PC: '桌面端',
//   Mobile: '手机端',
//   Pad: '平板端',
// };
// const matchRootState = {
//   0: '',
//   1: ':hover',
//   2: ':focus',
//   3: ':active'
// }

var Settings = function Settings(props) {
  var updateElement = props.updateElement,
      element = props.element,
      updateCustomStyle = props.updateCustomStyle,
      temporaryStyle = props.temporaryStyle,
      customStyle = props.customStyle,
      deleteTemporaryStyle = props.deleteTemporaryStyle,
      previewDevice = props.previewDevice,
      contentElement = props.contentElement;
  var propName = 'data.className'; // class

  var _useState = useState(''),
      _useState2 = _slicedToArray(_useState, 2),
      temporaryClassName = _useState2[0],
      setTemporaryClassName = _useState2[1];

  var getCurrentClass = get(element, propName);

  var _useState3 = useState(getCurrentClass || ''),
      _useState4 = _slicedToArray(_useState3, 2),
      classValue = _useState4[0],
      setClassValue = _useState4[1]; // other


  var _useState5 = useState([]),
      _useState6 = _slicedToArray(_useState5, 2),
      themeClass = _useState6[0],
      setThemeClass = _useState6[1]; // state(hover/focus等)


  var _useState7 = useState('0'),
      _useState8 = _slicedToArray(_useState7, 2),
      rootState = _useState8[0],
      setRootState = _useState8[1]; // css default


  var _useState9 = useState({}),
      _useState10 = _slicedToArray(_useState9, 2),
      cssDefaultCodeRoot = _useState10[0],
      setCSSDefaultCodeRoot = _useState10[1]; // css hover


  var _useState11 = useState({}),
      _useState12 = _slicedToArray(_useState11, 2),
      cssDefaultCodeRootHover = _useState12[0],
      setCSSDefaultCodeRootHover = _useState12[1]; // css focus


  var _useState13 = useState({}),
      _useState14 = _slicedToArray(_useState13, 2),
      cssDefaultCodeRootFocus = _useState14[0],
      setCSSDefaultCodeRootFocus = _useState14[1]; // css active


  var _useState15 = useState({}),
      _useState16 = _slicedToArray(_useState15, 2),
      cssDefaultCodeRootActive = _useState16[0],
      setCSSDefaultCodeRootActive = _useState16[1];

  var dataSource = {
    rootState: rootState,
    cssDefaultCodeRoot: cssDefaultCodeRoot,
    cssDefaultCodeRootHover: cssDefaultCodeRootHover,
    cssDefaultCodeRootFocus: cssDefaultCodeRootFocus,
    cssDefaultCodeRootActive: cssDefaultCodeRootActive,
    setCSSDefaultCodeRoot: setCSSDefaultCodeRoot,
    setCSSDefaultCodeRootHover: setCSSDefaultCodeRootHover,
    setCSSDefaultCodeRootFocus: setCSSDefaultCodeRootFocus,
    setCSSDefaultCodeRootActive: setCSSDefaultCodeRootActive
  };

  var _useState17 = useState(''),
      _useState18 = _slicedToArray(_useState17, 2),
      tempClass = _useState18[0],
      setTempClass = _useState18[1];

  var _useState19 = useState(false),
      _useState20 = _slicedToArray(_useState19, 2),
      modalStyleSheetVisible = _useState20[0],
      setModalStyleSheetVisible = _useState20[1];

  var _useState21 = useState(false),
      _useState22 = _slicedToArray(_useState21, 2),
      modalAddClassVisible = _useState22[0],
      setModalAddClassVisible = _useState22[1];

  var _Form$useForm = Form.useForm(),
      _Form$useForm2 = _slicedToArray(_Form$useForm, 1),
      form = _Form$useForm2[0]; // 保存class, 把当前效果保存(对应临时样式),方便多次使用


  var handleAddClass = /*#__PURE__*/function () {
    var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(form) {
      var values, customClass, getCustom, getCurrentClassStyle, children, newCustomObj, createCode, headTag, para, node;
      return _regeneratorRuntime.wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              _context.prev = 0;
              _context.next = 3;
              return form.validateFields();

            case 3:
              values = _context.sent;
              customClass = values.customClass;

              if (customClass) {
                _context.next = 8;
                break;
              }

              message.warn(i18n('PAGEBUIDER_SETTINGS_STYLE_INPUT_CLASS'));
              return _context.abrupt("return");

            case 8:
              if (!(JSON.stringify(cssDefaultCodeRoot) === '{}' && JSON.stringify(cssDefaultCodeRootHover) === '{}' && JSON.stringify(cssDefaultCodeRootFocus) === '{}' && JSON.stringify(cssDefaultCodeRootActive) === '{}')) {
                _context.next = 11;
                break;
              }

              message.warn(i18n("PAGEBUIDER_SETTINGS_STYLE_SET_CLASS"));
              return _context.abrupt("return");

            case 11:
              // 生成样式, 先删掉再生成
              getCustom = document.getElementsByClassName('css_custom');
              if (getCustom.length > 0) getCustom[0].remove(); // 获取code

              getCurrentClassStyle = {};
              children = isGroupInput(element.type) ? 'input' : '';

              if (Object.keys(cssDefaultCodeRoot).length > 0) {
                getCurrentClassStyle[".".concat(matchCodePrefix[previewDevice], " .").concat(customClass, " ").concat(children)] = _objectSpread({}, cssDefaultCodeRoot);
              }

              if (Object.keys(cssDefaultCodeRootHover).length > 0) {
                getCurrentClassStyle[".".concat(matchCodePrefix[previewDevice], " .").concat(customClass, ":hover ").concat(children)] = _objectSpread({}, cssDefaultCodeRootHover);
              }

              if (Object.keys(cssDefaultCodeRootFocus).length > 0) {
                getCurrentClassStyle[".".concat(matchCodePrefix[previewDevice], " .").concat(customClass, ":focus ").concat(children)] = _objectSpread({}, cssDefaultCodeRootFocus);
              }

              if (Object.keys(cssDefaultCodeRootActive).length > 0) {
                getCurrentClassStyle[".".concat(matchCodePrefix[previewDevice], " .").concat(customClass, ":active ").concat(children)] = _objectSpread({}, cssDefaultCodeRootActive);
              }

              newCustomObj = _objectSpread(_objectSpread({}, customStyle), getCurrentClassStyle);
              createCode = buildCSSToString(newCustomObj);
              headTag = document.getElementsByTagName("body");
              para = document.createElement("style"); // 创建需要增加的元素节点

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

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

              headTag[0].appendChild(para); // 保存到model

              updateCustomStyle(getCurrentClassStyle, function () {
                message.success(i18n('PAGEBUIDER_SETTINGS_STYLE_SAVE_SUCCESS'));
                setModalAddClassVisible(false);
                openClassEditModal();
              });
              _context.next = 33;
              break;

            case 30:
              _context.prev = 30;
              _context.t0 = _context["catch"](0);
              console.log('add class Failed:', _context.t0);

            case 33:
            case "end":
              return _context.stop();
          }
        }
      }, _callee, null, [[0, 30]]);
    }));

    return function handleAddClass(_x) {
      return _ref.apply(this, arguments);
    };
  }();

  var openClassEditModal = function openClassEditModal() {
    setModalStyleSheetVisible(true);
  }; // state change(default/hover/focus/active)


  var rootChange = function rootChange(flag) {
    setRootState(flag);
  }; // set themeclass


  var updateThemeClass = function updateThemeClass(flag) {
    setThemeClass([].concat(_toConsumableArray(themeClass), [flag]));
  }; // update element


  var updateElementStyle = function updateElementStyle(temporaryCode, temporaryClassName) {
    setTemporaryClassName(temporaryClassName); // 临时样式效果, 先删除，再增加

    var getCurrent = document.getElementsByClassName("css_temporary_".concat(temporaryClassName));
    if (getCurrent.length > 0) getCurrent[0].remove();
    var headTag = document.getElementsByTagName("body");
    var para = document.createElement("style"); // 创建需要增加的元素节点

    para.setAttribute('class', "css_temporary_".concat(temporaryClassName));
    var node = document.createTextNode(temporaryCode); // 创建文本节点

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

    headTag[0].appendChild(para); // 更新class到组件

    var getClass = get(element, propName);
    getClass = getClass || '';

    if (getClass.includes(temporaryClassName)) {
      getClass = getClass.replace(" ".concat(temporaryClassName), '');
    }

    var newElement = set(element, propName, "".concat(getClass, " ").concat(temporaryClassName));
    updateElement({
      element: newElement
    });
  };

  useEffect(function () {
    // 保存device到document
    if (previewDevice) {
      var newElement = set(contentElement, 'data.className', matchCodePrefix[previewDevice]);
      updateElement({
        element: newElement
      });
    }

    if (previewDevice && !classValue.trim()) {
      // 清空(setting, class), 不匹配，清掉
      var newElements = set(element, 'data.className', '');
      updateElement({
        element: newElements
      });
      setCSSDefaultCodeRoot({});
      setCSSDefaultCodeRootHover({});
      setCSSDefaultCodeRootFocus({});
      setCSSDefaultCodeRootActive({});
      setTempClass('');
      setClassValue('');
    }
  }, [previewDevice]);
  useEffect(function () {
    var temporaryClasses = classValue ? classValue.trim().split(' ').filter(function (vl) {
      return vl.includes('_css_');
    }) : '';

    if (temporaryClasses.length > 0) {
      var item = Object.keys(temporaryStyle).filter(function (v) {
        return v.includes(".".concat(temporaryClasses[0]));
      })[0];
      var itemHover = Object.keys(temporaryStyle).filter(function (v) {
        return v.includes(".".concat(temporaryClasses[0], ":hover"));
      })[0];
      var itemFocus = Object.keys(temporaryStyle).filter(function (v) {
        return v.includes(".".concat(temporaryClasses[0], ":focus"));
      })[0];
      var itemActive = Object.keys(temporaryStyle).filter(function (v) {
        return v.includes(".".concat(temporaryClasses[0], ":active"));
      })[0];

      if (itemHover) {
        setCSSDefaultCodeRootHover(temporaryStyle[itemHover]);
        setTempClass(temporaryClasses[0]);
      } else if (itemFocus) {
        setCSSDefaultCodeRootFocus(temporaryStyle[itemFocus]);
        setTempClass(temporaryClasses[0]);
      } else if (itemActive) {
        setCSSDefaultCodeRootActive(temporaryStyle[itemActive]);
        setTempClass(temporaryClasses[0]);
      } else if (item) {
        setCSSDefaultCodeRoot(temporaryStyle[item]);
        setTempClass(temporaryClasses[0]);
      }
    }
  }, [temporaryStyle]);
  return /*#__PURE__*/React.createElement(FormContainer, {
    className: "formbuild-style-wrap"
  }, /*#__PURE__*/React.createElement(Row, null, /*#__PURE__*/React.createElement(Col, {
    style: {
      paddingLeft: 5
    }
  }, i18n('PAGEBUIDER_SETTINGS_STYLE_STATE'), "\uFF1A", /*#__PURE__*/React.createElement(Select, {
    style: {
      width: 100
    },
    defaultValue: "0",
    onChange: rootChange
  }, /*#__PURE__*/React.createElement(Option, {
    value: "0"
  }, i18n('PAGEBUIDER_SETTINGS_STYLE_STATE_DEFAULT')), /*#__PURE__*/React.createElement(Option, {
    value: "1"
  }, ":hover"), /*#__PURE__*/React.createElement(Option, {
    value: "2"
  }, ":focus"), /*#__PURE__*/React.createElement(Option, {
    value: "3"
  }, ":active")))), /*#__PURE__*/React.createElement(SettingStyle, {
    mode: "element",
    updateThemeClass: updateThemeClass // updateCSSCode={value => setCSSCode(value)}
    ,
    updateElementStyle: updateElementStyle,
    dataSource: dataSource,
    tempClass: tempClass
  }), /*#__PURE__*/React.createElement(Button, {
    className: "mb-6",
    onClick: function onClick() {
      return setModalAddClassVisible(true);
    }
  }, i18n('PAGEBUIDER_SETTINGS_STYLE_SAVE_CLASS')), /*#__PURE__*/React.createElement(ModalAddClass, {
    form: form,
    visible: modalAddClassVisible,
    handleModalVisible: setModalAddClassVisible,
    handleFormSubmit: handleAddClass
  }), /*#__PURE__*/React.createElement(ModalStyleSheet, {
    visible: modalStyleSheetVisible,
    handleModalVisible: setModalStyleSheetVisible
  }));
};

var mapDispatchToProps = function mapDispatchToProps(dispatch) {
  return {
    updateElement: function updateElement(payload) {
      dispatch({
        type: 'appBuilder/updateAndFlattenElement',
        payload: payload
      });
    },
    updateCustomStyle: function updateCustomStyle(payload, callback) {
      dispatch({
        type: 'style/updateCustomStyle',
        payload: payload
      }).then(function (returnData) {
        if (returnData) callback();
      });
    },
    deleteTemporaryStyle: function deleteTemporaryStyle(payload) {
      dispatch({
        type: 'style/deleteTemporaryStyle',
        payload: payload
      });
    }
  };
};

export default connect(function (state) {
  return {
    element: getActiveElementWithChildren(state),
    temporaryStyle: state.style.temporaryStyle,
    customStyle: state.style.customStyle,
    previewDevice: state.ui.previewDevice,
    contentElement: getContent(state)
  };
}, mapDispatchToProps)(Settings);
//# sourceMappingURL=Settings.js.map