/**
 * Standard Bills Lib
 * Created by Mai on 2017/5/16.
 */

var billsLibObj = {
    doAfterLoadBills: null, //外部设置拉取清单数据后的回调
    stdBillsTree: null,
    stdBillsSpread: null,
    stdBillsJobSpread: null,
    stdBillsFeatureSpread: null,
    refreshSettingForHint: function () {
        TREE_SHEET_HELPER.initSetting($('#stdBillsSpread')[0], billsLibObj.stdBillsTreeSetting);
    },
    checkBillsSpread: function () {
        if (!this.stdBillsSpread) {
            this.stdBillsSpread = SheetDataHelper.createNewSpread($('#stdBillsSpread')[0]);
            sheetCommonObj.spreadDefaultStyle(this.stdBillsSpread);
            this.stdBillsSpread.getSheet(0).name('stdBillsLib_bills');
            // 刷新setting中记录的spread的位置
            this.refreshSettingForHint();
        }
    },
    refreshBillsSpread: function () {
        if (this.stdBillsSpread) {
            this.stdBillsSpread.refresh();
        }
    },
    checkBillsRelaSpread: function () {
        if (!this.stdBillsJobSpread) {
            this.stdBillsJobSpread = SheetDataHelper.createNewSpread($('#stdBillsJobs')[0]);
            sheetCommonObj.spreadDefaultStyle(this.stdBillsJobSpread);
        }
        if (!this.stdBillsFeatureSpread) {
            this.stdBillsFeatureSpread = SheetDataHelper.createNewSpread($('#stdBillsFeatures')[0]);
            sheetCommonObj.spreadDefaultStyle(this.stdBillsFeatureSpread);
        }
    },
    refreshBillsRelaSpread: function () {
        if (this.stdBillsJobSpread) {
            this.stdBillsJobSpread.refresh();
        }
        if (this.stdBillsFeatureSpread) {
            this.stdBillsFeatureSpread.refresh();
        }
    },
    clearHighLight: function (spread) {
        if (spread) {
            let sheet = spread.getActiveSheet();
            sheet.suspendPaint();
            let orgColor = optionsOprObj.getOption('COLOROPTS', 'DEFAULT').backColor;
            sheet.getRange(0, -1, sheet.getRowCount(), -1, GC.Spread.Sheets.SheetArea.viewport).backColor(orgColor);
            sheet.resumePaint();
        }
    },
    setTagForHint: function (nodes) {
        let sheet = this.stdBillsSpread.getActiveSheet();
        sheet.suspendPaint();
        sheet.suspendEvent();
        for(let node of nodes){
            sheet.setTag(node.serialNo(), 2, node.data.ruleText ? node.data.ruleText : '');
        }
        sheet.resumePaint();
        sheet.resumeEvent();
    },
    loadStdBillsLib: function () {
        let i, select = $('#stdBillsLibSelect');
        select.empty();

        let bills_lib = projectObj.project.projectInfo.engineeringInfo.bill_lib;
        let selectedBillsLib = sessionStorage.getItem('stdBillsLib');
        bills_lib.forEach(function (data) {
            var option = $('<option>').val(data.id).text(data.name);
            if(selectedBillsLib && data.id == selectedBillsLib){
                option.attr('selected', 'selected');
            }
            select.append(option);
        });
        if (select.children.length !== 0) {
            billsLibObj.loadStdBills(select.val());
        }
    },
     sortJobsAndFeatures: function (arr) {
        arr.sort(function (a, b) {
            let rst = 0;
            if(a.serialNo > b.serialNo) rst = 1;
            else if(a.serialNo < b.serialNo) rst = -1;
            return rst;
        });
    },
     findData: function (value, field, Array) {
        var i = 0;
        for (i = 0; i < Array.length; i++) {
            if (value[field] == Array[i][field]) {
                return Array[i];
            }
        }
        return null;
    },
    getBillsJobs: function (stdBillsJobData, node) {
        var jobs = [], i, jobData = null;
        if (stdBillsJobData && node && node.data.jobs) {
            for (i = 0; i < node.data.jobs.length; i++) {
                jobData = this.findData(node.data.jobs[i], 'id', stdBillsJobData);
                if (jobData) {
                    jobData.serialNo = node.data.jobs[i].serialNo;
                    jobs.push(jobData);
                }
            }
        }
        this.sortJobsAndFeatures(jobs);
        return jobs;
    },
    getBillsFeatures: function (stdBillsFeatureData, node) {
        var features = [], i, featureData = null;
        if (stdBillsFeatureData && node && node.data.items) {
            for (i = 0; i < node.data.items.length; i++) {
                featureData = this.findData(node.data.items[i], 'id', stdBillsFeatureData);
                if (featureData) {
                    featureData.serialNo = node.data.items[i].serialNo;
                    features.push(featureData);
                }
            }
        }
        this.sortJobsAndFeatures(features);
        return features;
    },
    insertBills: function (stdBillsJobData, stdBillsFeatureData, node) {
        if(projectObj.project.projectInfo.property.lockBills == true && projectObj.project.withinBillsLocked(projectObj.project.mainTree.selected)){
            return false;
        }
        $.bootstrapLoading.start();
        //设置清单备注
        if(node.parent && node.parent.data.recharge){
            node.data.comments = node.parent.data.recharge;
        }
        //特征及内容转化
        pageCCOprObj.setItemContentNode(node, this.getBillsJobs(stdBillsJobData, node), this.getBillsFeatures(stdBillsFeatureData, node), node.data.name);
        if (/\//.test(node.data.unit)) {
            let existB = projectObj.project.Bills.sameStdCodeBillsData(node.data.code);
            if (existB) {
                let std = JSON.parse(JSON.stringify(node.data));
                std.unit = existB.unit;
                let canAdd = ProjectController.addBills(projectObj.project, projectObj.mainController, std);
                if(canAdd === false && $.bootstrapLoading.isLoading()){
                    $.bootstrapLoading.end();
                }
            } else {
                ConfirmModal.stdBillsUnit.check(node.data, function (std) {
                    let canAdd = ProjectController.addBills(projectObj.project, projectObj.mainController, std);
                    if(canAdd === false && $.bootstrapLoading.isLoading()){
                        $.bootstrapLoading.end();
                    }
                }, function () {
                    if($.bootstrapLoading.isLoading()){
                        $.bootstrapLoading.end();
                    }
                });
            }
        } else {
            let canAdd = ProjectController.addBills(projectObj.project, projectObj.mainController, node.data);
            if(canAdd === false && $.bootstrapLoading.isLoading()){
                $.bootstrapLoading.end();
            }
        }
        return true;
    },
    showBillsRela: function (node) {
        if (node && node.children.length === 0) {
            billsLibObj.showJobsAndFeatures(node);
        } else {
            billsLibObj.showBillsRemark(node);
        }
    },
    showJobs:function (jobs) {
        SheetDataHelper.loadSheetHeader(billsLibObj.jobsSetting, billsLibObj.stdBillsJobSpread.getActiveSheet());
        SheetDataHelper.loadSheetData(billsLibObj.jobsSetting, billsLibObj.stdBillsJobSpread.getActiveSheet(), jobs);
    },
    showFeatures: function (features) {
        SheetDataHelper.loadSheetHeader(billsLibObj.featuresSetting, billsLibObj.stdBillsFeatureSpread.getActiveSheet());
        SheetDataHelper.loadSheetData(billsLibObj.featuresSetting, billsLibObj.stdBillsFeatureSpread.getActiveSheet(), features);
    },
    showJobsAndFeatures: function (node) {
        $('#stdBillsJobTab').show();
        $('#stdBillsRemarkTab').hide();
        billsLibObj.refreshBillsRelaSpread();
        billsLibObj.checkBillsRelaSpread();
        this.showJobs(billsLibObj.getBillsJobs(billsLibObj.stdBillsJobData, node));
        this.showFeatures(billsLibObj.getBillsFeatures(billsLibObj.stdBillsFeatureData, node));
    },
    showBillsRemark: function (node) {
        $('#stdBillsJobTab').hide();
        $('#stdBillsRemarkTab').show();
        $('#stdBillsRemark').text(node && node.data.recharge ? node.data.recharge : '');
    },
    loadStdBills: function (stdBillsLibID) {
        var that = this;
        var stdBills;
        if(that.stdBillsTree){
            that.stdBillsTree = null;
        }
        that.stdBillsTree  = idTree.createNew({id: 'ID', pid: 'ParentID', nid: 'NextSiblingID', rootId: -1, autoUpdate: true});
        var stdBillsTreeController = TREE_SHEET_CONTROLLER.createNew(that.stdBillsTree, billsLibObj.stdBillsSpread.getActiveSheet(), billsLibObj.stdBillsTreeSetting);
        $.bootstrapLoading.start();
        CommonAjax.post('/stdBillsEditor/getJobContent', {userId: userID, billsLibId: stdBillsLibID}, function (datas) {
            that.stdBillsJobData = datas;
        }, function () {
            that.stdBillsJobData = [];
        });
        CommonAjax.post('/stdBillsEditor/getItemCharacter', {userId: userID, billsLibId: stdBillsLibID}, function (datas) {
            that.stdBillsFeatureData = datas;
        }, function () {
            that.stdBillsFeatureData = [];
        });
        CommonAjax.post('/stdBillsEditor/getBills', {userId: userID, billsLibId: stdBillsLibID}, function (datas) {
            stdBills = datas;
            that.stdBillsTree.loadDatas(stdBills);
            //读取展开收起状态
            let currentExpState = sessionStorage.getItem('stdBillsLibExpState');
            if(currentExpState){
                that.stdBillsTree.setExpandedByState(that.stdBillsTree.items, currentExpState);
            }
            //非叶子节点默认收起
            else{
                that.stdBillsTree.setRootExpanded(that.stdBillsTree.roots, false);
            }
            stdBillsTreeController.showTreeData();
            //billsLibObj.setTagForHint(that.stdBillsTree.items);
            that.showBillsRela(that.stdBillsTree.firstNode());
            stdBillsTreeController.bind(TREE_SHEET_CONTROLLER.eventName.treeSelectedChanged, that.showBillsRela);
            that.stdBillsSpread.unbind(GC.Spread.Sheets.Events.CellDoubleClick);
            that.stdBillsSpread.bind(GC.Spread.Sheets.Events.CellDoubleClick, function (sender, args) {
                let selectNode = that.stdBillsTree.items[args.row];
                let name = selectNode.data.name;
                if (that.stdBillsTree.items[args.row].children.length === 0) {
                    billsLibObj.insertBills(that.stdBillsJobData, that.stdBillsFeatureData, selectNode);
                }
                else{
                    let me = billsLibObj;
                    let node = that.stdBillsTree.items[args.row];
                    if (!node || node.children.length === 0)
                        return;
                    node.setExpanded(!node.expanded);
                    //设置展开收起状态
                    sessionStorage.setItem('stdBillsLibExpState', that.stdBillsTree.getExpState(that.stdBillsTree.items));
                    TREE_SHEET_HELPER.massOperationSheet(args.sheet, function () {
                        let iCount = node.posterityCount(), i, child;
                        for (i = 0; i < iCount; i++) {
                            child = that.stdBillsTree.items[args.row + i + 1];
                            args.sheet.setRowVisible(args.row + i + 1, child.visible, args.sheetArea);
                        }
                        args.sheet.invalidateLayout();
                    });
                    args.sheet.repaint();
                }
            });
            if(that.doAfterLoadBills){
                that.doAfterLoadBills();
            }
            $.bootstrapLoading.end();
        }, function () {
            that.stdBillsSpread.unbind(GC.Spread.Sheets.Events.CellDoubleClick);
            $.bootstrapLoading.end();
        });

        $('#stdBillsSearch>div>button').click(function () {
            billsLibObj.clearHighLight(billsLibObj.stdBillsSpread);
            var keyword = $('#stdBillsSearch>input').val();
            if (!keyword || keyword === '') {
                $('#stdBillsSearchResult').hide();
                return;
            }

            var result = that.stdBillsTree.items.filter(function (item) {
                var codeIs = item.data.code ? item.data.code.indexOf(keyword) !== -1 : false;
                var nameIs = item.data.name ? item.data.name.indexOf(keyword) !== -1 : false;
                return codeIs || nameIs;
            });
            result.sort(function (x, y) {
                return x.serialNo() - y.serialNo();
            });
            if (result.length !== 0) {
                //展开搜索出来的节点
                billsLibObj.expandSearchNodes(result);
                //设置记住展开
                sessionStorage.setItem('stdBillsLibExpState', that.stdBillsTree.getExpState(that.stdBillsTree.items));
                TREE_SHEET_HELPER.massOperationSheet(billsLibObj.stdBillsSpread.getActiveSheet(), function () {
                    var sel = billsLibObj.stdBillsSpread.getActiveSheet().getSelections();
                    stdBillsTreeController.setTreeSelected(result[0]);
                    billsLibObj.stdBillsSpread.getActiveSheet().setSelection(result[0].serialNo(), sel[0].col, 1, 1);

                    for (let node of result) {
                        billsLibObj.stdBillsSpread.getActiveSheet().getRange(node.serialNo(), -1, 1, -1).backColor('lemonChiffon');
                    }
                });
                billsLibObj.stdBillsSpread.getActiveSheet().showRow(result[0].serialNo(), GC.Spread.Sheets.VerticalPosition.bottom);
                $('#nextStdBills').show();
                $('#nextStdBills').unbind('click');
                $('#nextStdBills').bind('click', function () {
                    var cur = that.stdBillsTree.selected, resultIndex = result.indexOf(cur), sel = billsLibObj.stdBillsSpread.getActiveSheet().getSelections();
                    if (resultIndex === result.length - 1) {
                        stdBillsTreeController.setTreeSelected(result[0]);
                        billsLibObj.stdBillsSpread.getActiveSheet().setSelection(result[0].serialNo(), sel[0].col, 1, 1);
                        billsLibObj.stdBillsSpread.getActiveSheet().showRow(result[0].serialNo(), GC.Spread.Sheets.VerticalPosition.top);
                    } else {
                        stdBillsTreeController.setTreeSelected(result[resultIndex + 1]);
                        billsLibObj.stdBillsSpread.getActiveSheet().setSelection(result[resultIndex + 1].serialNo(), sel[0].col, 1, 1);
                        billsLibObj.stdBillsSpread.getActiveSheet().showRow(result[resultIndex + 1].serialNo(), GC.Spread.Sheets.VerticalPosition.bottom);
                    }
                });
            } else {
                billsLibObj.clearHighLight(billsLibObj.stdBillsSpread);
                $('#nextStdBills').hide();
            }
            $('#stdBillsSearchResultCount').text('搜索结果：' + result.length);
            $('#stdBillsSearchResult').show();
        });
    },
    expandSearchNodes: function(nodes){
        let that = this;
        TREE_SHEET_HELPER.massOperationSheet(billsLibObj.stdBillsSpread.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.stdBillsTreeSetting, that.stdBillsSpread.getActiveSheet(), that.stdBillsTree.roots, true);
            TREE_SHEET_HELPER.refreshNodesVisible(that.stdBillsTree.roots, that.stdBillsSpread.getActiveSheet(), true);
        });
    },
    locateAtBills: function (code) {
        let nineCode = code.substring(0, 9);
        let items = this.stdBillsTree.items;
        let locateBills = _.find(items, function(item){
            return item.data.code === nineCode;
        });
        if(locateBills){
            this.expandSearchNodes([locateBills]);
            sessionStorage.setItem('stdBillsLibExpState', this.stdBillsTree.getExpState(this.stdBillsTree.items));
        }
        let stdBillsSheet = this.stdBillsSpread.getActiveSheet();
        let locateRow = locateBills ? locateBills.serialNo() : 0;
        stdBillsSheet.setActiveCell(locateRow, 0);
        this.showBillsRela(locateBills);
        stdBillsSheet.showRow(locateRow, GC.Spread.Sheets.VerticalPosition.center);
    },
    stdBillsTreeSetting: {
        "emptyRowHeader": true,
        "rowHeaderWidth": 15,
        "treeCol": 0,
        "emptyRows":0,
        "headRows":1,
        "headRowHeight":[
            40
        ],
        "defaultRowHeight": 21,
        "cols":[{
            "width":140,
            "readOnly": true,
            "head":{
                "titleNames":["项目编码"],
                "spanCols":[1],
                "spanRows":[1],
                "vAlign":[1],
                "hAlign":[1],
                "font":["Arial"]
            },
            "data":{
                "field":"code",
                "vAlign":1,
                "hAlign":0,
                "font":"Arial"
            }
        }, {
            "width":190,
            "readOnly": true,
            "head":{
                "titleNames":["项目名称"],
                "spanCols":[1],
                "spanRows":[1],
                "vAlign":[1],
                "hAlign":[1],
                "font":["Arial"]
            },
            "data":{
                "field":"name",
                "vAlign":1,
                "hAlign":0,
                "font":"Arial"
            }
        }, {
            "width":45,
            "readOnly": true,
            "showHint": true,
            "head":{
                "titleNames":["计量单位"],
                "spanCols":[1],
                "spanRows":[1],
                "vAlign":[1],
                "hAlign":[1],
                "font":["Arial"],
                "wordWrap": true
            },
            "data":{
                "field":"unit",
                "vAlign":1,
                "hAlign":1,
                "font":"Arial"
            }
        }/*, {
            "width":100,
            "readOnly": true,
            "showHint": true,
            "head":{
                "titleNames":["工程量计算规则"],
                "spanCols":[1],
                "spanRows":[1],
                "vAlign":[1],
                "hAlign":[1],
                "font":["Arial"]
            },
            "data":{
                "field":"ruleText",
                "vAlign":1,
                "hAlign":0,
                "font":"Arial"
            }
        }*/]
    },
    jobsSetting: {
        "emptyRows":0,
        "headRows":1,
        "rowHeaderWidth": 15,
        "headRowHeight":[25],
        "defaultRowHeight": 21,
        "cols":[{
            "width":160,
            "readOnly":true,
            "head":{
                "titleNames":["工作内容"],
                "spanCols":[1],
                "spanRows":[1],
                "vAlign":[1],
                "hAlign":[1],
                "font":["Arial"]
            },
            "data":{
                "field":"content",
                "vAlign":0,
                "hAlign":3,
                "font":"Arial"
            }
        }]
    },
    featuresSetting: {
        "emptyRows":0,
        "headRows":1,
        "rowHeaderWidth": 15,
        "headRowHeight":[25],
        "defaultRowHeight": 21,
        "cols":[{
            "width":160,
            "readOnly":true,
            "head":{
                "titleNames":["项目特征"],
                "spanCols":[1],
                "spanRows":[1],
                "vAlign":[1],
                "hAlign":[1],
                "font":["Arial"]
            },
            "data":{
                "field":"content",
                "vAlign":0,
                "hAlign":3,
                "font":"Arial"
            }
        }]
    }
};

