import _defineProperty from "@babel/runtime/helpers/defineProperty";
import _toConsumableArray from "@babel/runtime/helpers/toConsumableArray";
import _objectSpread from "@babel/runtime/helpers/objectSpread2";
import _slicedToArray from "@babel/runtime/helpers/slicedToArray";
import React, { useState, useEffect, useRef } from "react";
import { Modal, Button, Spin, Tabs, Row, Col, message } from '@whalecloud/fdx';
import { i18n } from '@fishx/i18n';
import { ControlledEditor } from "@monaco-editor/react";
import { cssDecode, buildCSSToString, cssToJson, strFormat } from "../../../../../utils";
import { connect } from "../../../../../redux";
import { getActiveElementWithChildren } from "../../../../../selectors";
import SettingStyle from "../SettingStyle";
import "../../index.module.less";
var TabPane = Tabs.TabPane;

var ModalStyleSheet = function ModalStyleSheet(props) {
  var currentClassState = useRef(null);
  var pageCurrentClassState = useRef(null);
  var visible = props.visible,
      customStyle = props.customStyle,
      updatePageStyle = props.updatePageStyle,
      currentPage = props.currentPage,
      currentBlock = props.currentBlock,
      pageStyle = props.pageStyle,
      handleModalVisible = props.handleModalVisible,
      updateCustomStyle = props.updateCustomStyle,
      element = props.element,
      updateElement = props.updateElement;

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

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

  var _useState5 = useState([]),
      _useState6 = _slicedToArray(_useState5, 2),
      themeClass = _useState6[0],
      setThemeClass = _useState6[1]; // const [activeKey, setActiveKey] = useState('2');
  // 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),
      currentClass = _useState18[0],
      setCurrentClass = _useState18[1];

  var _useState19 = useState(true),
      _useState20 = _slicedToArray(_useState19, 2),
      maskVisible = _useState20[0],
      setMaskVisible = _useState20[1];

  var _useState21 = useState(''),
      _useState22 = _slicedToArray(_useState21, 2),
      editorCode = _useState22[0],
      setEditorCode = _useState22[1]; // page
  // css default


  var _useState23 = useState({}),
      _useState24 = _slicedToArray(_useState23, 2),
      cssPageDefaultCodeRoot = _useState24[0],
      setPageCSSDefaultCodeRoot = _useState24[1]; // css hover


  var _useState25 = useState({}),
      _useState26 = _slicedToArray(_useState25, 2),
      cssPageDefaultCodeRootHover = _useState26[0],
      setPageCSSDefaultCodeRootHover = _useState26[1]; // css focus


  var _useState27 = useState({}),
      _useState28 = _slicedToArray(_useState27, 2),
      cssPageDefaultCodeRootFocus = _useState28[0],
      setPageCSSDefaultCodeRootFocus = _useState28[1]; // css active


  var _useState29 = useState({}),
      _useState30 = _slicedToArray(_useState29, 2),
      cssPageDefaultCodeRootActive = _useState30[0],
      setPageCSSDefaultCodeRootActive = _useState30[1];

  var pageDataSource = {
    rootState: rootState,
    cssPageDefaultCodeRoot: cssPageDefaultCodeRoot,
    cssPageDefaultCodeRootHover: cssPageDefaultCodeRootHover,
    cssPageDefaultCodeRootFocus: cssPageDefaultCodeRootFocus,
    cssPageDefaultCodeRootActive: cssPageDefaultCodeRootActive,
    setPageCSSDefaultCodeRoot: setPageCSSDefaultCodeRoot,
    setPageCSSDefaultCodeRootHover: setPageCSSDefaultCodeRootHover,
    setPageCSSDefaultCodeRootFocus: setPageCSSDefaultCodeRootFocus,
    setPageCSSDefaultCodeRootActive: setPageCSSDefaultCodeRootActive
  };

  var _useState31 = useState(''),
      _useState32 = _slicedToArray(_useState31, 2),
      pageCurrentClass = _useState32[0],
      setPageCurrentClass = _useState32[1];

  var _useState33 = useState(true),
      _useState34 = _slicedToArray(_useState33, 2),
      pageMaskVisible = _useState34[0],
      setPageMaskVisible = _useState34[1];

  var _useState35 = useState(''),
      _useState36 = _slicedToArray(_useState35, 2),
      pageEditorCode = _useState36[0],
      setPageEditorCode = _useState36[1];

  var _useState37 = useState('2'),
      _useState38 = _slicedToArray(_useState37, 2),
      tabCurrentKey = _useState38[0],
      setTabCurrentKey = _useState38[1];

  useEffect(function () {
    if (Object.keys(customStyle).length > 0 && Object.keys(customStyle)[0]) {
      var code = buildCSSToString(customStyle);
      setCSSCode(code);
    }

    if (currentClass) {
      setCSSDefaultCodeRoot(customStyle[currentClass]);
      setCSSDefaultCodeRootHover({});
      setCSSDefaultCodeRootFocus({});
      setCSSDefaultCodeRootActive({});
    }
  }, [customStyle]);
  useEffect(function () {
    if (Object.keys(pageStyle).length > 0 && Object.keys(pageStyle)[0]) {
      var code = buildCSSToString(null, null, pageStyle);
      setPageCSSCode(code);
    }

    if (pageCurrentClass) {
      setPageCSSDefaultCodeRoot(pageStyle[pageCurrentClass]);
      setPageCSSDefaultCodeRootHover({});
      setPageCSSDefaultCodeRootFocus({});
      setPageCSSDefaultCodeRootActive({});
    }
  }, [pageStyle]);
  useEffect(function () {
    if (!visible) {
      setMaskVisible(true);
      setPageMaskVisible(true);
    }
  }, [visible]);

  var handleEditorDidMount = function handleEditorDidMount(_valueGetter, _s) {
    _s.onDidBlurEditorText(function (e) {});

    _s.onDidChangeCursorPosition(function (e) {
      var lineNumber = e.position.lineNumber,
          source = e.source;
      if (source === 'keyboard') return;
      var b = {
        line: 0,
        state: ''
      };
      var a = {
        line: 0,
        state: ''
      };

      for (var i = lineNumber; i > 0; i--) {
        var item = _s.getModel().getLineContent(i).trim();

        if (item.includes('{')) {
          if (!b.state) {
            b.line = i;
            b.state = 'before';
          }
        } else if (item.includes('}')) {
          if (!a.state) {
            a.line = i;
            a.state = 'after';
          }
        }
      }

      if (!a.state && b.state && lineNumber > b.line || a.state && b.state && lineNumber > b.line && b.line > a.line) {
        setMaskVisible(false);
        currentClassState.current = false;

        var currentItem = _s.getModel().getLineContent(b.line).trim();

        currentItem = currentItem.replace(' {', ' ');
        var jsonCode = cssToJson(editorCode);
        var getCurrentStyle = customStyle[currentItem] || jsonCode[currentItem];
        setCSSDefaultCodeRoot(_objectSpread({}, getCurrentStyle));
        setCSSDefaultCodeRootHover({});
        setCSSDefaultCodeRootFocus({});
        setCSSDefaultCodeRootActive({});
        setCurrentClass(currentItem);
      } else {
        setMaskVisible(true);
        currentClassState.current = true;
      }

      if (source === 'model') {
        setMaskVisible(false);
      }
    });

    _s.onDidFocusEditorText(function (e, t, i) {
      if (!cssCode) {
        setMaskVisible(false);
      }
    });
  }; // set themeclass


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

  var maskBox = function maskBox() {
    return /*#__PURE__*/React.createElement("div", {
      className: "formbuild-style-mask",
      style: {
        display: maskVisible ? 'block' : 'none'
      }
    });
  };

  var pageMaskBox = function pageMaskBox() {
    return /*#__PURE__*/React.createElement("div", {
      className: "formbuild-style-mask",
      style: {
        display: pageMaskVisible ? 'block' : 'none'
      }
    });
  };

  var closeModal = function closeModal() {
    if (currentClass) {
      // 先删除
      var getCustom = document.getElementsByClassName('css_custom');
      if (getCustom.length > 0) getCustom[0].remove(); // 获取code

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

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

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

      headTag[0].appendChild(para);
    }

    if (pageCurrentClass) {
      // 先删除
      var getPage = document.getElementsByClassName('css_page');
      if (getPage.length > 0) getPage[0].remove(); // 获取code

      var jsonPageCode = cssToJson(pageEditorCode);
      var createPageCode = buildCSSToString({}, {}, jsonPageCode);
      var pageHeadTag = document.getElementsByTagName("body");
      var pagePara = document.createElement("style"); // 创建需要增加的元素节点

      pagePara.setAttribute('class', 'css_page');

      var _node = document.createTextNode(createPageCode); // 创建文本节点


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

      pageHeadTag[0].appendChild(pagePara);
    }

    handleModalVisible(false);
  };

  var handleEditorChange = function handleEditorChange(ev, value) {
    setEditorCode(value);
  };

  var handleSave = function handleSave() {
    // 右侧设置面板保存过不需要保存
    if (strFormat(editorCode).length < strFormat(cssCode).length && tabCurrentKey === '1') {
      handleModalVisible(false);
      return;
    }

    if (strFormat(pageEditorCode).length < strFormat(pageCSSCode).length && tabCurrentKey === '0') {
      handleModalVisible(false);
      return;
    } // custom


    var jsonCode = cssToJson(editorCode);
    var curClass = Object.keys(customStyle).filter(function (v) {
      return v = currentClass;
    });

    if (curClass.length > 0) {
      updateCustomStyle(_defineProperty({}, curClass[0], jsonCode[currentClass.trim()]));
    } else if (currentClass) {
      updateCustomStyle(_defineProperty({}, currentClass, jsonCode[currentClass.trim()]));
    } // page


    var jsonPageCode = cssToJson(pageEditorCode);
    var curPageClass = Object.keys(pageStyle).filter(function (v) {
      return v === pageCurrentClass;
    });

    if (curPageClass.length > 0) {
      updatePageStyle(_defineProperty({}, curPageClass[0], jsonPageCode[pageCurrentClass.trim()]));
    } else if (pageCurrentClass) {
      updatePageStyle(_defineProperty({}, pageCurrentClass, jsonPageCode[pageCurrentClass.trim()]));
    }

    closeModal();
  }; // page


  var handlePageEditorDidMount = function handlePageEditorDidMount(_valueGetter, _s) {
    _s.onDidBlurEditorText(function (e) {});

    _s.onDidChangeCursorPosition(function (e) {
      var lineNumber = e.position.lineNumber,
          source = e.source;
      if (source === 'keyboard') return;
      var b = {
        line: 0,
        state: ''
      };
      var a = {
        line: 0,
        state: ''
      };

      for (var i = lineNumber; i > 0; i--) {
        var item = _s.getModel().getLineContent(i).trim();

        if (item.includes('{')) {
          if (!b.state) {
            b.line = i;
            b.state = 'before';
          }
        } else if (item.includes('}')) {
          if (!a.state) {
            a.line = i;
            a.state = 'after';
          }
        }
      }

      if (!a.state && b.state && lineNumber > b.line || a.state && b.state && lineNumber > b.line && b.line > a.line) {
        setPageMaskVisible(false);
        pageCurrentClassState.current = false;

        var currentItem = _s.getModel().getLineContent(b.line).trim();

        currentItem = currentItem.replace(' {', ' ');
        var jsonPageCode = cssToJson(pageEditorCode);
        var getPageCurrentStyle = pageStyle[currentItem] || jsonPageCode[currentItem];
        setPageCSSDefaultCodeRoot(_objectSpread({}, getPageCurrentStyle));
        setPageCSSDefaultCodeRootHover({});
        setPageCSSDefaultCodeRootFocus({});
        setPageCSSDefaultCodeRootActive({});
        setPageCurrentClass(currentItem);
      } else {
        setPageMaskVisible(true);
        pageCurrentClassState.current = true;
      }

      if (source === 'model') {
        setPageMaskVisible(false);
      }
    });

    _s.onDidFocusEditorText(function (e, t, i) {
      if (!cssCode) {
        setPageMaskVisible(false);
      }
    });
  };

  var handlePageEditorChange = function handlePageEditorChange(ev, value) {
    setPageEditorCode(value);
  };

  return /*#__PURE__*/React.createElement(Modal, {
    title: i18n('PAGEBUILDER_STYLE_STYLESHEET'),
    visible: visible,
    width: 1000,
    onCancel: closeModal,
    footer: [/*#__PURE__*/React.createElement(Button, {
      key: "btn",
      type: "primary",
      onClick: handleSave
    }, i18n('PAGEBUIDER_ELEMENT_SAVE'))],
    className: "formbuild-style-modal",
    destroyOnClose: true
  }, /*#__PURE__*/React.createElement(Tabs, {
    defaultActiveKey: "1",
    onChange: function onChange(v) {
      return setTabCurrentKey(v);
    }
  }, (currentPage || currentBlock) && /*#__PURE__*/React.createElement(TabPane, {
    tab: i18n('PAGEBUILDER_STYLE_PAGE_STYLE'),
    key: "0"
  }, /*#__PURE__*/React.createElement(Row, null, /*#__PURE__*/React.createElement(Col, {
    span: 16,
    style: {
      height: 400,
      borderRight: '1px solid #ddd',
      position: 'relative'
    }
  }, /*#__PURE__*/React.createElement(ControlledEditor, {
    className: "formbuild-style-editorWrap",
    options: {
      lineNumbers: "off",
      roundedSelection: false
    },
    theme: 'light',
    language: 'css',
    loading: /*#__PURE__*/React.createElement(Spin, null),
    value: cssDecode(pageCSSCode),
    editorDidMount: handlePageEditorDidMount,
    onChange: handlePageEditorChange
  })), /*#__PURE__*/React.createElement(Col, {
    span: 8,
    style: {
      height: 400
    }
  }, /*#__PURE__*/React.createElement("div", {
    style: {
      height: '100%',
      overflow: 'auto',
      position: 'relative'
    }
  }, /*#__PURE__*/React.createElement(SettingStyle, {
    mode: "styleSheet",
    updateThemeClass: updateThemeClass,
    dataSource: pageDataSource,
    pageCurrentClass: pageCurrentClass
  })), pageMaskBox()))), /*#__PURE__*/React.createElement(TabPane, {
    tab: i18n('PAGEBUILDER_STYLE_PRODUCT_STYLE'),
    key: "1"
  }, /*#__PURE__*/React.createElement(Row, null, /*#__PURE__*/React.createElement(Col, {
    span: 16,
    style: {
      height: 400,
      borderRight: '1px solid #ddd',
      position: 'relative'
    }
  }, /*#__PURE__*/React.createElement(ControlledEditor, {
    className: "formbuild-style-editorWrap",
    options: {
      lineNumbers: "off",
      roundedSelection: false
    },
    theme: 'light',
    language: 'css',
    loading: /*#__PURE__*/React.createElement(Spin, null),
    value: cssDecode(cssCode),
    editorDidMount: handleEditorDidMount,
    onChange: handleEditorChange
  })), /*#__PURE__*/React.createElement(Col, {
    span: 8,
    style: {
      height: 400
    }
  }, /*#__PURE__*/React.createElement("div", {
    style: {
      height: '100%',
      overflow: 'auto',
      position: 'relative'
    }
  }, /*#__PURE__*/React.createElement(SettingStyle, {
    mode: "styleSheet",
    updateThemeClass: updateThemeClass,
    dataSource: dataSource,
    currentClass: currentClass
  })), maskBox())))));
};

