import _inheritsLoose from "@babel/runtime/helpers/inheritsLoose";
import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator";
import _regeneratorRuntime from "@babel/runtime/regenerator";
import * as React from "react";
import { useEffect, useState, Suspense, PureComponent, useRef } from "react";
import { PluginMode, EntrySchema, Entry } from "@cverse/core-lib-beta";
import { applyVueInReact } from "veaury";
import { CLowCodeService } from "../../utils/CLowCodeService";
import VueComp from "./index.vue";
import { getChildrenComponentKey, getMd5Data, getValueByLang, isEffectiveEventFlow } from "../../utils/comfn/util";
import { groupSubService } from "../../utils/comfn/groupSubService";
import { PageStateFlag } from "lowcode/_utils/treeDataRelationFn/type";
import { EngineRuleBeforeFlag } from "lowcode/_utils/utils";
import { checkMultiRuleNode } from "lowcode/_setters/cFlowEvent-setter/page/utils";
import { handleDictionaryData } from "../../utils/comfn/getLangByDictionary";
//打包
var ReactComp = applyVueInReact(VueComp);
var EngineRuleUltra = function EngineRuleUltra(props) {
  var _entrySchemaPro$entry;
  var __designMode = props.__designMode,
    flowEventConfig = props.flowEventConfig,
    ruleNodeGroupConfig = props.ruleNodeGroupConfig,
    componentKey = props.componentKey;
  var initEntrySchema = new EntrySchema();
  var cLowCodeService = new CLowCodeService();

  // 执行事件流到规则之前的内容生成hash
  var _useState = useState(""),
    ruleResultHash = _useState[0],
    setRuleResultHash = _useState[1];
  var _useState2 = useState(initEntrySchema),
    entrySchemaPro = _useState2[0],
    setEntrySchemaPro = _useState2[1];
  var _useState3 = useState(false),
    multiRule = _useState3[0],
    setMultiRule = _useState3[1];
  var executeFlowRef = useRef();
  useEffect(function () {
    if (__designMode !== "design" && isEffectiveEventFlow(props.flowEventConfig)) {
      var isMultiRule = checkMultiRuleNode(props.flowEventConfig);
      setMultiRule(isMultiRule);
      getFlowEventResultHash().then(function (res) {
        changeEntryData(res);
      });
    }
  }, []);
  useEffect(function () {
    // 如果是编辑态 整理出entry
    if (__designMode === "design") {
      setEntrySchemaProDesign();
    }
    // 预览态执行
    if (__designMode !== "design" && multiRule) {
      getFlowEventResultHash().then(function (res) {
        if (res.hash && res.hash !== ruleResultHash) {
          changeEntryData(res);
        }
      });
    }
  }, [props]);
  function changeEntryData(res) {
    var hash = res.hash,
      data = res.data;
    executeFlowRef.current = data;
    var preEntrySchema = getEntrySchema(data);
    setRuleResultHash(hash);
    setEntrySchemaPro(preEntrySchema);
  }
  function setEntrySchemaProDesign() {
    var _props$ruleNodeGroupC;
    var _entrySchema = new EntrySchema();
    if ((_props$ruleNodeGroupC = props.ruleNodeGroupConfig) !== null && _props$ruleNodeGroupC !== void 0 && _props$ruleNodeGroupC.ruleGroupId) {
      var _entry = new Entry();
      var _props$ruleNodeGroupC2 = props.ruleNodeGroupConfig.ruleConfig.config,
        viewKey = _props$ruleNodeGroupC2.viewKey,
        pageKey = _props$ruleNodeGroupC2.pageKey,
        pbiId = _props$ruleNodeGroupC2.pbiId,
        ruleId = _props$ruleNodeGroupC2.ruleId;
      _entry.viewKey = viewKey;
      _entry.pageKey = pageKey;
      if (ruleId) {
        _entry.ruleId = ruleId;
      }
      _entry.json = getEntryJson();
      _entrySchema.entry = _entry;
      setEntrySchemaPro(_entrySchema);
    }
  }
  function getEntryJson() {
    var _entryJson = {};
    var textKeys = [{
      key: 'buttonText',
      dictionaryKey: 'buttonTextDictionaryKey'
    }, {
      key: 'buttonLoadingText',
      dictionaryKey: 'buttonLoadingTextDictionaryKey'
    }, {
      key: 'buttonExecutingText',
      dictionaryKey: 'buttonExecutingTextDictionaryKey'
    }, {
      key: 'buttonWalletNotConnectedText',
      dictionaryKey: 'buttonWalletNotConnectedTextDictionaryKey'
    }];
    textKeys.forEach(function (item) {
      _entryJson[item.key] = props[item.dictionaryKey] ? handleDictionaryData(props[item.key], props[item.dictionaryKey], props.webGid) : props[item.key];
    });
    var keys = ["buttonText", "buttonLoadingText", "buttonExecutingText", "buttonWalletNotConnectedText", "inputCheckSwitch", "stepQueryPopSwitch", "style"];
    var specialKeyMap = {
      ruleLoadingStyle: 'loadingStyle',
      ruleHoverStyle: 'hoverStyle',
      ruleActiveStyle: 'activeStyle',
      ruleExecutingStyle: 'executingStyle',
      ruleDisableStyle: 'disableStyle',
      ruleTipStyle: 'tipStyle',
      ruleWalletNotConnectedStyle: 'walletNotConnectedStyle'
    };
    keys.forEach(function (key) {
      if (!_entryJson[key] && props !== null && props !== void 0 && props[key]) {
        _entryJson[key] = props[key];
      }
    });
    Object.keys(specialKeyMap).forEach(function (key) {
      if (props !== null && props !== void 0 && props[key]) {
        _entryJson[specialKeyMap[key]] = props[key];
      }
    });
    return _entryJson;
  }
  function getEntrySchema(res) {
    var result = initEntrySchema;
    if (res !== null && res !== void 0 && res.ruleInfo) {
      var info = res.ruleInfo;
      result.entry = {
        projectIdList: [info.projectId],
        pageKey: info.pageKey,
        viewKey: info.viewKey,
        ruleId: info === null || info === void 0 ? void 0 : info.ruleId,
        flowEventCallbackPre: preEventCallbackBeforeFn,
        flowEventCallbackBefore: flowEventCallbackBeforeFn,
        flowEventCallbackAfter: flowEventCallbackAfterFn,
        groupIndexCallback: groupIndexCallback,
        json: getEntryJson()
      };
    }
    return result;
  }
  function getFlowEventResultHash() {
    return _getFlowEventResultHash.apply(this, arguments);
  }
  function _getFlowEventResultHash() {
    _getFlowEventResultHash = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee5() {
      var result, res;
      return _regeneratorRuntime.wrap(function _callee5$(_context5) {
        while (1) switch (_context5.prev = _context5.next) {
          case 0:
            cLowCodeService.loadPageProps(props);
            _context5.next = 3;
            return cLowCodeService.handleFlowEvent(flowEventConfig);
          case 3:
            res = _context5.sent;
            if (res && res.flowResult.code === 200) {
              result = getMd5Data(res);
            }
            return _context5.abrupt("return", {
              hash: result,
              data: res
            });
          case 6:
          case "end":
            return _context5.stop();
        }
      }, _callee5);
    }));
    return _getFlowEventResultHash.apply(this, arguments);
  }
  var preEventCallbackBeforeFn = /*#__PURE__*/function () {
    var _ref = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee() {
      var _executeFlowRef$curre;
      var preFlowEventConfig, res;
      return _regeneratorRuntime.wrap(function _callee$(_context) {
        while (1) switch (_context.prev = _context.next) {
          case 0:
            preFlowEventConfig = executeFlowRef === null || executeFlowRef === void 0 ? void 0 : (_executeFlowRef$curre = executeFlowRef.current) === null || _executeFlowRef$curre === void 0 ? void 0 : _executeFlowRef$curre.preFlowNode;
            _context.next = 3;
            return flowEventComFn(preFlowEventConfig);
          case 3:
            res = _context.sent;
            console.log("flowEventCallbackPre-res", res);
            return _context.abrupt("return", res);
          case 6:
          case "end":
            return _context.stop();
        }
      }, _callee);
    }));
    return function preEventCallbackBeforeFn() {
      return _ref.apply(this, arguments);
    };
  }();
  var flowEventCallbackBeforeFn = /*#__PURE__*/function () {
    var _ref2 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee2() {
      var _executeFlowRef$curre2;
      var beforeFlowEventConfig, res;
      return _regeneratorRuntime.wrap(function _callee2$(_context2) {
        while (1) switch (_context2.prev = _context2.next) {
          case 0:
            beforeFlowEventConfig = executeFlowRef === null || executeFlowRef === void 0 ? void 0 : (_executeFlowRef$curre2 = executeFlowRef.current) === null || _executeFlowRef$curre2 === void 0 ? void 0 : _executeFlowRef$curre2.beforeFlowNode;
            _context2.next = 3;
            return flowEventComFn(beforeFlowEventConfig);
          case 3:
            res = _context2.sent;
            console.log("flowEventCallbackBefore-res", res);
            return _context2.abrupt("return", res);
          case 6:
          case "end":
            return _context2.stop();
        }
      }, _callee2);
    }));
    return function flowEventCallbackBeforeFn() {
      return _ref2.apply(this, arguments);
    };
  }();
  var flowEventCallbackAfterFn = /*#__PURE__*/function () {
    var _ref3 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee3() {
      var _executeFlowRef$curre3;
      var afterFlowEventConfig;
      return _regeneratorRuntime.wrap(function _callee3$(_context3) {
        while (1) switch (_context3.prev = _context3.next) {
          case 0:
            console.log("flowEventCallbackAfterFn-res", executeFlowRef.current);
            afterFlowEventConfig = executeFlowRef === null || executeFlowRef === void 0 ? void 0 : (_executeFlowRef$curre3 = executeFlowRef.current) === null || _executeFlowRef$curre3 === void 0 ? void 0 : _executeFlowRef$curre3.afterFlowNode;
            _context3.next = 4;
            return flowEventComFn(afterFlowEventConfig, false);
          case 4:
          case "end":
            return _context3.stop();
        }
      }, _callee3);
    }));
    return function flowEventCallbackAfterFn() {
      return _ref3.apply(this, arguments);
    };
  }();
  var groupIndexCallback = function groupIndexCallback(config) {
    console.log("groupIndexCallback-res", config);
    if (executeFlowRef.current === undefined) {
      console.error("executeFlow is undefined");
      return;
    }
    cLowCodeService.loadPageProps(props);
    var groupIds = getGroupIds(executeFlowRef.current);
    if (groupIds) {
      groupIds.forEach(function (groupId) {
        var configObj = {
          groupId: groupId,
          groupIndex: config.code,
          state: config.state
        };
        if (config.followState) {
          configObj.followState = config.followState;
        }
        var key = getChildrenComponentKey(props.webGid, groupId);
        groupSubService.publishGroupData(key, configObj);
      });
      var alterKey = getAlterKeyByConfig(config);
      var alterValue = getAlterValueByConfig(config);
      cLowCodeService.setPageStateData(alterKey, alterValue, PageStateFlag.EngineRule);
    }
  };
  function getAlterKeyByConfig(config) {
    return componentKey + "." + EngineRuleBeforeFlag + config.code + "." + EngineRuleBeforeFlag + config.state;
  }
  function getAlterValueByConfig(config) {
    var result = config;
    if (config.msg) {
      result.msg = getValueByLang(config.msg);
    }
    return result;
  }
  function getGroupIds(data) {
    var _data$ruleInfo;
    var result = [];
    if ((_data$ruleInfo = data.ruleInfo) !== null && _data$ruleInfo !== void 0 && _data$ruleInfo.groupIds) {
      result = data.ruleInfo.groupIds;
    }
    return result;
  }
  function handleParams() {
    var _executeFlowRef$curre4, _executeFlowRef$curre5;
    var result;
    // 每次都重新计算
    if (__designMode !== "design" && executeFlowRef !== null && executeFlowRef !== void 0 && (_executeFlowRef$curre4 = executeFlowRef.current) !== null && _executeFlowRef$curre4 !== void 0 && (_executeFlowRef$curre5 = _executeFlowRef$curre4.ruleInfo) !== null && _executeFlowRef$curre5 !== void 0 && _executeFlowRef$curre5.apiParams) {
      cLowCodeService.loadPageProps(props);
      result = cLowCodeService.getStateDataByTree(executeFlowRef === null || executeFlowRef === void 0 ? void 0 : executeFlowRef.current.ruleInfo.apiParams);
    }
    return result;
  }
  var flowEventComFn = /*#__PURE__*/function () {
    var _ref4 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee4(config, isParams) {
      var result, res;
      return _regeneratorRuntime.wrap(function _callee4$(_context4) {
        while (1) switch (_context4.prev = _context4.next) {
          case 0:
            if (isParams === void 0) {
              isParams = true;
            }
            result = {
              code: 500,
              data: undefined,
              msg: "error"
            };
            if (!config) {
              _context4.next = 8;
              break;
            }
            cLowCodeService.loadPageProps(props);
            _context4.next = 6;
            return cLowCodeService.handleFlowEvent(config);
          case 6:
            res = _context4.sent;
            if (res) {
              result = res.flowResult;
            }
          case 8:
            // 后置不需要参数
            if (isParams) {
              result.data = handleParams();
            }
            return _context4.abrupt("return", result);
          case 10:
          case "end":
            return _context4.stop();
        }
      }, _callee4);
    }));
    return function flowEventComFn(_x, _x2) {
      return _ref4.apply(this, arguments);
    };
  }();
  if (__designMode === "design" && (entrySchemaPro == undefined || ruleNodeGroupConfig === undefined || ruleNodeGroupConfig.ruleGroupId === undefined || ruleNodeGroupConfig.ruleGroupId === "")) {
    return /*#__PURE__*/React.createElement("div", {
      style: {
        textAlign: "center",
        paddingTop: "10px",
        paddingBottom: "10px"
      }
    }, "Configure the event flow and then select Rule Preview");
  }
  if (!(entrySchemaPro !== null && entrySchemaPro !== void 0 && (_entrySchemaPro$entry = entrySchemaPro.entry) !== null && _entrySchemaPro$entry !== void 0 && _entrySchemaPro$entry.ruleId)) {
    return /*#__PURE__*/React.createElement("div", null);
  }
  return /*#__PURE__*/React.createElement("div", null, /*#__PURE__*/React.createElement(Suspense, {
    fallback: /*#__PURE__*/React.createElement("div", null)
  }, /*#__PURE__*/React.createElement(ReactComp, {
    entry: entrySchemaPro.entry,
    mode: __designMode === "design" ? PluginMode.EmbedEdit : PluginMode.EmbedCall
  })));
};
var _default = /*#__PURE__*/function (_PureComponent) {
  function _default() {
    return _PureComponent.apply(this, arguments) || this;
  }
  _inheritsLoose(_default, _PureComponent);
  var _proto = _default.prototype;
  _proto.render = function render() {
    return /*#__PURE__*/React.createElement(EngineRuleUltra, this.props);
  };
  return _default;
}(PureComponent);
export { _default as default };