"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 antd_1 = require("antd");
const moment_1 = __importDefault(require("moment"));
const ACTIONS = __importStar(require("@/actions/applications/detail/file/conditions"));
const events_1 = require("@/actions/builder/events");
const PAGE_ACTIONS = __importStar(require("@/actions/builder/main"));
const index_1 = require("@/components/index");
const index_2 = require("@/constants/index");
const system_1 = require("@/pages/system");
const utils_1 = require("@/sagas/builder/utils");
const empty_check_1 = require("@/utils/empty-check");
const short_id_1 = __importDefault(require("@/utils/short-id"));
const timezone_1 = require("./utils/timezone");
const components_1 = require("./components");
const { RangePicker } = antd_1.DatePicker;
const dateFormat = 'YYYY-MM-DD hh:mm:ss';
const conditionExpression = 'condition.expression';
const timeConditionRelationKey = `${(0, utils_1.getSystemVariableRelationKey)(`${index_2.LOCAL_TIME_VARIABLE_NAME}:${index_2.LOCAL_TIME_VARIABLE_KEY}`)}`;
const timeConditionsKey = `{{${timeConditionRelationKey}}}`;
const displayKey = '1';
const LOCAL_TIME_ZONE = '+08';
const TIME_ZONE_START_POS = 19;
const mapStateToProps = (store) => ({
    applicationId: store.builder.header.applicationId,
    folderId: store.builder.header.folderId,
    locale: store.builder.header.locale,
    selectedComponent: store.builder.main.selectedNode,
    editorData: store.builder.main.toolbarEditorData,
    open: store.builder.main.toolbarEditorVisible,
});
const mapDispatchToProps = {
    fetchDetail: ACTIONS.fetchConditionDetail,
    saveCondition: ACTIONS.saveCondition,
    saveConditionVersion: ACTIONS.saveConditionVersion,
    closeDrawer: PAGE_ACTIONS.updateToolbarEditorVisible,
    conditionBind: events_1.conditionBind,
};
const Main = (props) => {
    var _a;
    const { open, applicationId, folderId, locale, editorData, fetchDetail, selectedComponent, saveCondition, saveConditionVersion, closeDrawer, conditionBind, } = props;
    const [conditions, setConditions] = (0, react_1.useState)([]);
    const [showStartTime, setShowStartTime] = (0, react_1.useState)(undefined);
    const [showEndTime, setShowEndTime] = (0, react_1.useState)(undefined);
    const [display, setDisplay] = (0, react_1.useState)(true);
    // time zone
    const timezones = (0, timezone_1.getAllTimeZone)(locale);
    const [defaultTimezone, setDefaultTimezone] = (0, react_1.useState)(((_a = timezones[0]) === null || _a === void 0 ? void 0 : _a.value) || '');
    // init condition content
    const timeConditionsContent = (0, react_1.useRef)(undefined);
    // i18n
    const { locale: i18n } = (0, react_1.useContext)(system_1.GlobalContext);
    const { global, condition } = i18n.business;
    (0, react_1.useEffect)(() => {
        var _a, _b;
        if (open) {
            setDefaultTimezone(((_a = timezones[0]) === null || _a === void 0 ? void 0 : _a.value) || '');
            setShowStartTime(undefined);
            setShowEndTime(undefined);
            setDisplay(true);
            const component = selectedComponent;
            if (component) {
                const newConditions = [];
                const conditionDirective = ((_b = component === null || component === void 0 ? void 0 : component.directive) === null || _b === void 0 ? void 0 : _b.if) || [];
                const conditionDirectiveIds = !(0, empty_check_1.objectEmptyCheck)(conditionDirective)
                    ? conditionDirective.map((item) => item.substring(item.indexOf(':') + 1, item.indexOf('}}')))
                    : [];
                conditionDirectiveIds.forEach((id) => {
                    if (id) {
                        fetchDetail({ applicationId, id }, (condition) => {
                            var _a, _b;
                            const schemaItems = (_b = (_a = condition === null || condition === void 0 ? void 0 : condition.content) === null || _a === void 0 ? void 0 : _a.schemas) === null || _b === void 0 ? void 0 : _b[0];
                            if (!schemaItems) {
                                return;
                            }
                            if ((0, utils_1.isTimeConditionRelation)(schemaItems)) {
                                timeConditionsContent.current = condition.contentId;
                                const childrenPropsItems = schemaItems === null || schemaItems === void 0 ? void 0 : schemaItems.children;
                                childrenPropsItems.forEach((item) => {
                                    var _a;
                                    const props = item.props;
                                    if (props.key === timeConditionsKey && props.operation === index_2.gtQqRelations.value) {
                                        setShowStartTime((0, timezone_1.getTimeByZone)(LOCAL_TIME_ZONE, props.value));
                                        setDefaultTimezone((_a = props.value) === null || _a === void 0 ? void 0 : _a.substr(TIME_ZONE_START_POS, 3));
                                    }
                                    else if (props.key === timeConditionsKey && props.operation === index_2.ltEqRelations.value) {
                                        setShowEndTime((0, timezone_1.getTimeByZone)(LOCAL_TIME_ZONE, props.value));
                                    }
                                    else if (props.key === displayKey && props.operation === index_2.eqRelations.value) {
                                        setDisplay(props.value === displayKey);
                                    }
                                });
                            }
                            else {
                                newConditions.push(condition);
                                return;
                            }
                        });
                    }
                });
                setConditions(newConditions);
            }
        }
    }, [open]);
    const handleSelectTimezone = (value) => {
        setDefaultTimezone(value);
    };
    const handleChangeTime = (value) => {
        const [startTime, endTime] = value || [];
        const newShowStartTime = startTime ? startTime.format() : '';
        const newShowEndTime = endTime ? endTime.format() : '';
        setShowStartTime(newShowStartTime);
        setShowEndTime(newShowEndTime);
    };
    const handleUpdateComponentCondition = (ids) => {
        var _a;
        const componentId = ((_a = editorData === null || editorData === void 0 ? void 0 : editorData.component) === null || _a === void 0 ? void 0 : _a.id) || '';
        if (componentId) {
            conditionBind(ids);
            closeDrawer(false);
        }
    };
    const handleApply = () => {
        if (!showStartTime || !showEndTime) {
            if (conditions.length > 0) {
                const conditionContentIds = conditions.map((condition) => condition.contentId);
                handleUpdateComponentCondition(conditionContentIds);
                return;
            }
        }
        let items = [];
        if (showStartTime && showEndTime) {
            items = [
                {
                    type: conditionExpression,
                    props: {
                        key: timeConditionsKey,
                        operation: index_2.gtQqRelations.value,
                        value: (0, timezone_1.getTimeByZone)(defaultTimezone, showStartTime),
                    },
                },
                {
                    type: conditionExpression,
                    props: {
                        key: timeConditionsKey,
                        operation: index_2.ltEqRelations.value,
                        value: (0, timezone_1.getTimeByZone)(defaultTimezone, showEndTime),
                    },
                },
            ];
        }
        items.push({
            type: conditionExpression,
            props: {
                key: displayKey,
                operation: index_2.eqRelations.value,
                value: display ? displayKey : '0',
            },
        });
        const timeConditionsName = `__condition_${(0, short_id_1.default)(10)}`;
        const timeConditionContentEntity = {
            id: timeConditionsContent.current || '',
            schemas: [{ type: 1, props: {}, name: timeConditionsName, children: items }],
            relation: {
                [timeConditionRelationKey]: {
                    type: 'sys_variable',
                    id: '',
                    // content: localTimeVariable.current.content,
                },
            },
        };
        // generate request
        const params = {
            applicationId,
            folderId,
            name: timeConditionsName,
            type: 'condition',
            content: timeConditionContentEntity,
        };
        const cb = (id) => {
            timeConditionContentEntity.id = id || timeConditionsContent.current || '';
            const conditionContentIds = conditions.map((condition) => condition.contentId);
            handleUpdateComponentCondition(conditionContentIds.concat([timeConditionContentEntity.id]));
        };
        // save or update version
        timeConditionsContent.current ? saveConditionVersion(params, cb) : saveCondition(params, cb);
    };
    return (react_1.default.createElement(index_1.OperationDrawer, { destroyOnClose: true, open: open, width: 480, title: global.condition, onClose: () => closeDrawer(false), actions: react_1.default.createElement(antd_1.Button, { type: "primary", onClick: handleApply }, global.apply) },
        react_1.default.createElement(index_1.Group, null,
            react_1.default.createElement(index_1.Title, null, condition.general),
            react_1.default.createElement(index_1.Field, null,
                react_1.default.createElement(index_1.Label, null, condition.time),
                react_1.default.createElement(antd_1.Select, { showSearch: true, optionLabelProp: "label", placeholder: condition.timezoneSelect, value: defaultTimezone, onChange: handleSelectTimezone, style: { width: 200, marginRight: 10, marginBottom: 8 } }, timezones.map((item) => (react_1.default.createElement(antd_1.Select.Option, { key: item.key, value: item.value, label: item.desc, title: `${item.desc}(${item.country})` },
                    item.desc,
                    "(",
                    item.country,
                    ")")))),
                react_1.default.createElement(RangePicker, { showTime: true, style: { marginBottom: 8 }, value: showStartTime && showEndTime
                        ? [(0, moment_1.default)(showStartTime, dateFormat), (0, moment_1.default)(showEndTime, dateFormat)]
                        : undefined, onChange: handleChangeTime })),
            react_1.default.createElement(index_1.Field, null,
                react_1.default.createElement(index_1.Label, null, "Display"),
                react_1.default.createElement(antd_1.Switch, { checkedChildren: condition.show, unCheckedChildren: condition.hide, checked: display, onChange: (value) => setDisplay(value) }))),
        react_1.default.createElement(index_1.Group, null,
            react_1.default.createElement(index_1.Title, null, condition.advanced),
            react_1.default.createElement(index_1.Field, null,
                react_1.default.createElement(index_1.Label, null,
                    global.terms,
                    " "),
                react_1.default.createElement(components_1.ConditionList, { conditions: conditions, updateComponentCondition: (conditions) => {
                        setConditions(conditions);
                    } })))));
};
exports.default = (0, react_redux_1.connect)(mapStateToProps, mapDispatchToProps)(Main);