var mapDispatchToProps = function mapDispatchToProps(dispatch) {
  return {
    updateElement: function updateElement(payload) {
      dispatch({
        type: 'appBuilder/updateAndFlattenElement',
        payload: payload
      });
    },
    updateCustomStyle: function updateCustomStyle(payload) {
      dispatch({
        type: 'style/updateCustomStyle',
        payload: payload
      }).then(function (returnData) {
        if (returnData) message.success('代码保存成功。');
      });
    },
    updatePageStyle: function updatePageStyle(payload) {
      dispatch({
        type: 'style/updatePageStyle',
        payload: payload
      });
    }
  };
};

export default connect(function (state) {
  var _state$appBuilder$con, _state$appBuilder$con2;

  return {
    element: getActiveElementWithChildren(state),
    customStyle: state.style.customStyle,
    pageStyle: state.style.pageStyle,
    currentPage: (_state$appBuilder$con = state.appBuilder.config) === null || _state$appBuilder$con === void 0 ? void 0 : _state$appBuilder$con.currentPage,
    currentBlock: (_state$appBuilder$con2 = state.appBuilder.config) === null || _state$appBuilder$con2 === void 0 ? void 0 : _state$appBuilder$con2.currentBlock
  };
}, mapDispatchToProps)(ModalStyleSheet);
//# sourceMappingURL=index.js.map