"use strict";

Object.defineProperty(exports, "__esModule", {
    value: true
});

var _defineProperty2 = require("babel-runtime/helpers/defineProperty");

var _defineProperty3 = _interopRequireDefault(_defineProperty2);

var _regenerator = require("babel-runtime/regenerator");

var _regenerator2 = _interopRequireDefault(_regenerator);

var _extends2 = require("babel-runtime/helpers/extends");

var _extends3 = _interopRequireDefault(_extends2);

exports.toArray = toArray;
exports.getFieldId = getFieldId;
exports.remoteSourceHandler = remoteSourceHandler;
exports.handleFieldSource = handleFieldSource;
exports.cascadeHandler = cascadeHandler;

var _rest = require("@fishx/rest");

var _message = require("../../message");

var _message2 = _interopRequireDefault(_message);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }

var __awaiter = undefined && undefined.__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());
    });
};
function toArray(candidate) {
    if (candidate === undefined || candidate === false) return [];
    return Array.isArray(candidate) ? candidate : [candidate];
}
function getFieldId(namePath, formName) {
    if (!namePath.length) return undefined;
    var mergedId = namePath.join('_');
    return formName ? formName + "_" + mergedId : mergedId;
}
// 请求远程数据源
function remoteSourceHandler(options, relates, values, locale) {
    return __awaiter(this, void 0, void 0, /*#__PURE__*/_regenerator2["default"].mark(function _callee() {
        var url, _options$method, method, _options$params, params, fetchUrl, value, _ref, data;

        return _regenerator2["default"].wrap(function _callee$(_context) {
            while (1) {
                switch (_context.prev = _context.next) {
                    case 0:
                        if (!(options && options.url)) {
                            _context.next = 21;
                            break;
                        }

                        url = options.url, _options$method = options.method, method = _options$method === undefined ? 'GET' : _options$method, _options$params = options.params, params = _options$params === undefined ? {} : _options$params;
                        fetchUrl = url;

                        if (!(url.indexOf('${value}') > -1)) {
                            _context.next = 8;
                            break;
                        }

                        value = values[relates[0]];

                        if (!(value === null || value === undefined || value === "")) {
                            _context.next = 7;
                            break;
                        }

                        return _context.abrupt("return", false);

                    case 7:
                        fetchUrl = fetchUrl.replace('${value}', value);

                    case 8:
                        _context.prev = 8;
                        _context.next = 11;
                        return (0, _rest.fetch)(fetchUrl, {
                            method: method,
                            data: (0, _extends3["default"])({}, params)
                        });

                    case 11:
                        _ref = _context.sent;
                        data = _ref.data;

                        if (!data) {
                            _context.next = 15;
                            break;
                        }

                        return _context.abrupt("return", data);

                    case 15:
                        _context.next = 21;
                        break;

                    case 17:
                        _context.prev = 17;
                        _context.t0 = _context["catch"](8);

                        _message2["default"].error(locale.requestFail);
                        return _context.abrupt("return", []);

                    case 21:
                        return _context.abrupt("return", options || []);

                    case 22:
                    case "end":
                        return _context.stop();
                }
            }
        }, _callee, this, [[8, 17]]);
    }));
}
function handleFieldSource(name, options, wrapForm) {
    wrapForm.setFieldSource((0, _defineProperty3["default"])({}, name, options));
    // const currentValue = wrapForm.getFieldValue(name);
    // const exit = options.findIndex(v => v.value === currentValue) > -1;
    // // 如果下拉数据源内不包含当前值，则清空当前值
    // if (!exit) {
    //   wrapForm.setFieldsValue({[name]: null});
    // }
}
function cascadeHandler(wrapForm, allValues, allDependency) {
    var currentItem = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : '';

    function cascade(relates, inputs, output, defaultOutput, key, item) {
        var res = relates.some(function (v, i) {
            if (inputs[i] === '*') {
                return !allValues[v];
            } else {
                if (allValues[v] && typeof allValues[v] === 'object') {
                    var value = Array.isArray(allValues[v]) ? allValues[v] : Object.values(allValues[v]);
                    var _res = value.some(function (val) {
                        return inputs[i].indexOf(val) !== -1;
                    });
                    return !_res;
                } else {
                    return inputs[i].indexOf(allValues[v]) === -1;
                }
            }
        });
        if (key === 'value') {
            wrapForm.setFieldValue((0, _defineProperty3["default"])({}, item, res ? defaultOutput : output));
        }
        if (key === 'source') {
            var _wrapForm$__INTERNAL_ = wrapForm.__INTERNAL__.locale,
                locale = _wrapForm$__INTERNAL_ === undefined ? {} : _wrapForm$__INTERNAL_;

            if (res) {
                remoteSourceHandler(defaultOutput, relates, allValues, locale).then(function (res) {
                    if (res) {
                        handleFieldSource(item, res, wrapForm);
                    }
                });
            } else {
                remoteSourceHandler(output, relates, allValues, locale).then(function (res) {
                    if (res) {
                        handleFieldSource(item, res, wrapForm);
                    }
                });
            }
        }
        if (key === 'disabled') {
            wrapForm.setFieldDisabled((0, _defineProperty3["default"])({}, item, res ? defaultOutput : output));
        }
        if (key === 'visible') {
            wrapForm.setFieldVisible((0, _defineProperty3["default"])({}, item, res ? defaultOutput : output));
        }
        if (key === 'required') {
            wrapForm.setFieldRequired((0, _defineProperty3["default"])({}, item, res ? defaultOutput : output));
        }
        return !res;
    }
    Object.keys(allValues).forEach(function (item) {
        var dependency = allDependency[item];
        if (dependency) {
            Object.keys(dependency).forEach(function (key) {
                var dep = dependency[key];
                var relates = dep.relates,
                    inputs = dep.inputs,
                    output = dep.output,
                    defaultOutput = dep.defaultOutput,
                    _dep$cases = dep.cases,
                    cases = _dep$cases === undefined ? [] : _dep$cases;

                if (currentItem && relates.indexOf(currentItem) !== -1 || !currentItem) {
                    if (cases.length) {
                        cases.some(function (v) {
                            return cascade(relates, v.inputs, v.output, defaultOutput, key, item);
                        });
                    } else {
                        cascade(relates, inputs, output, defaultOutput, key, item);
                    }
                }
            });
        }
    });
}