import _inheritsLoose from "@babel/runtime/helpers/inheritsLoose";
import _Tab from "@alifd/next/es/tab";
import _Message from "@alifd/next/es/message";
import _NumberPicker from "@alifd/next/es/number-picker";
import _Select from "@alifd/next/es/select";
import _Input from "@alifd/next/es/input";
import _Icon from "@alifd/next/es/icon";
import _Button from "@alifd/next/es/button";
import _Dialog from "@alifd/next/es/dialog";
import _extends from "@babel/runtime/helpers/extends";
import _Grid from "@alifd/next/es/grid";
import _Radio from "@alifd/next/es/radio";
import React, { Component, useEffect, useMemo, useState } from "react";
import "./index.less";
import BoxSlotComponent from "../_components/boxSlotComponent";
import { t } from "../../../src/locale";
import { groupCategoryType, groupClassType, groupModeType } from "./type";
import { createNewGroupItem, createNewGroupListItem, createNewStateListItem, getBaseDataSourceBySchema, getColDataSourceBySchema, getDefaultIndexOptions, getStateListByGroupIndex } from "./commonFn";
import { EngineRuleState } from "../../../src/utils/type";
import { cloneDeep } from "lodash";
var RadioGroup = _Radio.Group;
var Row = _Grid.Row,
  Col = _Grid.Col;
