/**
 * Created by Tony on 2017/4/28.
 */
var rationGLJOprObj = {
    workBook: null,
    currentRationItem: null,
    cache: {},
    setting: {
        header:[
            {headerName:"编码",headerWidth:160,dataCode:"code", dataType: "String", formatter: "@"},
            {headerName:"名称",headerWidth:400,dataCode:"name", dataType: "String"},
            {headerName:"单位",headerWidth:160,dataCode:"unit", dataType: "String"},
            {headerName:"单位基价",headerWidth:160, dataCode:"basePrice", dataType: "Number", precision: 2},
            {headerName:"定额消耗",headerWidth:160, dataCode:"consumeAmt", dataType: "Number", precision: 3},
            {headerName:"类型",headerWidth:160,dataCode:"gljDistType", dataType: "String"}
        ],
        view:{
            comboBox:[],
            lockColumns:[1,2,3,5,6]
        }
    },
    buildSheet: function(container) {
        var me = this;
        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.EditEnded, me.onCellEditEnd);
        me.workBook.getSheet(0).bind(GC.Spread.Sheets.Events.RangeChanged, me.onRangeChanged);
    },
    onRangeChanged: function(sender, args) {
        if (args.action == GC.Spread.Sheets.RangeChangedAction.clear) {
            var me = rationGLJOprObj, updateArr = [], removeArr = [];
            if (args.col == 0) {
                if (me.cache["_GLJ_" + me.currentRationItem.ID]) {
                    var cacheArr = me.cache["_GLJ_" + me.currentRationItem.ID];
                    for (var i = args.rowCount - 1; i >= 0; i--) {
                        if (args.row + i < cacheArr.length) {
                            cacheArr.splice(args.row + i, 1);
                        }
                    }
                    me.updateRationItem();
                    sheetCommonObj.cleanSheet(me.workBook.getSheet(0), me.setting, -1);
                    me.showGljItems(me.currentRationItem.ID);
                }
            }

        }
    },
    onClipboardPasting: function(sender, args) {
        var me = rationGLJOprObj;
        if (args.cellRange.colCount != 1 || args.cellRange.col != 0 || !(me.currentRationItem)) {
            args.cancel = true;
        }
    },
    onClipboardPasted: function(e, info) {
        var me = rationGLJOprObj, repId = storageUtil.getSessionCache("RationGrp","repositoryID");
        if (repId) {
            if (info.cellRange.col == 0) {
                var tmpCodes = sheetCommonObj.analyzePasteData({header:[{dataCode: "code"}] }, info);
                var codes = [];
                for (var i = 0; i < tmpCodes.length; i++) {
                    codes.push(tmpCodes[i].code);
                }
                me.addGljItems(codes, repId);
            } else {
                //修改用量
            }
        }
    },
    onCellEditEnd: function(sender, args){
        var me = rationGLJOprObj;
        if (args.col != 0) {
            var cacheArr = me.cache["_GLJ_" + me.currentRationItem.ID];
            if (args.row < cacheArr.length) {
                var editGlj = cacheArr[args.row];
                if (editGlj["consumeAmt"] != args.editingText) {
                    editGlj["consumeAmt"] = args.editingText;
                    me.updateRationItem();
                }
            }
        } else {
            //重新更新工料机
            if (args.editingText == null || args.editingText.trim() == "") {
                //delete
                if (me.cache["_GLJ_" + me.currentRationItem.ID]) {
                    var cacheArr = me.cache["_GLJ_" + me.currentRationItem.ID];
                    if (args.row < cacheArr.length) {
                        cacheArr.splice(args.row, 1);
                        me.updateRationItem();
                        sheetCommonObj.cleanSheet(me.workBook.getSheet(0), me.setting, -1);
                        me.showGljItems(me.currentRationItem.ID);
                    }
                }
            } else {
                var repId = storageUtil.getSessionCache("RationGrp","repositoryID");
                if (repId) {
                    var codes = [];
                    codes.push(args.editingText.trim());
                    me.addGljItems(codes, repId);
                }
            }
        }
    },

    addGljItems: function(codes, repId) {
        var me = this;
        $.ajax({
            type:"POST",
            url:"api/getGljItemsByCodes",
            data:{"gljCodes": JSON.stringify(codes), repId: repId},
            dataType:"json",
            cache:false,
            timeout:5000,
            success:function(result){
                sheetCommonObj.cleanSheet(me.workBook.getSheet(0), me.setting, -1);
                if (result) {
                    var rstArr = [], dummyR = {gljId: 0, consumeAmt:0}, newAddArr = [];
                    for (var i = 0; i < result.data.length; i++) {
                        dummyR.gljId = result.data[i].ID;
                        rstArr.push(me.createRationGljDisplayItem(dummyR, result.data[i]));
                    }
                    if (me.cache["_GLJ_" + me.currentRationItem.ID]) {
                        var cacheArr = me.cache["_GLJ_" + me.currentRationItem.ID];
                        for (var i = 0; i < rstArr.length; i++) {
                            var hasDup = false;
                            for (var j = 0; j < cacheArr.length; j++) {
                                if (cacheArr[j].gljId == rstArr[i].gljId) {
                                    hasDup = true;
                                    break;
                                }
                            }
                            if (!hasDup) {
                                newAddArr.push(rstArr[i]);
                            }
                        }
                        cacheArr.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.cache["_GLJ_" + me.currentRationItem.ID] = cacheArr.concat(newAddArr);
                    }
                    me.showGljItems(me.currentRationItem.ID);
                    if (newAddArr.length > 0) {
                        me.updateRationItem();
                    }
                }
                sheetCommonObj.lockCells(me.workBook.getSheet(0), me.setting);
            },
            error:function(err){
                alert(err);
            }
        })
    },

    updateRationItem: function() {
        var me = this, updateArr = [];
        if (me.currentRationItem) {
            me.currentRationItem.rationGljList = me.buildRationItemGlj();
            updateArr.push(me.currentRationItem);
            rationOprObj.mixUpdateRequest(updateArr, [], []);
        }
    },

    buildRationItemGlj: function(){
        var me = this, rst = [];
        if (me.currentRationItem && me.cache["_GLJ_" + me.currentRationItem.ID]) {
            var cacheArr = me.cache["_GLJ_" + me.currentRationItem.ID];
            for (var i = 0; i < cacheArr.length; i++) {
                rst.push({gljId: cacheArr[i].gljId, consumeAmt: cacheArr[i].consumeAmt, proportion: 0});
            }
        }
        return rst;
    },

    createRationGljDisplayItem: function(rItem, repGlj) {
        var rst = {};
        rst.gljId = rItem.gljId;
        rst.consumeAmt = rItem.consumeAmt;
        rst.code = repGlj.code;
        rst.name = repGlj.name;
        rst.specs = repGlj.specs;
        rst.unit = repGlj.unit;
        rst.basePrice = repGlj.basePrice;
        rst.gljDistType = repGlj.gljDistType;
        return rst;
    },
    getGljItems: function(rationItem) {
        var me = this, rationID = rationItem.ID, rationGljList = rationItem.rationGljList;
        me.currentRationItem = rationItem;
        if (me.cache["_GLJ_" + rationID]) {
            me.showGljItems(rationID);
            sheetCommonObj.lockCells(me.workBook.getSheet(0), me.setting);
        } else {
            var gljIds = [];
            for (var i = 0; i < rationGljList.length; i++) {
                gljIds.push(rationGljList[i].gljId);
            }
            $.ajax({
                type:"POST",
                url:"api/getGljItemsByIds",
                data:{"gljIds": JSON.stringify(gljIds)},
                dataType:"json",
                cache:false,
                timeout:5000,
                success:function(result){
                    sheetCommonObj.cleanSheet(me.workBook.getSheet(0), me.setting, -1);
                    if (result) {
                        var cacheArr = [];
                        for (var i = 0; i < result.data.length; i++) {
                            for (var j = 0; j < rationGljList.length; j++) {
                                if (rationGljList[j].gljId == result.data[i].ID) {
                                    cacheArr.push(me.createRationGljDisplayItem(rationGljList[j], result.data[i]));
                                    break;
                                }
                            }
                        }
                        me.cache["_GLJ_" + rationID] = cacheArr;
                        me.showGljItems(rationID);
                    }
                    sheetCommonObj.lockCells(me.workBook.getSheet(0), me.setting);
                },
                error:function(err){
                    alert(err);
                }
            })
        }
    },
    showGljItems: function(rationID) {
        var me = this;
        if (me.cache["_GLJ_" + rationID]) {
            sheetCommonObj.showData(me.workBook.getSheet(0), me.setting, me.cache["_GLJ_" + rationID]);
        }
    }
}