function addEventOnResize(fn){
    let originFn = window.onresize;
    window.onresize =function () {
        originFn && originFn();
        fn();
    }
}
addEventOnResize(billsLibObj.refreshSettingForHint);
//赋初始高度
if($('#stdBillsSpread').height() === 0 || $('#qd').find('.bottom-content').height() === 0){
    $('#stdBillsSpread').height($(window).height()-$(".header").height()-$(".toolsbar").height()-$(".tools-bar-height-q").height()-312);
    $('#qd').find('.bottom-content').find('.p-0').height(270);
}

$('#stdBillsTab').bind('click', function () {
    if(!projectReadOnly){
        refreshSubSpread();//subSpread、jobSpread、itemSpread显示问题
        var select = $('#stdBillsLibSelect');
        billsLibObj.refreshBillsSpread();
        billsLibObj.refreshBillsRelaSpread();
        billsLibObj.checkBillsSpread();
        if (select[0].options.length === 0) {
            billsLibObj.loadStdBillsLib();
        };
    }
});
$('#stdBillsLibSelect').change(function () {
    $('#stdBillsSearchResult').hide();
    //$(".main-data-side-q").height($(window).height() - $(".header").height() - $(".toolsbar").height() -  $(".tools-bar-height-q").height() - 202);
    billsLibObj.clearHighLight(billsLibObj.stdBillsSpread);

    var select = $(this);
    if (this.children.length !== 0) {
        //设置sessionStorage
        let billsLibId  = select.val();
        sessionStorage.setItem('stdBillsLib', billsLibId);
        //清除展开收起状态sessionStorage
        sessionStorage.removeItem('stdBillsLibExpState');
        billsLibObj.loadStdBills(billsLibId);
    }
});
//搜索框回车
$('#stdBillsSearch>input').bind('keypress', function (event) {
    if(event.keyCode === 13){
        $(this).blur();
        $('#stdBillsSearch>div>button').click();
    }
});

// 关闭搜索结果
$('#closeSearchStdBills').click(function () {
    $('#stdBillsSearchResult').hide();
    $(".main-data-side-q").height($(window).height() - $(".header").height() - $(".toolsbar").height() -  $(".tools-bar-height-q").height() - 202);
    billsLibObj.clearHighLight(billsLibObj.stdBillsSpread);
    billsLibObj.refreshBillsSpread();
    billsLibObj.refreshBillsRelaSpread();
});