import { BaseViewModel } from '../master/baseViewModel.js';
import { TreeMapSelect } from '../master/model';
import {
    SubstituteNodeViewModel, MappingRuleDataViewModel,
    MappingSrcViewModel,
    MappingDataViewModel,
    MappingRuleViewModel,
    EffectedMappingForm,
    MappingResultError,
} from './model';
require('./model');
require('./resource');

export function MappingViewModel() {
    var self = this;
    self.stateEffectedMappingForm = ko.observable(false);
    self.showConfirnForm = ko.observable(false);
    self.showResultsModal = ko.observable(false);
    self.resultsModel = ko.observable();
    self.substituteNodeModel = ko.observable(new SubstituteNodeViewModel());
    self.mappingRuleModel = ko.observable();
    self.mappingSrcModel = ko.observable();
    self.confirmFormRecord = ko.observable();
    self.childModel = ko.observable();
    self.caption = ko.observable();
    self.captionMappingTree = ko.observable();
    self.mappingType = ko.observable();
    self.sheetId = ko.observable();
    self.treeId = ko.observable();
    self.activeSide = ko.observable(1);
    self.isEffected = ko.observable(false);
    self.isTreeEffected = ko.observable(false);
    self.filterType = ko.observable(0);
    self.treeTitle = ko.observable("");
    self.sheetTitle = ko.observable();
    self.records = [];
    self.treeMappingSelectList = ko.observableArray();
    self.balancesheetSelectList = ko.observableArray();
    self.filterBalancesheetSelectList = ko.observableArray();
    self.showResults = function () {
        var selectedRecord = _h.kocnx().formModel();
        var model = new MappingRuleDataViewModel(selectedRecord);
        model.treeId(self.treeId());
        model.balanceSheetId(self.sheetId());
        model.rule(selectedRecord.rule());
        model.mappingRuleId(selectedRecord.id());

        self.resultsModel(model);
        self.resultsModel().init();
        self.showResultsModal(true);
    };
    self.mappingType.subscribe(function (newValue) {
        if (_h.isNullOrEmpty(newValue)) return;
        self.getTreeMappingSelectList();
    });
    self.sheetId.subscribe(function (newValue) {
        if (_h.isNullOrEmpty(newValue)) return;
        ko.utils.arrayFilter(self.balancesheetSelectList(), function (item) {
            if (newValue === item.value())
                self.sheetTitle('( ' + item.text() + ' )');
        });
    });
    self.treeId.subscribe(function (newValue) {
        if (_h.isNullOrEmpty(newValue)) {
            self.sheetId(null);
            return;
        }
        var target;
        self.sheetId(null);
        ko.utils.arrayFilter(self.treeMappingSelectList(), function (item) {
            if (newValue === item.value()) {
                self.treeTitle(item.text());
                target = item;
            }
        });
        self.filterBalancesheetSelectList.removeAll();
        if (self.balancesheetSelectList().length)
            for (var i = 0; i < self.balancesheetSelectList().length; i++) {
                var sheet = self.balancesheetSelectList()[i];
                if (sheet.currencyType() === target.currencyType())
                    self.filterBalancesheetSelectList.push(sheet);
            }

        self.substituteNodeModel().treeId(newValue);
    });
    self.onEnterSearchKey = function (d, e) {
        if (e.keyCode === 13) {
            self.getRecords(function (res) {
            });
        }
        return true;
    };
    self.getTreeMappingSelectList = function () {
        var model = {
            controllerName: 16,
            mappingType: self.mappingType()
        };
        if (!model.mappingType)
            model.mappingType = 0;
        self.apiService.request({
            name: "getMappingTreeList",
            data: model,
            success: function (data) {
                self.treeMappingSelectList.removeAll();
                if (_h.any(data))
                    for (var j = 0; j < data.length; j++) {
                        var target = data[j];
                        self.treeMappingSelectList.push(new TreeMapSelect(target));
                    }
                self.treeId(null);
            },
            error: function () {
                toast.error("Tree", 'getSelectList');
            }
        });
    };
    self.getBalancesheetSelectList = function (sign) {
        self.apiService.request({
            name: "/api/common/getbalancesheetlist",
            data: { controllerName: this.controllerName },
            success: function (data) {
                self.balancesheetSelectList.removeAll();
                if (_h.any(data))
                    for (var j = 0; j < data.length; j++) {
                        var target = data[j];
                        self.balancesheetSelectList.push(new TreeMapSelect(target));
                    }
                if (!sign)
                    self.sheetId(null);
            },
            error: function () {
                var text = _h.getApiMessage("ErrorLoadSelectBalancesheet");
                _h.failToast(text);
            }
        });
    }
    self.createMappingScope = function () {
        if (!self.validationObject.isValid()) {
            self.validationObject.errors.showAllMessages();
            return false;
        }
        self.searchKey(undefined);
        if (self.mappingSrcModel()) {
            self.mappingSrcModel().searchKey(undefined);
        }
        $(".createmodel-drop").removeClass("open");
        switch (self.mappingType()) {
            case 1:
                self.mappingSrcModel(null);
                self.getRecords(function (res) {
                    if (res) {
                        self.onClickleftSideTab();
                    }
                });
                break;
            case 2:
                self.getRecords(function (res) {
                    if (res) {
                        //
                    }
                });
                self.mappingRuleModel(null);
                self.childModel(null);
                self.substituteNodeModel(new SubstituteNodeViewModel());
                var dataModel = new MappingSrcViewModel();
                dataModel.treeId(self.treeId());
                dataModel.treeName(self.treeTitle());
                self.mappingSrcModel(dataModel);
                self.mappingSrcModel().init();
                self.changeCaption();
                break;
        }
    };
    self.validationObject = ko.validatedObservable({
        mappingType: self.mappingType.extend({
            required: {
                params: true,

                message: "لطفا نوع نگاشت را انتخاب کنید"
            }
        }),
        treeId: self.treeId.extend({
            required: {
                params: true,
                message: "لطفا درخت نگاشت را انتخاب کنید"
            }
        }),
        sheetId: self.sheetId.extend({
            required: {
                onlyIf: function () {
                    return self.mappingType() === 1;
                },
                message: "لطفا فایل تراز راانتخاب کنید"
            }
        })
    });
    self.onClickleftSideTab = function () {
        var dataModel;
        switch (self.activeSide()) {
            case 1:
                self.mappingRuleModel(null);
                dataModel = new MappingDataViewModel();
                dataModel.treeId(self.treeId());
                dataModel.sheetId(self.sheetId());
                self.childModel(dataModel);
                self.childModel().init();
                self.fixChosenTab();
                break;
            case 2:
                if (self.isTreeEffected())
                    return;
                self.substituteNodeModel().init();
                break;
            case 3:
                dataModel = new MappingRuleViewModel();
                dataModel.treeId(self.treeId());
                dataModel.balanceSheetId(self.sheetId());
                self.mappingRuleModel(dataModel);
                self.mappingRuleModel().init();
                break;
        }
        self.changeCaption();
    };
    self.fixChosenTab = function () {
        if ($("#substitutenode-t").hasClass("active") === true && self.isTreeEffected()) {
            $('a[href="#balancesheetmapping-t"]').trigger('click');
        }
    };
    self.getEffectedModel = function (callback) {
        self.apiService.request({
            name: "getTreeListWithFiles",
            success: function (data) {
                callback(data);
            },
            error: function () {
                var text = _h.getApiMessage("ErrorLoadMapTreeEffected");
                _h.failToast(text);
                callback(null);
            }
        });
    };
    self.effectedMappingBtn = function () {
        self.getEffectedModel(function (resData) {
            if (resData !== null) {
                _h.kocnx()
                    .openForm(new EffectedMappingForm(self, self.balancesheetSelectList(), resData));
            }
        });
    }
    self.updateEffectedMapping = function (parents, btnModel, e) {
        var item = parents[1];
        var model = item.toServer();
        item.showprogressBar(true);
        item.progressBar(10);
        self.apiService.request({
            name: "postChangeMappingResult",
            data: model,
            success: function (obj) {
                if (obj && _h.any(obj.models)) {
                    item.progressBar(40);
                    item.progressBar(100);
                    setTimeout(function () {
                        item.showprogressBar(false);
                        item.mappingResultErrorList.removeAll();
                        $.each(obj.models, function (i, p) {
                            item.mappingResultErrorList.push(new MappingResultError(p));
                        });
                        item.showSaveBtn(false);
                    }, 500);
                } else {
                    item.progressBar(40);
                    item.progressBar(100);
                    setTimeout(function () {
                        _h.kocnx().closeForm();
                        var text = _h.getApiMessage("SuccessPostBothMapping");
                        _h.successToast(text);
                        if (!_h.isNullOrEmpty(self.treeId()) && !_h.isNullOrEmpty(self.sheetId())) {
                            self.getRecords(function (res) { });
                        }
                    },
                        500);
                }
                _h.kocnx().advm(null);
            },
            error: function () {
            }
        });
    };
    self.configTools = function () {
        var tType = self.mappingType() === 2 ? "MappingDest" : "Mapping";
        $("#tree_view").treeView({
            tType: tType,
            location: tType,
            nodes: self.records,
            rootId: self.treeId(),
            permitPeriodEdit: _h.kocnx().permitPeriodEdit(),
            isEffected: self.isEffected(),
            removeItemsFunc: self.removeMapItems,
            onDropCallback: self.onDropCallback,
            controllerName: 16,
            sheetId: self.sheetId(),
            onClickItem: self.addMapItem,
            mappingSide: self.mappingType() === 1 ? 0 : 1,
            mappingType: self.mappingType
        });
    };
    self.removeMapItems = function (nodeId, count, type, code, callback) {
        if (type === "multi") {
            self.deleteItems(nodeId, code, count, function (res, list) {
                callback(res, list);
            });
        } else {
            self.deleteItems(nodeId, code, 1, function (res, list) {
                callback(res, list);
            });
        }
    };
    self.deleteItems = function (nodeId, code, count, callback) {
        var model = {
            treeId: self.treeId(),
            balanceSheetId: self.sheetId(),
            nodeId: nodeId,
            code: code
        };
        if (self.mappingType() === 2) {
            model.showMapped = self.mappingSrcModel().showMapped();
        }
        self.apiService.request({
            name: "delete",
            data: model,
            success: function (data) {
                if (!_h.isNullOrEmpty(data)) {
                    if (_h.any(data.errors)) {
                        callback(false);
                    } else {
                        var text = _h.getApiMessage("MappingDeleteSuccess");
                        text = text.replace("__", count);
                        switch (self.mappingType()) {
                            case 1:
                                if (_h.any(data.balanceDataList))
                                    self.childModel().afterDeleteMappingNodes(data.balanceDataList);

                                if (_h.any(data.model))
                                    $("#tree_view").treeView("refreshTree", data.model);

                                _h.successToast(text);
                                callback(true);
                                break;
                            case 2:

                                if (_h.any(data.sourceNodes)) {
                                    $("#tree_view_l").treeView("collectOpenBranches");
                                    $("#tree_view_l").treeView("refreshTree", data.sourceNodes);
                                    $("#tree_view_l").treeView("openBranches");
                                }
                                _h.successToast(text);
                                callback(nodeId, data.destNodes);
                                break;
                        }
                    }
                }
            },
            error: function () {
                var text = _h.getApiMessage("MappingDeleteError");
                _h.failToast(text);
                callback(false);
            }
        });
    }
    self.addMapItem = function (nodeId, opts, nt, callback) {
        if (self.mappingType() === 1) {
            if ($("#substitutenode-t").hasClass("active") === false && nt === 2) {
                if (self.childModel().allSelectedRecords().length === 0) {
                    callback(undefined);
                    return;
                }
                var codes = self.getSelectedCodes();
                self.postMapping(nodeId, codes, function (list) {
                    callback(nodeId, list, opts);
                });
            }
            if ($("#substitutenode-t").hasClass("active") && nt === 1) {
                self.substituteNodeModel().refreshFormNodeSelect(target);
                callback(undefined);
            }
        }
        if (self.mappingType() === 2) {
            var codes = self.getSelectedCodes();
            self.postMapping(nodeId, codes, function (list) {
                callback(nodeId, list, opts);
            });
        }
    };
    self.getSelectedCodes = function () {
        var items = null, item;
        var array = [];
        if (self.mappingType() === 1) {
            for (var j = 0; j < self.childModel().allSelectedRecords().length; j++) {
                var id = self.childModel().allSelectedRecords()[j].id;
                array.push(id);
            }

        } else {
            items = $("#tree_view_l").treeView("selectedItems");
            if (items)
                for (var i = 0; i < items.length; i++) {
                    item = items[i];
                    array.push(item.id + "");
                }
        }
        return array;
    };
    self.postMapping = function (targetId, codes, callback) {
        var model = {
            treeId: self.treeId(),
            balanceSheetId: self.sheetId(),
            nodeId: targetId,
            codes: codes
        };
        if (self.mappingType() === 2) {
            model.showMapped = self.mappingSrcModel().showMapped();
        }
        self.apiService.request({
            splashId: "#treeMap-tre",
            name: "post",
            data: model,
            success: function (data) {
                if (!_h.isNullOrEmpty(data)) {
                    if (_h.any(data.errors)) {
                        callback(undefined);
                    } else {
                        var text;
                        if (self.mappingType() === 1) {
                            text = _h.getApiMessage("TreeMapUpdateSuccess");
                            _h.successToast(text);
                            self.childModel().clearAllSelectedRecords();
                            if (_h.any(data.model)) {
                                self.childModel().refreshTable();
                                callback(data.model);
                            }
                        }
                        if (self.mappingType() === 2) {
                            if (_h.any(data.sourceNodes)) {
                                $("#tree_view_l").treeView("collectOpenBranches");
                                $("#tree_view_l").treeView("refreshTree", data.sourceNodes);
                                $("#tree_view_l").treeView("openBranches");
                            }
                            if (_h.any(data.destNodes)) {
                                callback(data.destNodes);
                            }
                            text = _h.getApiMessage("MappingNodeUpdateSuccess");
                            _h.successToast(text);
                        }
                    }
                }
            },
            error: function () {
                var text = _h.getApiMessage("TreeMapUpdateError");
                _h.failToast(text);
                callback(undefined);
            }
        });
    };
    self.expandAll = function () {
        $("#tree_view").treeView("expandAll");
    };
    self.collapseAll = function () {
        $("#tree_view").treeView("collapseAll");
    };
    self.onDropCallback = function (nodeId, opts, callback) {
        var codes = self.getSelectedCodes();
        self.postMapping(nodeId, codes, function (list) {
            callback(nodeId, list, opts);
        });
    };
    self.changeCaption = function () {
        var rTitle = "", lTitle = "";
        switch (self.mappingType()) {
            case undefined:
                self.caption(rTitle);
                self.childModel().caption(lTitle);
                break;
            case 1:
                rTitle = _h.getLocalizedText("treeDestinationSide");
                self.caption(rTitle);
                lTitle = self.sheetTitle();
                self.childModel().caption(lTitle);
                break;
            case 2:
                rTitle = " ( " + _h.kocnx().currentCompany().pr + " )";
                self.caption(rTitle);
                lTitle = " ( " + _h.kocnx().currentCompany().n + " )";
                self.captionMappingTree(lTitle);
                break;
        }
    };
    self.showFilterItem = function (item) {
        switch (self.mappingType()) {
            case 1:
                return item.type !== 3;
            case 2:
                return item.type !== 2;

            default:
                return true;
        }
    };
    self.init = function () {
        var context = _h.kocnx();
        if (context.loginCompanyType() === 0) {
            self.mappingType(2);

        } else {
            self.getBalancesheetSelectList();
        }

    };
    self.reInit = function () {
        self.treeId(null);
        self.sheetId(null);
        self.childModel(null);
        self.treeTitle("");
        self.sheetTitle("");
        $(".dmn-tree").empty();
        self.records = [];
        self.getBalancesheetSelectList();
    };
    ko.utils.extend(self, new BaseViewModel({
        entityName: "Mapping",
        getList: false,
        apiService: {
            actionList: ["filterby", "post", "delete", "gettreelistwithfiles", "postchangemappingresult"]
        },
        buttons: [],
        filters: [],
        tableStyle: "font-size: 11px;",
        styleRow: "styleRowValue",
        sortDirection: "Ascending",
        sortProperty: "code",
        context: self,
        searchKeyType: "enter",
        cols: mappingtreeModelRes,
        selectRow: false,
        saveState: false,
        contextMenu: false,
        isMultiSelectRows: false
    }));
    self.getRecords = function (callback) {
        var model = {
            treeId: self.treeId(),
            sheetId: self.sheetId(),
            filterType: self.filterType(),
            searchKey: self.searchKey()
        };
        if (self.mappingType() === 1)
            model.mappingSide = 0;
        if (self.mappingType() === 2)
            model.mappingSide = 1;
        self.apiService.request({
            name: "filterBy",
            data: model,
            success: function (data) {
                if (!_h.isNullOrEmpty(data)) {
                    self.isEffected(data.isEffected);
                    self.isTreeEffected(data.isTreeEffected);
                    if (_h.any(data.nodes))
                        self.records = data.nodes;
                    else
                        self.records = [];
                    self.configTools();
                }
                if (callback)
                    callback(true);
            },
            error: function () {
                var text = _h.getApiMessage("ErrorLoadMapTree");
                _h.failToast(text);
                if (callback)
                    callback(false);
            }
        });
    };
}