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

var billsLibObj = {
    stdBillsSpread: null,
    stdBillsJobSpread: null,
    stdBillsFeatureSpread: null,
    checkBillsSpread: function () {
        if (!this.stdBillsSpread) {
            this.stdBillsSpread = SheetDataHelper.createNewSpread($('#stdBillsSpread')[0]);
        }
    },
    refreshBillsSpread: function () {
        if (this.stdBillsSpread) {
            this.stdBillsSpread.refresh();
        }
    },
    checkBillsRelaSpread: function () {
        if (!this.stdBillsJobSpread) {
            this.stdBillsJobSpread = SheetDataHelper.createNewSpread($('#stdBillsJobs')[0]);
        }
        if (!this.stdBillsFeatureSpread) {
            this.stdBillsFeatureSpread = SheetDataHelper.createNewSpread($('#stdBillsFeatures')[0]);
        }
    },
    refreshBillsRelaSpread: function () {
        if (this.stdBillsJobSpread) {
            this.stdBillsJobSpread.refresh();
        }
        if (this.stdBillsFeatureSpread) {
            this.stdBillsFeatureSpread.refresh();
        }
    },
    loadStdBillsLib: function () {
        CommonAjax.post('/stdBillsEditor/getStdBillsLib', {userId: userID}, function (datas) {
            var i, select = $('#stdBillsLibSelect');
            select.empty();
            datas.forEach(function (data) {
                var option = $('<option>').val(data.billsLibId).text(data.billsLibName);
                select.append(option);
            });
            if (select.children.length !== 0) {
                billsLibObj.loadStdBills(select.val());
            }
        });
    },
    loadStdBills: function (stdBillsLibID) {
        var that = this;
        var stdBillsJobData, stdBillsFeatureData, stdBills;
        var stdBillsTree  = idTree.createNew({id: 'ID', pid: 'ParentID', nid: 'NextSiblingID', rootId: -1, autoUpdate: true});
        var stdBillsTreeController = TREE_SHEET_CONTROLLER.createNew(stdBillsTree, billsLibObj.stdBillsSpread.getActiveSheet(), billsLibObj.stdBillsTreeSetting);
        var findData = function (value, field, Array) {
            var i = 0;
            for (i = 0; i < Array.length - 1; i++) {
                if (value === Array[i][field]) {
                    return Array[i];
                }
            }
            return null;
        };
        var getBillsJobs = function (node) {
            var jobs = [], i, jobData = null;
            if (stdBillsJobData && node && node.data.jobs) {
                for (i = 0; i < node.data.jobs.length - 1; i++) {
                    jobData = findData(node.data.jobs[i], 'id', stdBillsJobData);
                    if (jobData) {
                        jobs.push(jobData);
                    }
                }
            }
            return jobs;
        };
        var getBillsFeatures = function (node) {
            var features = [], i, featureData = null;
            if (stdBillsFeatureData && node && node.data.items) {
                for (i = 0; i < node.data.items.length - 1; i++) {
                    featureData = findData(node.data.items[i], 'id', stdBillsFeatureData);
                    if (featureData) {
                        features.push(featureData);
                    }
                }
            }
            return features;
        };
        var showJobs = function (jobs) {
            SheetDataHelper.loadSheetHeader(billsLibObj.jobsSetting, billsLibObj.stdBillsJobSpread.getActiveSheet());
            SheetDataHelper.loadSheetData(billsLibObj.jobsSetting, billsLibObj.stdBillsJobSpread.getActiveSheet(), jobs);
        };
        var showFeatures = function (features) {
            SheetDataHelper.loadSheetHeader(billsLibObj.featuresSetting, billsLibObj.stdBillsFeatureSpread.getActiveSheet());
            SheetDataHelper.loadSheetData(billsLibObj.featuresSetting, billsLibObj.stdBillsFeatureSpread.getActiveSheet(), features);
        };
        var showJobsAndFeatures = function (node) {
            $('#stdBillsJobTab').show();
            $('#stdBillsRemarkTab').hide();
            billsLibObj.checkBillsRelaSpread();
            showJobs(getBillsJobs(node));
            showFeatures(getBillsFeatures(node));
        };
        var showBillsRemark = function (node) {
            $('#stdBillsJobTab').hide();
            $('#stdBillsRemarkTab').show();
            $('#stdBillsRemark').text(node && node.data.recharge ? node.data.recharge : '');
        };
        var showBillsRela = function (node) {
            if (node && node.children.length === 0) {
                showJobsAndFeatures(node);
            } else {
                showBillsRemark(node);
            }
        };

        CommonAjax.post('/stdBillsEditor/getJobContent', {userId: userID, billsLibId: stdBillsLibID}, function (datas) {
            stdBillsJobData = datas;
        }, function () {
            stdBillsJobData = [];
        });
        CommonAjax.post('/stdBillsEditor/getItemCharacter', {userId: userID, billsLibId: stdBillsLibID}, function (datas) {
            stdBillsFeatureData = datas;
        }, function () {
            stdBillsFeatureData = [];
        });
        CommonAjax.post('/stdBillsEditor/getBills', {userId: userID, billsLibId: stdBillsLibID}, function (datas) {
            stdBills = datas;
            stdBillsTree.loadDatas(stdBills);
            stdBillsTreeController.showTreeData();
            showBillsRela(stdBillsTree.firstNode());

            stdBillsTreeController.bind(TREE_SHEET_CONTROLLER.eventName.treeSelectedChanged, showBillsRela);
            that.stdBillsSpread.bind(GC.Spread.Sheets.Events.CellDoubleClick, function (sender, args) {
                if (stdBillsTree.items[args.row].children.length === 0) {
                    ProjectController.addBills(projectObj.project, projectObj.mainController, stdBillsTree.items[args.row]);
                }
            });
        }, function () {
            that.stdBillsSpread.unbind(GC.Spread.Sheets.Events.CellDoubleClick);
        });

        $('#stdBillsSearch>span>button').click(function () {
            var keyword = $('#stdBillsSearch>input').val();

            if (!keyword || keyword === '') {return}

            var result = 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) {
                var sel = billsLibObj.stdBillsSpread.getActiveSheet().getSelections();
                stdBillsTreeController.setTreeSelected(result[0]);
                billsLibObj.stdBillsSpread.getActiveSheet().setSelection(result[0].serialNo(), sel[0].col, 1, 1);

                $('#nextStdBills').show();
                $('#nextStdBills').click(function () {
                    var cur = 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);
                    } else {
                        stdBillsTreeController.setTreeSelected(result[resultIndex + 1]);
                        billsLibObj.stdBillsSpread.getActiveSheet().setSelection(result[resultIndex + 1].serialNo(), sel[0].col, 1, 1);
                    }
                });
            } else {
                $('#nextStdBills').hide();
            }
            $('#stdBillsSearchResultCount').text('搜索结果：' + result.length);
            $('#stdBillsSearchResult').show();
        });
    },
    stdBillsTreeSetting: {
        "treeCol": 0,
        "emptyRows":0,
        "headRows":1,
        "headRowHeight":[
            40
        ],
        "defaultRowHeight": 21,
        "cols":[{
            "width":150,
            "readOnly": true,
            "head":{
                "titleNames":["项目编码"],
                "spanCols":[1],
                "spanRows":[1],
                "vAlign":[1],
                "hAlign":[1],
                "font":["Arial"]
            },
            "data":{
                "field":"code",
                "vAlign":1,
                "hAlign":0,
                "font":"Arial"
            }
        }, {
            "width":120,
            "readOnly": true,
            "head":{
                "titleNames":["项目名称"],
                "spanCols":[1],
                "spanRows":[1],
                "vAlign":[1],
                "hAlign":[1],
                "font":["Arial"]
            },
            "data":{
                "field":"name",
                "vAlign":1,
                "hAlign":0,
                "font":"Arial"
            }
        }, {
            "width":40,
            "readOnly": 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,
            "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,
        "headRowHeight":[25],
        "defaultRowHeight": 21,
        "cols":[{
            "width":200,
            "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,
        "headRowHeight":[25],
        "defaultRowHeight": 21,
        "cols":[{
            "width":200,
            "readOnly":true,
            "head":{
                "titleNames":["项目特征"],
                "spanCols":[1],
                "spanRows":[1],
                "vAlign":[1],
                "hAlign":[1],
                "font":["Arial"]
            },
            "data":{
                "field":"content",
                "vAlign":0,
                "hAlign":3,
                "font":"Arial"
            }
        }]
    }
};

$('#stdBillsTab').bind('click', function () {
    $(".main-data-side-q").height($(window).height() - $(".header").height() - $(".toolsbar").height() -  $(".tools-bar-height-q").height() - 202);
    var select = $('#stdBillsLibSelect');
    billsLibObj.refreshBillsSpread();
    billsLibObj.refreshBillsRelaSpread();
    billsLibObj.checkBillsSpread();
    if (select[0].options.length === 0) {
        billsLibObj.loadStdBillsLib();
    };
});
$('#stdBillsLibSelect').change(function () {
    var select = $(this);
    if (this.children.length !== 0) {
        LoadStdBills(select.val());
    }
});

$('#closeSearchStdBills').click(function () {
    $('#stdBillsSearchResult').hide();
    $(".main-data-side-q").height($(window).height() - $(".header").height() - $(".toolsbar").height() -  $(".tools-bar-height-q").height() - 202);
});