/**
 * Created by Tony on 2017/4/28.
 */

$("#gongliao").click(function(){
    $(this).attr('href', "/rationRepository/lmm" + "?repository=" + getQueryString("repository"))
});

$("#fuzhu").click(function(){
    $(this).attr('href', "/rationRepository/coeList" + "?repository=" + getQueryString("repository"))
});

var rationOprObj = {
    workBook: null,
    currentRations: {},
    currentEditingRation: null,
    currentSectionId: -1,
    setting: {
        header:[
            {headerName:"编码",headerWidth:120,dataCode:"code", dataType: "String", formatter: "@"},
            {headerName:"名称",headerWidth:300,dataCode:"name", dataType: "String"},
            {headerName:"单位",headerWidth:120,dataCode:"unit", dataType: "String", hAlign: "center"},
            {headerName:"基价",headerWidth:120,dataCode:"basePrice", dataType: "Number", formatter: "0.00", hAlign: "right"},
            {headerName:"显示名称（以%s表示参数）",headerWidth:350,dataCode:"caption", dataType: "String"},
            {headerName:"取费专业",headerWidth:120,dataCode:"feeType", dataType: "Number", hAlign: "center"}
        ],
        view:{
            comboBox:[
                {row:-1,col:2,rowCount:-1,colCount:1}
            ],
            lockedCells:[
                {row:-1,col:3,rowCount:-1, colCount:1}
            ]
        }
    },
    buildSheet: function(container) {
        var me = rationOprObj;
        me.workBook = sheetCommonObj.buildSheet(container, me.setting, 30);
        me.workBook.getSheet(0).bind(GC.Spread.Sheets.Events.ClipboardPasting, me.onClipboardPasting);
        me.workBook.getSheet(0).bind(GC.Spread.Sheets.Events.ClipboardPasted, me.onClipboardPasted);
        me.workBook.getSheet(0).bind(GC.Spread.Sheets.Events.EditStarting, me.onCellEditStart);
        me.workBook.getSheet(0).bind(GC.Spread.Sheets.Events.EditEnded, me.onCellEditEnd);
        me.workBook.getSheet(0).bind(GC.Spread.Sheets.Events.RangeChanged, me.onRangeChanged);
        me.workBook.getSheet(0).bind(GC.Spread.Sheets.Events.CellClick, me.onCellClick);
    },
    onCellClick: function(sender, args) {
        var me = rationOprObj, sheet = rationGLJOprObj.workBook.getSheet(0), setting = rationGLJOprObj.setting;
        if(args.sheetArea === GC.Spread.Sheets.SheetArea.colHeader || args.sheetArea === GC.Spread.Sheets.SheetArea.corner){
            sheetCommonObj.cleanSheet(sheet, setting, -1);
            sheetCommonObj.shieldAllCells(sheet);
        } else {
            sheetCommonObj.cleanSheet(sheet, setting, -1);
            sheetCommonObj.shieldAllCells(sheet);
            var cacheSection = me.getCache();
            if (cacheSection && args.row < cacheSection.length) {
                rationGLJOprObj.getGljItems(cacheSection[args.row]);
            }
        }
        me.workBook.focus(true);
    },
    getCache: function() {
        var me = this, rst = me.currentRations["_SEC_ID_" + me.currentSectionId];
        if (!(rst)) {
            me.currentRations["_SEC_ID_" + me.currentSectionId] = [];
            rst = me.currentRations["_SEC_ID_" + me.currentSectionId];
        }
        return rst;
    },
    updateCache: function(addArr, updateArr, removeIds, result) {
        var me = this, cacheSection = me.getCache();
        if (addArr.length > 0) {
            me.currentRations["_SEC_ID_" + me.currentSectionId] = cacheSection.concat(addArr);
            cacheSection = me.currentRations["_SEC_ID_" + me.currentSectionId];
        }
        for (var i = removeIds.length - 1; i >= 0; i--) {
            for (var j = cacheSection.length - 1; j >= 0 ; j--) {
                if (cacheSection[j]["ID"] == removeIds[i]) {
                    cacheSection.splice(j,1);
                }
            }
        }
        if (result && result.data.ops && result.data.ops.length > 0) {
            for (var i = 0; i < result.data.ops.length; i++) {
                for (var j = 0; j < cacheSection.length; j++) {
                    if (cacheSection[j][me.setting.header[0].dataCode] == result.data.ops[i][me.setting.header[0].dataCode]) {
                        cacheSection[j]["ID"] = result.data.ops[i]["ID"];
                        cacheSection[j]["rationGljList"] = result.data.ops[i]["rationGljList"];
                    }
                }
            }
        }
        for (var i = 0; i < updateArr.length; i++) {
            for (var j = 0; j < cacheSection.length; j++) {
                if (updateArr[i]["ID"] && cacheSection[j]["ID"]) {
                    if (cacheSection[j]["ID"] == updateArr[i]["ID"]) {
                        cacheSection[j] = updateArr[i];
                    }
                } else {
                    if (cacheSection[j][me.setting.header[0].dataCode] == updateArr[i][me.setting.header[0].dataCode]) {
                        cacheSection[j] = updateArr[i];
                    }
                }
            }
        }
        return cacheSection;
    },
    onRangeChanged: function(sender, args) {
        if (args.action == GC.Spread.Sheets.RangeChangedAction.clear) {
            var me = rationOprObj, updateArr = [], removeArr = [];
            var cacheSection = me.getCache();
            if (cacheSection) {
                for (var i = 0; i < args.rowCount; i++) {
                    var hasUpdate = false, rObj = sheetCommonObj.combineRowData(me.workBook.getSheet(0), me.setting, args.row + i),
                        isEmpty = sheetCommonObj.chkIfEmpty(rObj, me.setting);
                    for (var j = 0; j < cacheSection.length; j++) {
                        if (cacheSection[j][me.setting.header[0].dataCode] == rObj[me.setting.header[0].dataCode]) {
                            rObj["ID"] = cacheSection[j]["ID"];
                            hasUpdate = true;
                            break;
                        }
                    }
                    if (hasUpdate) {
                        if (isEmpty) {
                            removeArr.push(rObj);
                        } else updateArr.push(rObj);
                    } else if (isEmpty) {
                        if (args.row + i < cacheSection.length) {
                            rObj["ID"] = cacheSection[args.row + i]["ID"];
                            removeArr.push(rObj["ID"]);
                        }
                    }
                }
                me.mixUpdateRequest(updateArr, [], removeArr);
                //removeRationItems
            }
        }
    },
    onCellEditStart: function(sender, args) {
        var me = rationOprObj;
        var rObj = sheetCommonObj.combineRowData(me.workBook.getSheet(0), me.setting, args.row);
        me.currentEditingRation = rObj;
        var cacheSection = me.getCache();
        if (cacheSection) {
            for (var j = 0; j < cacheSection.length; j++) {
                if (cacheSection[j][me.setting.header[0].dataCode] == rObj[me.setting.header[0].dataCode]) {
                    rObj["ID"] = cacheSection[j]["ID"];
                    break;
                }
            }
        }
    },
    onCellEditEnd: function(sender, args) {
        var me = rationOprObj, rObj = sheetCommonObj.combineRowData(me.workBook.getSheet(0), me.setting, args.row),
            updateArr = [], addArr = [];
        if (me.currentEditingRation["ID"]) {
            rObj["ID"] = me.currentEditingRation["ID"];
            updateArr.push(rObj);
        } else {
            if (!sheetCommonObj.chkIfEmpty(rObj, me.setting)) {
                addArr.push(rObj);
            }
        }
        me.currentEditingRation = null;
        if (updateArr.length > 0 || addArr.length > 0) {
            me.mixUpdateRequest(updateArr, addArr, []);
        }
    },
    onClipboardPasting: function(sender, args) {
        var me = rationOprObj;
        if (args.cellRange.colCount != me.setting.header.length) {
            args.cancel = true;
        }
    },
    onClipboardPasted: function(e, info) {
        var me = rationOprObj;
        var cacheSection = me.getCache();
        var updateArr = [], addArr = [];
        var items = sheetCommonObj.analyzePasteData(me.setting, info);
        for (var i = 0; i < items.length; i++) {
            if (cacheSection) {
                var hasCacheItem = false;
                for (var j = 0; j < cacheSection.length; j++) {
                    if (cacheSection[j][me.setting.header[0].dataCode] == items[i][me.setting.header[0].dataCode]) {
                        hasCacheItem = true;
                        items[i]["ID"] = cacheSection[j]["ID"];
                        break;
                    }
                }
                if (!hasCacheItem) {
                    addArr.push(items[i]);
                } else {
                    updateArr.push(items[i]);
                }
            } else {
                addArr.push(items[i])
            }
        };
        if (updateArr.length > 0 || addArr.length > 0) {
            me.mixUpdateRequest(updateArr, addArr, []);
        }
    },
    mixUpdateRequest: function(updateArr, addArr, removeIds) {
        var me = rationOprObj;
        $.ajax({
            type:"POST",
            url:"api/mixUpdateRationItems",
            data:{"sectionID": me.currentSectionId, "updateItems": JSON.stringify(updateArr), "addItems": JSON.stringify(addArr), "removeIds": JSON.stringify(removeIds)},
            dataType:"json",
            cache:false,
            timeout:5000,
            success:function(result){
                if (result.err) {
                    alert(err);
                    me.getRationItems(me.currentSectionId);
                } else {
                    var cacheSection = me.updateCache(addArr, updateArr, removeIds, result);
                    cacheSection.sort(function(a, b){
                        var rst = 0;
                        if (a.code > b.code) rst = 1
                        else if (a.code < b.code) rst = -1;
                        return rst;
                    });
                    me.showRationItems(me.currentSectionId);
                }
            },
            error:function(){
            }
        });
    },
    getRationItems: function(sectionID){
        if (sectionID != -1) {
            var me = rationOprObj;
            me.currentSectionId = sectionID;
            if (me.currentRations["_SEC_ID_" + sectionID]) {
                me.showRationItems(sectionID);
                sheetCommonObj.unShieldAllCells(me.workBook.getSheet(0));
                sheetCommonObj.lockCells(rationGLJOprObj.workBook.getSheet(0), rationGLJOprObj.setting);
            } else {
                $.ajax({
                    type:"POST",
                    url:"api/getRationItems",
                    data:{"sectionID": sectionID},
                    dataType:"json",
                    cache:false,
                    timeout:1000,
                    success:function(result){
                        if (result) {
                            me.currentRations["_SEC_ID_" + sectionID] = result.data;
                            me.showRationItems(sectionID);
                            sheetCommonObj.unShieldAllCells(me.workBook.getSheet(0));
                            sheetCommonObj.lockCells(rationGLJOprObj.workBook.getSheet(0), rationGLJOprObj.setting);
                        } else {
                            sheetCommonObj.shieldAllCells(me.workBook.getSheet(0));
                            sheetCommonObj.shieldAllCells(rationGLJOprObj.workBook.getSheet(0));
                        }
                    },
                    error:function(err){
                        alert(err);
                    }
                })
            }
        }
    },
    showRationItems: function(sectionID){
        var me = rationOprObj;
        if (me.workBook) {
            if (me.currentRations && me.currentRations["_SEC_ID_" + sectionID] && me.currentRations["_SEC_ID_" + sectionID].length > 0) {
                var cacheSection = me.currentRations["_SEC_ID_" + sectionID];
                sheetCommonObj.cleanSheet(me.workBook.getSheet(0), me.setting, -1);
                sheetCommonObj.showData(me.workBook.getSheet(0), me.setting, cacheSection);
            } else {
                //清除ration数据及工料机数据
                sheetCommonObj.cleanSheet(me.workBook.getSheet(0), me.setting, -1);
            }
        }
    }
}