var CGroupManagerSetter = function CGroupManagerSetter(props) {
  var value = props.value,
    onChange = props.onChange;
  var dc;
  var _useState = useState(value || []),
    groupList = _useState[0],
    setGroupList = _useState[1];
  var _useState2 = useState(),
    groupItem = _useState2[0],
    setGroupItem = _useState2[1];
  var _useState3 = useState({
      visible: false,
      type: 'add',
      title: t('page.add')
    }),
    dialogConfig = _useState3[0],
    setDialogConfig = _useState3[1];
  useEffect(function () {
    onChange(groupList);
  }, [groupList]);
  var openAddDialog = function openAddDialog() {
    setDialogConfig({
      visible: true,
      type: 'add',
      title: t('page.add')
    });
    var newGroup = createNewGroupItem();
    setGroupItem(newGroup);
  };
  var removeGroup = function removeGroup(groupId) {
    var _dc;
    setGroupList(groupList.filter(function (item) {
      return item.groupId !== groupId;
    }));
    (_dc = dc) === null || _dc === void 0 ? void 0 : _dc.hide();
  };
  var saveGroupData = function saveGroupData() {
    var newGroupList = groupList || [];
    var nG = [].concat(newGroupList);
    if (groupItem) {
      if (dialogConfig.type === 'add') {
        nG.push(groupItem);
      } else {
        nG = nG.map(function (item) {
          if (item.groupId === groupItem.groupId) {
            return groupItem;
          }
          return item;
        });
      }
      setGroupList(nG);
    }
    closeDialog();
  };
  var closeDialog = function closeDialog() {
    setDialogConfig(_extends({}, dialogConfig, {
      visible: false
    }));
  };
  var onGroupItemChange = function onGroupItemChange(v) {
    setGroupItem(v);
  };
  var alterGroupItem = function alterGroupItem(item) {
    setDialogConfig({
      visible: true,
      type: 'alter',
      title: t('page.alter')
    });
    setGroupItem(cloneDeep(item));
  };
  function removeConfirm(groupId) {
    dc = _Dialog.confirm({
      v2: true,
      title: t("page.removeTip"),
      content: t("page.removeTipTitle"),
      footer: /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(_Button, {
        onClick: function onClick() {
          removeGroup(groupId);
        },
        type: "primary"
      }, t('setter.ok')), /*#__PURE__*/React.createElement(_Button, {
        style: {
          marginLeft: '10px'
        },
        onClick: function onClick() {
          var _dc2;
          (_dc2 = dc) === null || _dc2 === void 0 ? void 0 : _dc2.hide();
        }
      }, t('setter.cancel')))
    });
  }
  return /*#__PURE__*/React.createElement("div", {
    className: "cGroupManager"
  }, /*#__PURE__*/React.createElement("div", {
    className: "group-header"
  }, /*#__PURE__*/React.createElement(_Button, {
    type: "primary",
    onClick: openAddDialog
  }, t("page.add"))), groupList.length > 0 && /*#__PURE__*/React.createElement("div", {
    className: "group-body"
  }, groupList.map(function (item) {
    return /*#__PURE__*/React.createElement("div", {
      className: "group-body-item",
      style: {
        cursor: 'pointer'
      },
      onClick: function onClick() {
        alterGroupItem(item);
      }
    }, /*#__PURE__*/React.createElement(Row, null, /*#__PURE__*/React.createElement(Col, {
      span: "24"
    }, /*#__PURE__*/React.createElement("div", {
      className: "group-btn"
    }, /*#__PURE__*/React.createElement(_Icon, {
      style: {
        cursor: 'pointer'
      },
      type: "edit",
      onClick: function onClick() {
        alterGroupItem(item);
      }
    }), /*#__PURE__*/React.createElement(_Icon, {
      style: {
        cursor: 'pointer',
        marginLeft: "10px"
      },
      type: "ashbin",
      onClick: function onClick(e) {
        e.stopPropagation();
        removeConfirm(item.groupId);
      }
    })))), /*#__PURE__*/React.createElement(Row, {
      className: "group-row"
    }, /*#__PURE__*/React.createElement(Col, {
      span: "4"
    }, " ", /*#__PURE__*/React.createElement("div", null, " ", t("page.groupId"), ":")), /*#__PURE__*/React.createElement(Col, {
      span: "20"
    }, " ", item.groupId)), /*#__PURE__*/React.createElement(Row, {
      className: "group-row"
    }, /*#__PURE__*/React.createElement(Col, {
      span: "4"
    }, " ", /*#__PURE__*/React.createElement("div", null, " ", t("page.groupName"), ":")), /*#__PURE__*/React.createElement(Col, {
      span: "20"
    }, "  ", /*#__PURE__*/React.createElement("div", {
      className: "groupName"
    }, item.groupName))), /*#__PURE__*/React.createElement(Row, {
      className: "group-row"
    }, /*#__PURE__*/React.createElement(Col, {
      span: "12"
    }, /*#__PURE__*/React.createElement(Row, null, /*#__PURE__*/React.createElement(Col, {
      span: "8"
    }, /*#__PURE__*/React.createElement("div", null, " ", t("page.groupCategory"), ":")), /*#__PURE__*/React.createElement(Col, {
      span: "16"
    }, item.groupCategory === groupCategoryType["default"] ? t('page.defaultCategory') : t('page.allPurposeCategory')))), /*#__PURE__*/React.createElement(Col, {
      span: "12"
    }, /*#__PURE__*/React.createElement(Row, null, /*#__PURE__*/React.createElement(Col, {
      span: "8"
    }, /*#__PURE__*/React.createElement("div", null, " ", t("page.groupType"), ":")), /*#__PURE__*/React.createElement(Col, {
      span: "16"
    }, item.groupType === groupClassType.slot ? t('page.groupSlot') : t('page.groupComponent'))))), /*#__PURE__*/React.createElement(Row, {
      className: "group-row"
    }, /*#__PURE__*/React.createElement(Col, {
      span: "12"
    }, /*#__PURE__*/React.createElement(Row, null, /*#__PURE__*/React.createElement(Col, {
      span: "8"
    }, " ", /*#__PURE__*/React.createElement("div", null, "  ", t("page.groupMode"), ":")), /*#__PURE__*/React.createElement(Col, {
      span: "16"
    }, "  ", item.groupMode === groupModeType.single ? t('page.single') : t('page.schedule')))), /*#__PURE__*/React.createElement(Col, {
      span: "12"
    }, /*#__PURE__*/React.createElement(Row, {
      className: "group-row"
    }, /*#__PURE__*/React.createElement(Col, {
      span: "8"
    }, " ", /*#__PURE__*/React.createElement("div", null, "  ", t("page.groupLength"), ":")), /*#__PURE__*/React.createElement(Col, {
      span: "16"
    }, item.groupList.length)))));
  })), /*#__PURE__*/React.createElement(_Dialog, {
    className: "CComputed-dialog",
    visible: dialogConfig.visible,
    title: dialogConfig.title,
    footerAlign: "right",
    onClose: closeDialog,
    footer: [/*#__PURE__*/React.createElement(_Button, {
      onClick: saveGroupData,
      type: "primary"
    }, t('setter.ok')), /*#__PURE__*/React.createElement(_Button, {
      style: {
        marginLeft: '10px'
      },
      onClick: closeDialog
    }, t('setter.cancel'))]
  }, /*#__PURE__*/React.createElement(GroupItemComponent, {
    groupItem: groupItem,
    onChange: onGroupItemChange
  })));
};
var GroupItemComponent = function GroupItemComponent(props) {
  var groupItem = props.groupItem,
    onChange = props.onChange;
  var _useState4 = useState(groupItem || createNewGroupItem()),
    group = _useState4[0],
    setGroup = _useState4[1];
  var _useState5 = useState([]),
    groupBaseDataSource = _useState5[0],
    setGroupBaseDataSource = _useState5[1];
  var defaultIndexOptions = useMemo(function () {
    return getDefaultIndexOptions();
  }, []);
  useEffect(function () {
    var baseData = getBaseDataSourceBySchema();
    setGroupBaseDataSource(baseData);
  }, []);
  useEffect(function () {
    onChange(group);
  }, [group]);
  var groupListChange = function groupListChange(v, index, name) {
    if (group.groupList[index]) {
      // 组件，进度模式，只能有一个被选中
      if (name === 'selected' && group.groupType === groupClassType.component && group.groupMode === groupModeType.schedule) {
        group.groupList = group.groupList.map(function (item) {
          item.selected = false;
          return item;
        });
      }
      // 槽位，进度模式，所有状态中保留最大的选中
      if (name === 'stateList' && group.groupType === groupClassType.slot && group.groupMode === groupModeType.schedule) {
        // 是否有超过一个以上的选中状态
        var selectList = [];
        var maxGroupIndex = 0;
        group.groupList.forEach(function (item) {
          var selectState = item.stateList.find(function (stateItem) {
            return stateItem.selected;
          });
          if (selectState) {
            selectList.push(item.groupIndex);
            maxGroupIndex = item.groupIndex;
          }
        });
        if (selectList.length > 1) {
          group.groupList = group.groupList.map(function (item) {
            if (item.groupIndex !== maxGroupIndex) {
              item.stateList = item.stateList.map(function (stateItem) {
                stateItem.selected = false;
                return stateItem;
              });
            }
            return item;
          });
        }
      }
      var _groupItem = group.groupList[index];
      _groupItem[name] = v;
    }
    setGroup(_extends({}, group));
  };
  var groupIndexChange = function groupIndexChange(v, index, type) {
    if (type === groupCategoryType.allPurpose) {
      var list = getStateListByGroupIndex(v);
      groupListChange(list, index, 'stateList');
    }
    groupListChange(v, index, 'groupIndex');
  };
  var groupModeChange = function groupModeChange(e) {
    var newData = _extends({}, group, {
      groupMode: e
    });
    // 由于进度模式，组件某一个瞬间只能有一个选中
    if (newData.groupType === groupClassType.component && e === groupModeType.schedule && newData.groupList.length > 1) {
      // 判断是否有2个以上的选中
      var selectedCount = 0;
      for (var i = 0; i < newData.groupList.length; i++) {
        if (newData.groupList[i].selected) {
          selectedCount++;
          if (selectedCount >= 2) {
            break;
          }
        }
      }
      if (selectedCount >= 2) {
        newData.groupList = newData.groupList.map(function (item) {
          item.selected = false;
          return item;
        });
      }
    }
    setGroup(newData);
  };
  var addGroupListItem = function addGroupListItem() {
    var index = group.groupCategory === groupCategoryType.allPurpose ? 100100 : group.groupList.length + 1;
    group.groupList.push(createNewGroupListItem(index));
    setGroup(_extends({}, group));
  };
  var removeGroupListItem = function removeGroupListItem(index) {
    group.groupList.splice(index, 1);
    setGroup(_extends({}, group));
  };
  return /*#__PURE__*/React.createElement("div", null, /*#__PURE__*/React.createElement(BoxSlotComponent, {
    title: t("page.groupId") + ":",
    titleStyle: {
      color: '#fff'
    }
  }, /*#__PURE__*/React.createElement(_Input, {
    style: {
      width: "100%"
    },
    value: group.groupId,
    disabled: true
  })), /*#__PURE__*/React.createElement(BoxSlotComponent, {
    title: t("page.groupName") + ":",
    titleStyle: {
      color: '#fff'
    }
  }, /*#__PURE__*/React.createElement(_Input, {
    style: {
      width: "100%"
    },
    value: group.groupName,
    onChange: function onChange(e) {
      setGroup(_extends({}, group, {
        groupName: e
      }));
    }
  })), /*#__PURE__*/React.createElement(BoxSlotComponent, {
    title: t("page.groupCategory") + ":",
    titleStyle: {
      color: '#fff'
    }
  }, /*#__PURE__*/React.createElement(RadioGroup, {
    value: group.groupCategory,
    onChange: function onChange(e) {
      setGroup(_extends({}, group, {
        groupCategory: e,
        groupList: []
      }));
    }
  }, /*#__PURE__*/React.createElement(_Radio, {
    id: groupCategoryType["default"],
    value: groupCategoryType["default"]
  }, /*#__PURE__*/React.createElement("span", {
    style: {
      color: '#fff'
    }
  }, t('page.defaultCategory'))), /*#__PURE__*/React.createElement(_Radio, {
    id: groupCategoryType.allPurpose,
    value: groupCategoryType.allPurpose
  }, /*#__PURE__*/React.createElement("span", {
    style: {
      color: '#fff'
    }
  }, t('page.allPurposeCategory'))))), /*#__PURE__*/React.createElement(BoxSlotComponent, {
    title: t("page.groupType") + ":",
    titleStyle: {
      color: '#fff'
    }
  }, /*#__PURE__*/React.createElement(RadioGroup, {
    value: group.groupType,
    onChange: function onChange(e) {
      setGroup(_extends({}, group, {
        groupType: e
      }));
    }
  }, /*#__PURE__*/React.createElement(_Radio, {
    id: groupClassType.component,
    value: groupClassType.component
  }, /*#__PURE__*/React.createElement("span", {
    style: {
      color: '#fff'
    }
  }, t('page.groupComponent'))), /*#__PURE__*/React.createElement(_Radio, {
    id: groupClassType.slot,
    value: groupClassType.slot
  }, /*#__PURE__*/React.createElement("span", {
    style: {
      color: '#fff'
    }
  }, t('page.groupSlot'))))), /*#__PURE__*/React.createElement(BoxSlotComponent, {
    title: t("page.groupMode") + ":",
    titleStyle: {
      color: '#fff'
    }
  }, /*#__PURE__*/React.createElement(RadioGroup, {
    value: group.groupMode,
    onChange: function onChange(e) {
      groupModeChange(e);
    }
  }, /*#__PURE__*/React.createElement(_Radio, {
    id: groupModeType.single,
    value: groupModeType.single
  }, /*#__PURE__*/React.createElement("span", {
    style: {
      color: '#fff'
    }
  }, t('page.single'))), /*#__PURE__*/React.createElement(_Radio, {
    id: groupModeType.schedule,
    value: groupModeType.schedule
  }, /*#__PURE__*/React.createElement("span", {
    style: {
      color: '#fff'
    }
  }, t('page.schedule'))))), /*#__PURE__*/React.createElement(BoxSlotComponent, {
    title: t("page.groupList") + ":",
    titleStyle: {
      color: '#fff'
    }
  }, /*#__PURE__*/React.createElement("div", {
    className: "sub_btn"
  }, /*#__PURE__*/React.createElement(_Button, {
    type: "primary",
    onClick: addGroupListItem
  }, /*#__PURE__*/React.createElement("span", null, t("setter.addData"))))), /*#__PURE__*/React.createElement("div", {
    className: "groupListBox"
  }, group.groupList.map(function (item, index) {
    return /*#__PURE__*/React.createElement("div", {
      className: "groupListItem",
      key: item.groupIndex + "-" + index
    }, /*#__PURE__*/React.createElement(BoxSlotComponent, {
      title: t("page.groupIndex") + ":",
      titleStyle: {
        color: '#fff'
      }
    }, group.groupCategory === groupCategoryType.allPurpose ? /*#__PURE__*/React.createElement(_Select, {
      placeholder: t("setter.selectPlaceHolder"),
      notFoundContent: t('setter.notFoundContent'),
      showSearch: true,
      hasClear: true,
      value: item.groupIndex,
      dataSource: defaultIndexOptions,
      onChange: function onChange(v) {
        groupIndexChange(v, index, groupCategoryType.allPurpose);
      }
    }) : /*#__PURE__*/React.createElement(_NumberPicker, {
      style: {
        width: '100%'
      },
      step: 1,
      min: 0,
      hasTrigger: false,
      value: item.groupIndex,
      onChange: function onChange(v) {
        groupIndexChange(v, index, groupCategoryType["default"]);
      }
    })), group.groupType === groupClassType.component && /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(BoxSlotComponent, {
      title: t("page.groupComponent") + ":",
      titleStyle: {
        color: '#fff'
      }
    }, /*#__PURE__*/React.createElement(_Select, {
      placeholder: t("setter.selectPlaceHolder"),
      notFoundContent: t('setter.notFoundContent'),
      showSearch: true,
      hasClear: true,
      value: item.code,
      dataSource: groupBaseDataSource,
      onChange: function onChange(v) {
        groupListChange(v, index, 'code');
      }
    }))), group.groupType === groupClassType.slot && /*#__PURE__*/React.createElement(GroupStateItemComponent, {
      parentGroup: {
        groupIndex: item.groupIndex,
        groupCategory: group.groupCategory,
        groupMode: group.groupMode
      },
      stateList: item.stateList,
      onChange: function onChange(newStateList) {
        groupListChange(newStateList, index, 'stateList');
      }
    }), /*#__PURE__*/React.createElement("div", {
      className: "CDataBtn"
    }, /*#__PURE__*/React.createElement(_Icon, {
      style: {
        cursor: "pointer",
        color: "#fff"
      },
      type: "ashbin",
      onClick: function onClick() {
        removeGroupListItem(index);
      }
    })));
  })));
};
var GroupStateItemComponent = function GroupStateItemComponent(props) {
  var parentGroup = props.parentGroup,
    stateList = props.stateList,
    onChange = props.onChange;
  var _useState6 = useState(stateList),
    stateData = _useState6[0],
    setSateData = _useState6[1];
  var _useState7 = useState([]),
    groupColDataSource = _useState7[0],
    setGroupColDataSource = _useState7[1];
  var _useState8 = useState('0'),
    activeKey = _useState8[0],
    setActiveKey = _useState8[1];
  useEffect(function () {
    setGroupColDataSource(getColDataSourceBySchema());
    if (stateList.length === 0) {
      var list = [];
      if (parentGroup.groupCategory === groupCategoryType.allPurpose) {
        list = getStateListByGroupIndex(parentGroup.groupIndex);
      } else {
        var loading = createNewStateListItem({
          state: EngineRuleState.loading,
          isDelete: false,
          isIndexDisable: true,
          name: t('page.stateDefaultName')
        });
        var succeeded = createNewStateListItem({
          state: EngineRuleState.succeeded,
          isIndexDisable: true,
          name: t('page.stateSuccessName')
        });
        var failed = createNewStateListItem({
          state: EngineRuleState.failed,
          isIndexDisable: true,
          name: t('page.stateFailName')
        });
        list = [loading, succeeded, failed];
      }
      setSateData(list);
    }
  }, []);
  useEffect(function () {
    onChange(stateData);
  }, [stateData]);
  var handleChange = function handleChange(value, index, key) {
    var alterItem = stateData[index];
    if (key === 'state') {
      var isRepeat = stateData.find(function (item) {
        return item.state === value;
      });
      if (isRepeat) {
        _Message.show({
          type: "error",
          content: t('page.stateError')
        });
        return;
      }
    }
    var newData = stateData;
    // 槽位里面的某一个状态永远只能有一个被选中
    if (key === 'selected') {
      newData = newData.map(function (item) {
        return _extends({}, item, {
          selected: false
        });
      });
    }
    alterItem[key] = value;
    newData = newData.map(function (item, i) {
      if (i === index) {
        return alterItem;
      }
      return item;
    });
    setSateData(newData);
    // onChange(newData)
  };
  var addGroupListItem = function addGroupListItem() {
    var stateItem = createNewStateListItem({
      state: stateData.length
    });
    stateData.push(stateItem);
    var newData = [].concat(stateData);
    setSateData(newData);
  };
  var removeGroupListItem = function removeGroupListItem(index) {
    stateData.splice(index, 1);
    var newData = [].concat(stateData);
    setSateData(newData);
  };
  return /*#__PURE__*/React.createElement("div", {
    className: "groupStateListBox"
  }, parentGroup.groupCategory === groupCategoryType["default"] && /*#__PURE__*/React.createElement("div", {
    className: "groupStateListBox-header"
  }, /*#__PURE__*/React.createElement(_Button, {
    type: "primary",
    onClick: addGroupListItem
  }, /*#__PURE__*/React.createElement("span", null, t("page.stateAdd")))), /*#__PURE__*/React.createElement("div", {
    className: "groupStateListBox-body"
  }, /*#__PURE__*/React.createElement(_Tab, {
    excessMode: "slide",
    shape: "pure",
    activeKey: activeKey,
    onChange: function onChange(v) {
      setActiveKey(v);
    },
    onClose: function onClose(v) {
      if (activeKey === v) {
        setActiveKey("" + (parseInt(v) - 1));
      }
      removeGroupListItem(parseInt(v));
    },
    className: "chaos-element-ui-new"
  }, stateData.map(function (stateItem, stateIndex) {
    return /*#__PURE__*/React.createElement(_Tab.Item, {
      title: stateItem.name,
      key: stateIndex,
      closeable: stateItem.isDelete
    }, /*#__PURE__*/React.createElement("div", {
      className: "groupStateItem"
    }, /*#__PURE__*/React.createElement(BoxSlotComponent, {
      title: t("page.stateName") + ":",
      titleStyle: {
        color: '#fff'
      }
    }, /*#__PURE__*/React.createElement(_Input, {
      disabled: parentGroup.groupCategory === groupCategoryType.allPurpose,
      style: {
        width: "100%"
      },
      value: stateItem.name,
      onChange: function onChange(e) {
        handleChange(e, stateIndex, 'name');
      }
    })), /*#__PURE__*/React.createElement(BoxSlotComponent, {
      title: t("page.stateIndex") + ":",
      titleStyle: {
        color: '#fff'
      }
    }, /*#__PURE__*/React.createElement(_NumberPicker, {
      disabled: stateItem.isIndexDisable,
      style: {
        width: '100%'
      },
      step: 1,
      min: 0,
      hasTrigger: false,
      value: stateItem.state,
      onChange: function onChange(v) {
        handleChange(v, stateIndex, 'state');
      }
    })), /*#__PURE__*/React.createElement(BoxSlotComponent, {
      title: t("page.groupSlot") + ":",
      titleStyle: {
        color: '#fff'
      }
    }, /*#__PURE__*/React.createElement(_Select, {
      placeholder: t("setter.selectPlaceHolder"),
      notFoundContent: t('setter.notFoundContent'),
      showSearch: true,
      hasClear: true,
      value: stateItem.code,
      dataSource: groupColDataSource,
      onChange: function onChange(v) {
        handleChange(v, stateIndex, 'code');
      }
    }))));
  }))));
};
var _default = /*#__PURE__*/function (_Component) {
  function _default() {
    return _Component.apply(this, arguments) || this;
  }
  _inheritsLoose(_default, _Component);
  var _proto = _default.prototype;
  _proto.render = function render() {
    return /*#__PURE__*/React.createElement(CGroupManagerSetter, this.props);
  };
  return _default;
}(Component);
export { _default as default };