"use strict";
var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.handleInitialValues = exports.handleOnFinish = exports.getModalFormFields = exports.formStringValuesToTs = exports.addValidator = void 0;
require("reflect-metadata");
var class_transformer_1 = require("class-transformer");
var common_helpers_1 = require("./common-helpers");
var class_validator_1 = require("class-validator");
var immer_1 = __importDefault(require("immer"));
var ValidatorOptions = {
    stopAtFirstError: false,
    skipMissingProperties: true
};
var TransformOptions = {
    enableImplicitConversion: true,
    excludePrefixes: ['_'],
    exposeUnsetFields: false
};
function inputValidator(transformClass, field, tsType) {
    return function (_a) {
        var getFieldValue = _a.getFieldValue;
        return ({
            validator: function (_, value) {
                return __awaiter(this, void 0, void 0, function () {
                    var newValue, obj, errors;
                    var _a;
                    return __generator(this, function (_b) {
                        switch (_b.label) {
                            case 0:
                                if (tsType === 'string' &&
                                    (value === '' || (Array.isArray(value) && value.length > 0)) // checkbox select(mutiple)
                                ) {
                                    return [2 /*return*/, Promise.resolve()]; //依赖required规则先执行（''值无法通过required的验证）
                                }
                                newValue = value;
                                if (tsType === 'boolean' || tsType === 'number' || tsType === 'bigint') {
                                    newValue = value === null || value === void 0 ? void 0 : value.toString().trim();
                                    if (newValue === '' && value !== '') {
                                        return [2 /*return*/, Promise.reject(new Error("'".concat(field, "' can not be blank characters")))];
                                    }
                                }
                                if (Array.isArray(value) && value.length === 0) {
                                    value = undefined;
                                }
                                obj = (0, class_transformer_1.plainToInstance)(transformClass, (_a = {}, _a[field] = value, _a), TransformOptions);
                                return [4 /*yield*/, (0, class_validator_1.validate)(obj, ValidatorOptions)
                                    // errors is an array of validation errors
                                ];
                            case 1:
                                errors = _b.sent();
                                // errors is an array of validation errors
                                if (errors.length > 0) {
                                    return [2 /*return*/, Promise.reject(new Error(Object.values(errors[0].constraints || []).join(' AND ')))];
                                }
                                else {
                                    return [2 /*return*/, Promise.resolve()];
                                }
                                return [2 /*return*/];
                        }
                    });
                });
            }
        });
    };
}
function addValidator(field, transformClass) {
    return (0, immer_1.default)(field, function (draft) {
        draft.validator = inputValidator(transformClass, draft.name, draft.tsType);
    });
}
exports.addValidator = addValidator;
function formStringValuesToTs(transformClass, values) {
    /*
    const newValues = {};
    Object.entries(values).forEach(([k, v]) => {
      newValues[k] = stringToTsType(v, scalarToTS(dataTypes[k].type) as TsTypeString);
    })
    */
    var isInsert = values.id === undefined;
    var transformedValues = (0, class_transformer_1.plainToInstance)(transformClass, values, TransformOptions);
    var newValues = Object.entries(values).reduce(function (acc, _a) {
        var key = _a[0], value = _a[1];
        if (value === undefined)
            return acc;
        if (typeof value === 'object' && value.hasOwnProperty('connect')) {
            var realValue = value['connect'];
            if (Array.isArray(realValue)) {
                acc[key] = {
                    set: [],
                    connect: realValue.map(function (id) { return ({ id: id }); })
                };
            }
            else {
                acc[key] = {
                    set: [],
                    connect: { id: realValue }
                };
            }
            if (isInsert) {
                delete acc[key].set;
            }
        }
        else {
            acc[key] = transformedValues[key];
        }
        return acc;
    }, {});
    if (!isInsert && newValues.hasOwnProperty('id')) {
        delete newValues.id;
    }
    return newValues;
}
exports.formStringValuesToTs = formStringValuesToTs;
function getModalFormFields(changeValueModal, fieldsComponent) {
    return changeValueModal.fields
        .map(function (fieldName) { return fieldsComponent[fieldName]; })
        .filter(function (component) { return component; })
        .map(function (component) {
        return changeValueModal.keys.length &&
            !changeValueModal.initialValues.hasOwnProperty('id')
            ? (0, common_helpers_1.omit)(component, ['when', 'visible', 'reaction']) // rowSelection CHANGE_VALUE
            : component;
    });
}
exports.getModalFormFields = getModalFormFields;
function handleOnFinish(values, fields, action) {
    return __assign(__assign({}, values), fields.reduce(function (aac, field) {
        var _a, _b, _c;
        var _d = field.uiType.formItem, uiType = _d.type, args = _d.args;
        if (field.kind === 'object') {
            if (field.name.endsWith('.connect')) {
                var fieldName = field.name.split('.')[0];
                if (field.isList) {
                    if (action === 'edit') {
                        aac[fieldName] = {
                            set: [],
                            connect: (_a = values === null || values === void 0 ? void 0 : values[fieldName]) === null || _a === void 0 ? void 0 : _a.ids.map(function (id) { return ({ id: id }); })
                        };
                    }
                    else {
                        aac[fieldName] = {
                            connect: (_b = values === null || values === void 0 ? void 0 : values[fieldName]) === null || _b === void 0 ? void 0 : _b.ids.map(function (id) { return ({ id: id }); })
                        };
                    }
                }
                else {
                    aac[fieldName] = { connect: { id: (_c = values === null || values === void 0 ? void 0 : values[fieldName]) === null || _c === void 0 ? void 0 : _c.id } };
                }
            }
        }
        else if (uiType === 'File' || uiType === 'Image') {
            if (Array.isArray(values[field.name])) {
                aac[field.name] = JSON.stringify(values[field.name].map(function (val) {
                    var _a;
                    return (__assign(__assign({}, (0, common_helpers_1.omit)(val, [
                        'xhr',
                        'originFileObj',
                        'lastModified',
                        'lastModifiedDate'
                    ])), { thumbUrl: (_a = val === null || val === void 0 ? void 0 : val.response) === null || _a === void 0 ? void 0 : _a.url }));
                }));
            }
        }
        else if (uiType === 'CheckBox' ||
            (uiType === 'Select' && args.mode === 'multiple')) {
            if (Array.isArray(values[field.name])) {
                aac[field.name] = JSON.stringify(values[field.name]);
            }
        }
        return aac;
    }, {}));
}
exports.handleOnFinish = handleOnFinish;
function handleInitialValues(initialValues, fields) {
    return __assign(__assign({}, initialValues), fields.reduce(function (aac, field) {
        var _a;
        var _b = field.uiType.formItem, uiType = _b.type, args = _b.args;
        if (field.kind === 'object' &&
            field.isList &&
            field.name.endsWith('.connect')) {
            var fieldName = field.name.split('.')[0];
            aac[fieldName] = {
                ids: (_a = initialValues === null || initialValues === void 0 ? void 0 : initialValues[fieldName]) === null || _a === void 0 ? void 0 : _a.map(function (item) { return item.id; })
            };
        }
        else if (initialValues[field.name] &&
            (['File', 'Image', 'CheckBox'].includes(uiType || '') ||
                (uiType === 'Select' && args.mode === 'multiple'))) {
            aac[field.name] = JSON.parse(initialValues[field.name]);
        }
        return aac;
    }, {}));
}
exports.handleInitialValues = handleInitialValues;
//# sourceMappingURL=form-helpers.js.map