/**
 * Standard Ration Lib
 * Created by Mai on 2017/5/16.
 */
/*var rationChapterSpread, sectionRationsSpread;*/

var rationLibObj = {
    searchLimit: 50,
    searchMode: 0,
    libType: {complementary: 0, std: 1},
    compleRationLibId: 'compleRationLib',
    doAfterGetRationTree: null, //获取章节树回调
    doAfterLoadGetRations: null, //获取章节树下定额后回调
    rationChapterSpread: null,
    sectionRationsSpread: null,
    resultSpread: null,
    rationChapterTreeController: null,
    refreshSettingForHint: function () {
        TREE_SHEET_HELPER.initSetting($('#stdSectionRations')[0], rationLibObj.sectionRationsSetting);
    },
    checkSpread: function () {
        if (!this.rationChapterSpread) {
            this.rationChapterSpread = SheetDataHelper.createNewSpread($('#stdRationChapter')[0]);
            this.rationChapterSpread.getSheet(0).options.rowHeaderVisible = false;
            sheetCommonObj.spreadDefaultStyle(this.rationChapterSpread);
            this.rationChapterSpread.getSheet(0).name('stdRationLib_chapter');
            this.rationChapterSpread.bind(GC.Spread.Sheets.Events.CellDoubleClick, this.onChapterSpreadCellDoubleClick);
        }
        if (!this.sectionRationsSpread) {
            this.sectionRationsSpread = SheetDataHelper.createNewSpread($('#stdSectionRations')[0]);
            this.sectionRationsSpread.getSheet(0).setColumnWidth(0, 1, GC.Spread.Sheets.SheetArea.rowHeader);
            sheetCommonObj.spreadDefaultStyle(this.sectionRationsSpread);
            if (!projectReadOnly) {
                this.sectionRationsSpread.bind(GC.Spread.Sheets.Events.CellDoubleClick, this.onRationSpreadCellDoubleClick);
            }
            this.refreshSettingForHint();
        }
    },
    refreshSpread: function () {
        if (this.rationChapterSpread) {
            this.rationChapterSpread.refresh();
        }
        if (this.sectionRationsSpread) {
            this.sectionRationsSpread.refresh();
        }
        if(this.resultSpread){
            this.resultSpread.refresh();
        }
    },
    loadStdRationLibs: async function () {
        let select = $('#stdRationLibSelect');
        select.empty();
        let ration_lib = projectObj.project.projectInfo.engineeringInfo.ration_lib;
        ration_lib.push({
            isDefault: false,
            id: rationLibObj.compleRationLibId,
            name: '我的补充定额'
        });
        const receiveList = await ajaxPost('/pm/api/getReceiveLibList', { user_id: userID, libType: commonConstants.ShareLibType.RATION_LIB });
        const otherCompleLibs = receiveList.map(user => ({ name: `${user.real_name}的补充定额库`, isDefault: false, id: `${rationLibObj.compleRationLibId}*${user._id}`}));
        ration_lib.push(...otherCompleLibs);
        let selectedRationLib = sessionStorage.getItem('stdRationLib');
        ration_lib.forEach(function (data) {
            let option = $('<option>').val(data.id).text(data.name);
            if(selectedRationLib){
                if(data.id == selectedRationLib){
                    option.attr('selected', 'selected');
                }
            }else if(data.isDefault == true){
                option.attr('selected', 'selected');
            }
            select.append(option);
        });
        //我的补充定额库
       /* let $opt = $('<option>').val(rationLibObj.compleRationLibId).text('我的补充定额');
        select.append($opt);*/
        if (select[0].options.length !== 0) {
            rationLibObj.loadStdRation(select.val());
        }
    },
    initQuestionModal: function(row) {
        let node = rationLibObj.tree.items[row];
        while (node && !node.data.explanation){
            node = node.parent;
        }
        let explanation = node && node.data.explanation ? node.data.explanation : '无内容';
        node = rationLibObj.tree.items[row];
        $('#questionContent1').html(explanation);
        while (node && !node.data.ruleText){
            node = node.parent;
        }
        let ruleText = node && node.data.ruleText ? node.data.ruleText : '无内容';
        $('#questionTab1').text('说明');
        $('#questionTab2').text('工程量计算规则');
        $('#questionContent2').html(ruleText);
        $('#questionModal').modal('show');
    },
    hasExplanationRuleText: function(row) {
        let node = rationLibObj.tree.items[row];
        if (!node) {
            return false;
        }
        while (node) {
            if (node.data.explanation || node.data.ruleText) {
                return true;
            }
            node = node.parent;
        }
        return false;
    },
    loadStdRation: function (rationLibIDVal) {
        $.bootstrapLoading.start();
        const [rationLibID, owner] = rationLibIDVal.split('*');
        rationLibObj.curLibType = rationLibID === rationLibObj.compleRationLibId ? rationLibObj.libType.complementary : rationLibObj.libType.std;
        var that = this;
        var showRationChapterTree = function (datas) {
            var rationChapterTree = idTree.createNew({id: 'ID', pid: 'ParentID', nid: 'NextSiblingID', rootId: -1, autoUpdate: false});
            that.tree = rationChapterTree;
            var rationChapterTreeController = TREE_SHEET_CONTROLLER.createNew(rationChapterTree, that.rationChapterSpread.getActiveSheet(), that.rationChapterTreeSetting);
            sheetCommonObj.setColumnWidthByRate($('#stdRationChapter').width() - 40, that.rationChapterSpread, that.rationChapterTreeSetting.cols);
            rationChapterTree.loadDatas(datas);
            //读取展开收起状态
            let currentExpState = sessionStorage.getItem('stdRationLibExpState');
            if(currentExpState){
                that.tree.setExpandedByState(that.tree.items, currentExpState);
            }
            else {
                //展开至第二层
                for(let root of that.tree.roots){
                    root.setExpanded(true);
                    that.tree.setRootExpanded(root.children, false);
                }
            }
            rationChapterTreeController.showTreeData();
            rationLibObj.rationChapterSpread.getSheet(0).options.rowHeaderVisible = true;
            rationChapterTreeController.bind(TREE_SHEET_CONTROLLER.eventName.treeSelectedChanged, function (node) {
                rationLibObj.loadSectionRations(node && node.children.length === 0 ? node.getID() : null);
            });

            if (rationChapterTree.firstNode() && rationChapterTree.firstNode().length === 0) {
                rationLibObj.loadSectionRations(rationChapterTree.firstNode().getID());
            } else {
                rationLibObj.loadSectionRations();
            };
        };
        //type: 0-补充库 1-标准库
        CommonAjax.post('/complementaryRation/api/getRationTree', {owner, userId: userID, rationRepId: rationLibID, type: rationLibObj.curLibType}, function (datas) {
            showRationChapterTree(datas);
            if(that.doAfterGetRationTree){
                that.doAfterGetRationTree();
            }
            $.bootstrapLoading.end();
        }, function () {
            showRationChapterTree([]);
            $.bootstrapLoading.end();
        });
    },
    //双击隐藏显示
    onChapterSpreadCellDoubleClick: function (sender, args) {
        let me = rationLibObj;
        let node = me.tree.items[args.row];
        if (!node || node.children.length === 0)
            return;
        node.setExpanded(!node.expanded);
        sessionStorage.setItem('stdRationLibExpState', me.tree.getExpState(me.tree.items));
        TREE_SHEET_HELPER.massOperationSheet(args.sheet, function () {
            let iCount = node.posterityCount(), i, child;
            for (i = 0; i < iCount; i++) {
                child = me.tree.items[args.row + i + 1];
                args.sheet.setRowVisible(args.row + i + 1, child.visible, args.sheetArea);
            }
            args.sheet.invalidateLayout();
        });
        args.sheet.repaint();
    },
    setTagForHint: function (sheet, datas) {
        sheet.suspendPaint();
        sheet.suspendEvent();
        for(let i = 0, len = sheet.getRowCount(); i < len; i++){
            sheet.setTag(i, 0, '');
        }
        for(let i = 0, len = datas.length; i < len; i++){
            sheet.setTag(i, 0, datas[i].hint ? datas[i].hint : '');
        }
        sheet.resumePaint();
        sheet.resumeEvent();
    },
    loadSectionRations: function (sectionID) {
        let me = this;
        var showDatas = function (datas, setting) {
            let rationSheet = rationLibObj.sectionRationsSpread.getActiveSheet();
            /*TREE_SHEET_HELPER.massOperationSheet(rationSheet, function () {
                rationSheet.setColumnWidth(0, 25, GC.Spread.Sheets.SheetArea.rowHeader);
            });*/
            SheetDataHelper.loadSheetHeader(setting, rationLibObj.sectionRationsSpread.getActiveSheet());
            SheetDataHelper.loadSheetData(setting, rationLibObj.sectionRationsSpread.getActiveSheet(), datas);
            rationLibObj.setTagForHint(rationSheet, datas);
        };
        
        // 去掉第一个空格及空格前面的文本，去掉后面的“(编号：”及之后的文字和字符。取剩余中间的中文及符号
        function getMidlleName(name) {
            const codeReg = /[\(（]编码[:：]/;
            const withCodeReg = /\s(.+)(?=[\(（]编码[:：])/;
            const withoutCodeReg = /\s(.+)/;
            if (!name) {
                return name;
            }
            let tempName = name;;
            if (codeReg.test(name)) {
                const match = withCodeReg.exec(name);
                if (match && match[1]) {
                    tempName = match[1];
                }
            } else if (withoutCodeReg.test(name)) {
                const match = withoutCodeReg.exec(name);
                if (match && match[1]) {
                    tempName = match[1];
                }
            }
            return tempName.trim();
        }
        // 新的处理：
        /*
        1、从定额库提取定额名称，判断其是否含有空格：
        1.1、无空格，则不处理。
        
        1.2、有空格，则取第一个空格前的文本，赋值为a。
        
        2、取定额所属节点名称，去掉第一个空格及空格前面的文本，去掉后面的“(编号：”及之后的文字和字符，剩余中间的中文及符号，赋值为b。
        
        3、比较a、b是否相同：
        
        3.1、相同，则将定额名称显示为去除第一个空格及空格之前的文本f。
        
        3.2、不同，则取定额所属节点的父项，去掉第一个空格及空格前面的文本，去掉后面的“(编号：”及之后的文字和字符，剩余中间的中文及符号，赋值为c。
        
        比较a、c+b是否相同。
        
        3.2.1、相同，则将定额名称显示为去除第一个空格及空格之前的文本f。
        
        3.2.2、不同，则比较a、c是否相同。
        
        3.2.2.1、相同，则将定额名称显示为去除第一个空格及空格之前的文本f。
        
        3.2.2.2、不同，则定额名称显示原始名称。*/
        //@param {String}sectionName(章节节点) {Array}datas(定额数据)
        function simplifyName(sectionItem, datas) {
            if (!sectionItem) {
                return;
            }
            const sectionName = sectionItem.data.name;
            if (!sectionName || !datas || datas.length === 0) {
                return;
            }
            // 定额所属章节节点，章节名称中间值
            const midSectionName = getMidlleName(sectionName); // (b)
            //简化匹配到的定额名称
            const textBeforeFirstSpaceReg = /([^\s]+)\s/;
            const textAfterFirstSpaceReg = /\s(.+)/;
            for (let data of datas) {
                if (!data.name) {
                    continue;
                }
                console.log(data.name);
                const firstTextMatch = textBeforeFirstSpaceReg.exec(data.name);
                const textBeforeFirstSpace = firstTextMatch && firstTextMatch[1]; // (a)
                if (!textBeforeFirstSpace) { // 没有空格直接跳过
                    continue;
                }
                const afterTextMatch = textAfterFirstSpaceReg.exec(data.name);
                const textAfterFirstSpace = afterTextMatch && afterTextMatch[1]; // (f)
                // /\s(.+)/
                if (textBeforeFirstSpace === midSectionName) { // (a === b)
                    data.name = textAfterFirstSpace;
                } else {
                    const parentSectionName = sectionItem.parent && sectionItem.parent.data.name;
                    if (!parentSectionName) {
                        continue;
                    }
                    const midParentSectionName = getMidlleName(parentSectionName); // (c)
                    const combinedSectionName = `${midParentSectionName}${midSectionName}`; // (c + b)
                    if (textBeforeFirstSpace === combinedSectionName || textBeforeFirstSpace === midParentSectionName) { // (a === c + b) || (a === c)
                        data.name = textAfterFirstSpace;
                    }
                }
            }
        }
        //定额名称的处理:
        /*
         * 1、从定额库提取的名称，是否含有空格：
         * 1.1、无，则不处理。
         * 1.2、有，则取第一个空格前的文本，与定额所属节点名称(去掉前面和后面的编号、括号、空格，保留中间的中文及符号)比较是否相同：
         * 1.2.1、不同，则不处理。
         * 1.2.2、相同，则将定额名称显示为去除第一个空格及空格之前的文本。
         */
        /* function simplifyName(sectionName, datas){
            if (!sectionName || !datas || datas.length === 0) {
                return;
            }
            //提取需要匹配的章节名称
            // 去掉后缀
            const suffixReg = /[(（]编码[：:][\w、]+[)）]/;
            const tempName = sectionName.split(suffixReg)[0];
            // 获取第一个空格后的内容
            const sReg = /\s(.+)/;
            const tempTarget = tempName.match(sReg);
            const target = tempTarget ? tempTarget[1] : null;
            if (!target) {
                return;
            }
            //简化匹配到的定额名称
            for (let data of datas) {
                if (!data.name) {
                    continue;
                }
                //第一个空格前的字符串去进行匹配，没有则不匹配
                let nameArr = data.name.split(' ');
                if (nameArr.length <= 1) {
                    continue;
                }
                let matchName = nameArr[0];
                const matchNameWithoutSpace = matchName.replace(/\s/g, '');
                const targetWithoutSpace = target.replace(/\s/g, '');
                if (matchNameWithoutSpace === targetWithoutSpace) {
                    nameArr.shift();
                    data.name = nameArr.join(' ');
                }
            }
        } */
        if (sectionID) {
            const [, owner] = $('#stdRationLibSelect').val().split('*');
            CommonAjax.post('/complementaryRation/api/getRationGljItemsBySection', {user_Id: userID, sectionId: sectionID, type: me.curLibType, owner}, function (datas) {
                const sectionItem = rationLibObj.tree.findNode(sectionID);
                simplifyName(sectionItem, datas);
                showDatas(datas, rationLibObj.sectionRationsSetting);
                if(me.doAfterLoadGetRations){
                    me.doAfterLoadGetRations(datas);
                    me.doAfterLoadGetRations = null;
                }
            }, function () {
                showDatas([], rationLibObj.sectionRationsSetting);
            });
        } else {
            showDatas([], rationLibObj.sectionRationsSetting);
        }
    },
    onRationSpreadCellDoubleClick: function (sender, args) {
        var select = $('#stdRationLibSelect'), rationCode = args.sheet.getText(args.row, 0);
        if (rationCode !== '' && projectObj.project.Ration.canAdd(projectObj.project.mainTree.selected)) {
            const [rationLibID, owner] = select.val().split('*');
            let query = {userID: owner || userID, rationRepId: rationLibID, code: rationCode};
            //搜索结果全部定额中双击添加定额、有可能同名不同库，更新查询的库ID
            if (rationLibObj.resultCache && rationLibObj.resultCache[args.row]) {
                query.rationRepId = rationLibObj.resultCache[args.row].type === 'std' ? rationLibObj.resultCache[args.row].rationRepId : rationLibObj.compleRationLibId;
            }
            projectObj.project.Ration.addNewRation(query,rationType.ration, function () {
                projectObj.setActiveCell('quantity', true);
            });
        }
    },
    //滚动条到底部加载
    onRationSpreadTopRowChanged: function (sender, args) {
        let me = rationLibObj;
        if(me.searching) {
            return;
        }
        let bottomRow = args.sheet.getViewportBottomRow(1),
            rowCount = args.sheet.getRowCount();
        //滚到了底部
        if (bottomRow + 1 - me.sectionRationsSetting.emptyRows === rowCount - me.sectionRationsSetting.emptyRows) {
            seachRation();
        }
    },
    loadStdRationContextMenu: function () {
        let rationSpread = rationLibObj.sectionRationsSpread, rationSheet = rationSpread.getActiveSheet(),  rationModel = projectObj.project.Ration;;
        $.contextMenu({
            selector: '#stdSectionRations',
            build: function ($trigger, e) {
                let target = SheetDataHelper.safeRightClickSelection($trigger, e, rationSpread);
                return target.hitTestType === GC.Spread.Sheets.SheetArea.viewport || target.hitTestType === GC.Spread.Sheets.SheetArea.rowHeader;
            },
            items: {
                "insertStdRation": {
                    name: "插入定额",
                    icon: 'fa-sign-in',
                    disabled: function () {
                        return projectReadOnly || !projectObj.project.Ration.canAdd(projectObj.project.mainTree.selected);
                    },
                    callback: function (key, opt) {
                        let select = $('#stdRationLibSelect'), rationSelect = rationSheet.getSelections();
                        let rationCode = rationSelect.length > 0 ? rationSheet.getText(rationSelect[0].row, 0) : '';
                        if (rationCode !== '') {
                            rationModel.addNewRation({userID: userID, rationRepId: select.val(), code: rationCode},rationType.ration, function () {
                            });
                        }
                    }
                },
                "replaceStdRation": {
                    name: "替换定额",
                    icon: 'fa-sign-in',
                    disabled: function () {
                        return projectReadOnly || !projectObj.project.Ration.canAdd(projectObj.project.mainTree.selected);
                    },
                    callback: function (key, opt) {
                        let select = $('#stdRationLibSelect'), rationSelect = rationSheet.getSelections();
                        let rationCode = rationSelect.length > 0 ? rationSheet.getText(rationSelect[0].row, 0) : '';
                        let mainTreeSelected = projectObj.project.mainTree.selected;
                        if (rationCode !== ''&&mainTreeSelected&&mainTreeSelected.sourceType == rationModel.getSourceType()) {
                            rationModel.updateRationCodes([{'node':mainTreeSelected,value:rationCode}]);
                        }
                    }
                },
            }
        });
    },
    expandSearchNodes: function(nodes){
        let that = rationLibObj;
        TREE_SHEET_HELPER.massOperationSheet(that.rationChapterSpread.getActiveSheet(), function () {
            function expParentNode(node){
                if(node.parent){
                    expParentNode(node.parent);
                    if(!node.parent.expanded){
                        node.parent.setExpanded(true);
                    }
                }
            }
            for(let node of nodes){
                expParentNode(node);
            }
            TREE_SHEET_HELPER.refreshTreeNodeData(that.rationChapterTreeSetting, that.rationChapterSpread.getActiveSheet(), that.tree.roots, true);
            TREE_SHEET_HELPER.refreshNodesVisible(that.tree.roots, that.rationChapterSpread.getActiveSheet(), true);
        });
    },
    initSel: function (row) {
        let me = this;
        let sheet = me.rationChapterSpread.getActiveSheet();
        sheet.setActiveCell(row, 0);
        sheet.showRow(row, GC.Spread.Sheets.VerticalPosition.center);
        let sectionNode = me.tree.items[row] || null;
        me.loadSectionRations(sectionNode && sectionNode.children.length === 0 ? sectionNode.data.ID : null);
    },
    locateAtRation: function(libID, code){
        if(!isDef(libID)) return;
        let me = rationLibObj;
        if ($('#rationSearchResult').is(':visible')) {
            $('#rationSearchResult a').click();
        }
        //查找定额，以确定定额所在章节节点
        let locateRow = 0,
            locateSubRow = 0;
        CommonAjax.post('/complementaryRation/api/getRationItem', {rationRepIds: [libID], code: code}, function (ration) {
            if(ration && ration.sectionId){
                let sectionNode = me.tree.findNode(ration.sectionId);
                if(sectionNode){
                    me.expandSearchNodes([sectionNode]);
                    sessionStorage.setItem('stdRationLibExpState', me.tree.getExpState(me.tree.items));
                }
                locateRow = sectionNode.serialNo();
                me.doAfterLoadGetRations = function (rationItems) {
                    let rationSheet = me.sectionRationsSpread.getActiveSheet();
                    locateSubRow = _.findIndex(rationItems, {ID: ration.ID});
                    rationSheet.setActiveCell(locateSubRow, 0);
                    rationSheet.showRow(locateSubRow, GC.Spread.Sheets.VerticalPosition.center);
                };
                me.initSel(locateRow);
            }
            else {
                me.initSel(locateRow);
            }
        }, function () {
            me.initSel(locateRow);
        });
    },
    rationChapterTreeSetting: {
        "emptyRowHeader": true,
        "rowHeaderWidth": 1,
        "emptyRows":0,
        "headRows":1,
        "headRowHeight":[30],
        "defaultRowHeight": 21,
        "treeCol": 0,
        "cols":[{
            "rateWidth": 1,
            "width":400,
            "readOnly": true,
            "head":{
                "titleNames":["名称"],
                "spanCols":[1],
                "spanRows":[1],
                "vAlign":[1],
                "hAlign":[1],
                "font":["Arial"]
            },
            "data":{
                "field":"name",
                "vAlign":1,
                "hAlign":0,
                "font":"Arial"
            }
        }]
    },
    sectionRationsSetting: {
        "emptyRowHeader": true,
        "rowHeaderWidth": 1,
        "emptyRows":3,
        "headRows":1,
        "headRowHeight":[20],
        "defaultRowHeight": 21,
        "cols":[{
            "width":60,
            "readOnly": true,
            "showHint": true,
            "head":{
                "titleNames":["编码"],
                "spanCols":[1],
                "spanRows":[1],
                "vAlign":[1],
                "hAlign":[1],
                "font":["Arial"]
            },
            "data":{
                "field":"code",
                "vAlign":1,
                "hAlign":0,
                "font":"Arial"
            }
        }, {
            "width":220,
            "readOnly": true,
            "showHint": true,
            "head":{
                "titleNames":["名称"],
                "spanCols":[1],
                "spanRows":[1],
                "vAlign":[1],
                "hAlign":[1],
                "font":["Arial"]
            },
            "data":{
                "field":"name",
                "vAlign":1,
                "hAlign":0,
                "font":"Arial"
            }
        }, {
            "width":55,
            "readOnly":true,
            "head":{
                "titleNames":["单位"],
                "spanCols":[1],
                "spanRows":[1],
                "vAlign":[1],
                "hAlign":[1],
                "font":["Arial"]
            },
            "data":{
                "field":"unit",
                "vAlign":1,
                "hAlign":1,
                "font":"Arial"
            }
        }, {
            "width":60,
            "readOnly":true,
            "head":{
                "titleNames":["基价"],
                "spanCols":[1],
                "spanRows":[1],
                "vAlign":[1],
                "hAlign":[1],
                "font":["Arial"]
            },
            "data":{
                "field":"basePrice",
                "vAlign":1,
                "hAlign":2,
                "font":"Arial"
            }
        }]
    },
    getStdRationLibIDs: function () {
        let ids = [];
        if(projectObj.project.projectInfo.engineeringInfo.ration_lib.length === 0){
            alert('当前项目无定额库，请添加定额库。');
            return null;
        }
        for(let rationLib of projectObj.project.projectInfo.engineeringInfo.ration_lib){
            ids.push(rationLib.id);
        }
        return ids;
    },
    getCurrentStdRationLibID:function () {
        if(projectObj.project.projectInfo.engineeringInfo.ration_lib.length === 0){
            alert('当前项目无定额库，请添加定额库。');
            return null;
        }
        if($('#stdRationLibSelect').val()){
            return parseInt($('#stdRationLibSelect').val());
        }else {
            return projectObj.project.projectInfo.engineeringInfo.ration_lib[0].id;
        }
    },
    getFirstStdRationLibID: function () {
        if(projectObj.project.projectInfo.engineeringInfo.ration_lib.length === 0){
            alert('当前项目无定额库，请添加定额库。');
            return null;
        }
        return parseInt(projectObj.project.projectInfo.engineeringInfo.ration_lib[0].id);
    },
    getDefaultStdRationLibID:function(){
        let ration_lib = projectObj.project.projectInfo.engineeringInfo.ration_lib;
        if(ration_lib.length === 0){
            alert('当前项目无定额库，请添加定额库。');
            return null;
        }
        let defaultLib = _.find(ration_lib,{'isDefault':true});
        let libID = defaultLib?defaultLib.id:ration_lib[0].id;
        return parseInt(libID);
    },
    //@param {Array}datas(resultCache) @return {Object}
    //搜索skip信息,不能被每页搜索数整除，则说明上次搜索已经搜索完整
    getSearchSkip: function (datas) {
        if (datas.length % this.searchLimit !== 0) {
            return null;
        }
        let skip = {std: 0, comple: 0};
        if (!datas || !Array.isArray(datas) || datas.length === 0) {
            return skip;
        }
        for (let data of datas) {
            if (data.type === 'std') {
                skip.std++;
            } else {
                skip.comple++;
            }
        }
        return skip;
    }
};

addEventOnResize(rationLibObj.refreshSettingForHint);
//赋初始高度
if($('#stdRationChapter').height() === 0 || $('#stdSectionRations').height() === 0){
    $('#stdRationChapter').height($(window).height()-$(".header").height()-$(".toolsbar").height()-$(".tools-bar-height-q").height()-312);
    $('#stdSectionRations').height(270);
}

$('#stdRationTab').bind('click', async function () {
    var select = $('#stdRationLibSelect');
    rationLibObj.checkSpread();
    if (select[0].options.length === 0) {
        try {
            await rationLibObj.loadStdRationLibs();
        } catch (err) {
            alert(err);
        }
        rationLibObj.loadStdRationContextMenu();
    };
});
$('#stdRationLibSelect').change(function () {
    var select = $(this);
    if (this.children.length !== 0) {
        let rationLibId = select.val();
        sessionStorage.setItem('stdRationLib', rationLibId);
        sessionStorage.removeItem('stdRationLibExpState');
        rationLibObj.loadStdRation(rationLibId);
    }
});
//回车键搜索
$('#rationSearchKeyword').bind('keypress', function (event) {
    if(event.keyCode === 13){
        $(this).blur();
        $('#rationSearch').click();
    }
});
$('#rationSearchKeyword').keyup(function () {
    let keyword = $('#rationSearchKeyword').val();
    if(keyword === ''){
        if($('#rationSearchResult').is(':visible')){
            rationLibObj.resultCache = [];
            $('#rationSearchResult').hide();
            $(".main-data-side-search", $('#rationSearchResult')).height(0);
            switchRationSearchMode(0);
            autoFlashHeight();
            rationLibObj.refreshSpread();
        }
    }
});

//变换搜索本定额、全部定额状态
function switchRationSearchMode(mode) {
    rationLibObj.searchMode = mode;
    rationLibObj.resultCache = [];
    //搜索本定额
    if(mode === 0){
        $('#curRationLib').removeClass('btn-light');
        $('#curRationLib').addClass('btn-secondary');
        $('#allRationLibs').removeClass('btn-secondary');
        $('#allRationLibs').addClass('btn-light');
    } else {//搜索全部定额
        $('#allRationLibs').removeClass('btn-light');
        $('#allRationLibs').addClass('btn-secondary');
        $('#curRationLib').removeClass('btn-secondary');
        $('#curRationLib').addClass('btn-light');
    }
}

//搜索本定额
$('#curRationLib').click(function () {
    if($(this).hasClass('btn-secondary')){
        return;
    }
    switchRationSearchMode(0);
    $('#rationSearch').click();
});

//搜索全部定额
$('#allRationLibs').click(function () {
    if($(this).hasClass('btn-secondary')){
        return;
    }
    switchRationSearchMode(1);
    $('#rationSearch').click();
});

//搜索
function seachRation(){
    let skip = rationLibObj.getSearchSkip(rationLibObj.resultCache);
    if (!skip) {
        return;
    }
    rationLibObj.searching = true;
    var keyword = $('#rationSearchKeyword').val();
    if(keyword === ''){
        if($('#rationSearchResult').is(':visible')){
            rationLibObj.resultCache = [];
            $('#rationSearchResult').hide();
            $(".main-data-side-search", $('#rationSearchResult')).height(0);
            autoFlashHeight();
            rationLibObj.refreshSpread();
        }
        return;
    }
    //获取搜索定额的库：本库/所有库
    let rationLibIDs = [];
    if($('#curRationLib').hasClass('btn-secondary')){
        rationLibIDs.push($('#stdRationLibSelect').val());
    } else {
        for(let lib of projectObj.project.projectInfo.engineeringInfo.ration_lib){
            rationLibIDs.push(lib.id);
        }
    }
    let bindContextmenuOpr = function (sheet) {
        $.contextMenu({
            selector: '#rationSearchResult',
            build: function($triggerElement, e){
                //控制允许右键菜单在哪个位置出现
                let offset = $('.main-data-side-search').offset(),
                    x = e.pageX - offset.left,
                    y = e.pageY - offset.top;
                let target = sheet.hitTest(x, y);
                if(target.hitTestType === 3 && typeof target.row !== 'undefined' && typeof target.col !== 'undefined'){//在表格内
                    sheet.setActiveCell(target.row, target.col);
                    return {
                        callback: function(){},
                        items: {
                            "locate": {
                                name: "定位至章节",
                                disabled: function () {
                                    return target.row >= rationLibObj.resultCache.length;
                                },
                                icon: "fa-arrow-left",
                                callback: function (key, opt) {
                                    let data = rationLibObj.resultCache[target.row],
                                        libId = data.rationRepId ? data.rationRepId : rationLibObj.compleRationLibId;
                                    $('#rationSearchResult').hide();
                                    $(".main-data-side-search", $('#rationSearchResult')).height(0);
                                    autoFlashHeight();
                                    rationLibObj.refreshSpread();
                                    switchRationSearchMode(0);
                                    if($('#stdRationLibSelect').select().val() != libId){
                                        let libOpts = $('#stdRationLibSelect').find('option');
                                        for(let libOpt of libOpts){
                                            if($(libOpt).val() == libId){
                                                $(libOpt).prop('selected', 'selected');
                                                break;
                                            }
                                        }
                                        $('#stdRationLibSelect').change();
                                        rationLibObj.doAfterGetRationTree = function () {
                                            this.locateAtRation(libId, data.code);
                                            this.doAfterGetRationTree = null;
                                        };
                                    } else {
                                        rationLibObj.locateAtRation(libId, data.code);
                                    }
                                }}
                        }
                    };
                }
                else{
                    return false;
                }
            }
        });
    };
    const searchCurRationSetting = _.cloneDeep(rationLibObj.sectionRationsSetting);
    // 搜索全部定额，表格需要多显示一列定额库
    const searchAllRationSetting = _.cloneDeep(rationLibObj.sectionRationsSetting);
    searchAllRationSetting.cols.push({
        "width": 100,
        "readOnly": true,
        "showHint": true,
        "head": {
            "titleNames": ["定额库"],
            "spanCols": [1],
            "spanRows": [1],
            "vAlign": [1],
            "hAlign": [1],
            "font": ["Arial"]
        },
        "data": {
            "field": "rationLibName",
            "vAlign": 1,
            "hAlign": 0,
            "font": "Arial"
        }
    });
    const rationSetting = rationLibObj.searchMode === 0 ? searchCurRationSetting : searchAllRationSetting;
    var showResult = function (result) {
        if(!rationLibObj.resultSpread){
            let resultSpread = SheetDataHelper.createNewSpread($('.main-data-side-search')[0]);
            rationLibObj.resultSpread = resultSpread;
            bindContextmenuOpr(resultSpread.getActiveSheet());
            //SheetDataHelper.loadSheetHeader(rationLibObj.sectionRationsSetting, resultSpread.getActiveSheet());
            if (!projectReadOnly) {
                resultSpread.bind(GC.Spread.Sheets.Events.CellDoubleClick, rationLibObj.onRationSpreadCellDoubleClick);
            }
            resultSpread.bind(GC.Spread.Sheets.Events.TopRowChanged, rationLibObj.onRationSpreadTopRowChanged);
        }else {
            rationLibObj.resultSpread.refresh();
        }
        SheetDataHelper.loadSheetHeader(rationSetting, rationLibObj.resultSpread.getActiveSheet());
        SheetDataHelper.loadSheetData(rationSetting, rationLibObj.resultSpread.getActiveSheet(), result);
        rationLibObj.setTagForHint(rationLibObj.resultSpread.getActiveSheet(), result);
        rationLibObj.resultCache = result;
    };
    $.bootstrapLoading.start();
    CommonAjax.post('/complementaryRation/api/findRation', {'user_id': userID, 'rationRepId': rationLibIDs, 'keyword': keyword, skip: skip}, function (result) {
        var resultObj = $('#rationSearchResult');
        if (result.count !== null) {
            $('#rationSearchCount').text(`搜索结果：${result.count}`);
        }
        $('a', resultObj).unbind('click');
        $('a', resultObj).bind('click', function () {
            rationLibObj.resultCache = [];
            switchRationSearchMode(0);
            resultObj.hide();
            $(".main-data-side-search", resultObj).height(0);
            autoFlashHeight();
            loadSideToolsHeight();
        });
        resultObj.show();
        $(".main-data-side-search", resultObj).height($(window).height() - $(".header").height() - $(".toolsbar").height() - 64);
        showResult(rationLibObj.resultCache.concat(result.data));
        rationLibObj.searching = false;
        //以防一开始就需要加载后面的分页数据
        if (result.data.length > 0) {
            rationLibObj.onRationSpreadTopRowChanged({}, {sheet: rationLibObj.resultSpread.getActiveSheet()});
        }
        $.bootstrapLoading.end();
    }, function () {
        rationLibObj.searching = false;
        $.bootstrapLoading.end();
    });
}
$('#rationSearch').click(function () {
    rationLibObj.resultCache = [];
    seachRation();
});
