"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const react_1 = __importStar(require("react"));
const react_redux_1 = require("react-redux");
const icons_1 = require("@ant-design/icons");
const antd_1 = require("antd");
const lodash_1 = __importDefault(require("lodash"));
const styled_components_1 = __importDefault(require("styled-components"));
const ACTIONS = __importStar(require("@/actions/applications/detail/file/conditions"));
const index_1 = require("@/components/index");
const index_2 = require("@/constants/index");
const system_1 = require("@/pages/system");
const { Option } = antd_1.Select;
const Container = styled_components_1.default.div `
  display: flex;
  margin-bottom: 10px;
`;
const FormulaContainer = styled_components_1.default.div `
  display: flex;
  flex-grow: 1;
`;
const FormulaCTAContainer = styled_components_1.default.div `
  padding: 0 10px;
  flex: 0 0 70px;
  align-self: center;
`;
const mapStateToProps = (store) => ({
    pageInfo: store.applications.detail.file.conditions.pageInfo,
    condition: store.applications.detail.file.conditions.editCondition,
    type: store.applications.detail.file.conditions.drawerType,
    visible: store.applications.detail.file.conditions.drawerVisible,
});
const mapDispatchToProps = {
    closeDrawer: ACTIONS.openEditDrawer,
    saveCondition: ACTIONS.saveCondition,
    fetchList: ACTIONS.fetchList,
};
function EditDrawer(props) {
    const { applicationId, folderId, type, pageInfo, visible, condition, closeDrawer, saveCondition, fetchList, } = props;
    const [name, setName] = (0, react_1.useState)('');
    const [logicType, setLogicType] = (0, react_1.useState)(0);
    // init opt data
    const defaultOptData = [
        {
            type: 'condition.expression',
            props: {
                key: '',
                operation: '',
                value: '',
            },
        },
    ];
    const [optData, setOptData] = (0, react_1.useState)(defaultOptData);
    const viewMode = !!type && type === 'view';
    // i18n
    const { locale } = (0, react_1.useContext)(system_1.GlobalContext);
    const { condition: conditionI18n, global } = locale.business;
    (0, react_1.useEffect)(() => {
        var _a, _b;
        if (visible) {
            // get name & set default when edit
            const conditionName = (condition === null || condition === void 0 ? void 0 : condition.name) || undefined;
            if (conditionName)
                setName(conditionName);
            // get type & set default when edit
            const { content } = condition || {};
            const { schemas } = content || {};
            const conditionType = schemas ? (_a = schemas[0]) === null || _a === void 0 ? void 0 : _a.type : undefined;
            if (conditionType)
                setLogicType(conditionType - 1);
            // get optData & set default when edit
            const conditionOptData = schemas ? (_b = schemas[0]) === null || _b === void 0 ? void 0 : _b.children : undefined;
            if (conditionOptData)
                setOptData(conditionOptData);
        }
    }, [visible, condition]);
    const handleUpdateName = (name) => {
        const newName = !folderId ? name : name.startsWith('_') ? name : '';
        setName(newName);
    };
    const handleClose = (0, react_1.useCallback)(() => {
        setName('');
        setLogicType(0);
        setOptData([
            {
                type: 'condition.expression',
                props: {
                    key: '',
                    operation: '',
                    value: '',
                },
            },
        ]);
        setTimeout(() => closeDrawer(false), 50);
    }, [closeDrawer]);
    const handleApply = (0, react_1.useCallback)(() => {
        const id = (condition === null || condition === void 0 ? void 0 : condition.id) || '';
        const contentId = (condition === null || condition === void 0 ? void 0 : condition.contentId) || '';
        const newSchemas = [
            {
                name,
                type: logicType + 1,
                props: {},
                children: optData,
            },
        ];
        saveCondition({
            applicationId,
            folderId,
            id,
            name,
            content: {
                id: contentId,
                schemas: newSchemas,
            },
            type: 'condition',
        }, () => {
            handleClose();
            fetchList({
                applicationId,
                folderId,
                page: pageInfo.page,
                size: pageInfo.size,
            });
        });
    }, [applicationId, condition, name, logicType, optData, saveCondition, handleClose]);
    // expression change
    const handleOptDataChange = (0, react_1.useCallback)((key, value, idx) => {
        const newData = lodash_1.default.cloneDeep(optData);
        Object.assign(newData[idx]['props'], { [key]: value });
        setOptData(newData);
    }, [optData]);
    // button click
    const handleAddItem = (0, react_1.useCallback)(() => {
        const newData = [...optData];
        newData.push({
            type: 'condition.expression',
            props: {
                key: '',
                operation: '',
                value: '',
            },
        });
        setOptData(newData);
    }, [optData]);
    const handleRemoveItem = (0, react_1.useCallback)((idx) => {
        const newData = [...optData];
        newData.splice(idx, 1);
        setOptData(newData);
    }, [optData]);
    return (react_1.default.createElement(index_1.OperationDrawer, { destroyOnClose: true, width: 550, open: visible, title: viewMode ? global.view : (condition === null || condition === void 0 ? void 0 : condition.id) ? global.edit : global.add, actions: react_1.default.createElement(antd_1.Button, { type: "primary", disabled: !name || viewMode, onClick: handleApply }, global.apply), onClose: handleClose },
        react_1.default.createElement(index_1.Group, null,
            react_1.default.createElement(index_1.Field, null,
                react_1.default.createElement(index_1.Label, null, folderId ? global.nameLabelWithUnderline : global.nameLabel),
                react_1.default.createElement(antd_1.Input, { disabled: viewMode, placeholder: conditionI18n.nameLabel, value: name, onChange: (e) => handleUpdateName(e.target.value) })),
            react_1.default.createElement(index_1.Field, null,
                react_1.default.createElement(index_1.Label, null, conditionI18n.arithmeticLogic),
                react_1.default.createElement(antd_1.Select, { placeholder: "logic", disabled: !!(condition === null || condition === void 0 ? void 0 : condition.id) || viewMode, value: logicType, onChange: setLogicType, style: { width: 160 } }, index_2.ConditionType &&
                    index_2.ConditionType.map((item, idx) => (react_1.default.createElement(Option, { key: item, value: idx }, item))))),
            react_1.default.createElement(index_1.Field, null,
                react_1.default.createElement(index_1.Label, null, global.expression),
                optData.map((item, index) => (react_1.default.createElement(Container, { key: index },
                    react_1.default.createElement(FormulaContainer, null,
                        react_1.default.createElement(antd_1.Input, { disabled: viewMode, placeholder: "origin", value: item.props.key, onChange: (e) => handleOptDataChange('key', e.target.value, index) }),
                        react_1.default.createElement(antd_1.Select, { disabled: viewMode, dropdownMatchSelectWidth: false, placeholder: "formula", value: item.props.operation, onChange: (value) => handleOptDataChange('operation', value, index), style: { flex: '0 0 120px', marginRight: 10, marginLeft: 10 } }, index_2.ConditionFormula &&
                            index_2.ConditionFormula.map((item) => (react_1.default.createElement(Option, { key: item.value, value: item.value }, item.label)))),
                        react_1.default.createElement(antd_1.Input, { disabled: viewMode, placeholder: "expected", value: item.props.value, onChange: (e) => handleOptDataChange('value', e.target.value, index) })),
                    react_1.default.createElement(FormulaCTAContainer, null,
                        optData.length > 1 && (react_1.default.createElement(antd_1.Button, { icon: react_1.default.createElement(icons_1.DeleteOutlined, null), size: "small", type: "text", onClick: () => handleRemoveItem(index) })),
                        index === optData.length - 1 && optData.length < 10 && (react_1.default.createElement(antd_1.Button, { icon: react_1.default.createElement(icons_1.PlusOutlined, null), size: "small", type: "text", onClick: handleAddItem }))))))))));
}
exports.default = (0, react_redux_1.connect)(mapStateToProps, mapDispatchToProps)(EditDrawer);
