/**
 * Created by CSL on 2017-06-08.
 */
 //modified by zhong on 2017-09-25
var rationCoeOprObj = {
    sheet: null,
    libID: null,
    curRation: null,
    tempDelArr: [],
    cache: {},
    setting: {
        header:[
            {headerName:"编号",headerWidth:50,dataCode:"serialNo", dataType: "Number", hAlign: 'center'},
            {headerName:"名称",headerWidth:280,dataCode:"name", dataType: "String", hAlign: 'left'},
            {headerName:"内容",headerWidth:150,dataCode:"content", dataType: "String", hAlign: 'left'}
        ],
        view:{
            comboBox:[],
            lockColumns:[1,2]
        }
    },

    buildSheet: function(sheet) {
        var me = this;
        me.sheet = sheet;
        //me.libID = storageUtil.getSessionCache("RationGrp","repositoryID"); // 不可靠，有时取不到
        me.libID = pageOprObj.rationLibId; // 不可靠，有时取不到
        if (me.libID == undefined){me.libID = getQueryString('repository')};
        sheetCommonObj.initSheet(me.sheet, me.setting, 30);
        me.sheet.bind(GC.Spread.Sheets.Events.ClipboardPasting, me.onClipboardPasting);
        me.sheet.bind(GC.Spread.Sheets.Events.ClipboardPasted, me.onClipboardPasted);
        me.sheet.bind(GC.Spread.Sheets.Events.EditStarting, me.onEditStarting);
        me.sheet.bind(GC.Spread.Sheets.Events.EditEnded, me.onEditEnded);
    },

    isDef: function (v) {
        return v !== undefined && v !== null;
    },


    upMove: function (thisObj, preObj, cell) {
        let me = this;
        let tempNo = thisObj.no;
        thisObj.no = preObj.no;
        preObj.no = tempNo;
        //ajax
        me.updateCurRation(function () {
            me.showCoeItems(me.curRation.ID);
            me.sheet.setActiveCell(cell.row, cell.col);
        });
    },

    downMove: function (thisObj, nextObj, cell) {
        let me = this;
        let tempNo = thisObj.no;
        thisObj.no = nextObj.no;
        nextObj.no = tempNo;
        me.updateCurRation(function () {
            me.showCoeItems(me.curRation.ID);
            me.sheet.setActiveCell(cell.row, cell.col);
        });
    },

    //本节所有使用此条件
    useAll: function (coe) {

    },

    sortByNo: function (cache) {
        cache.sort(function (a, b) {
            let rst = 0;
            if(a.no > b.no){
                rst = 1;
            }
            else if(a.no < b.no){
                rst = -1;
            }
            return rst;
        });
    },

    onClipboardPasting: function(sender, args) {
        var me = rationCoeOprObj;
        let rationSection = rationOprObj.getCache();
        let rationRow = rationOprObj.workBook.getActiveSheet().getSelections()[0].row;
        me.curRation = rationRow < rationSection.length ? rationSection[rationRow] : null;
        if (args.cellRange.colCount != 1 || args.cellRange.col != 0 || !(me.curRation)) {
            args.cancel = true;
        }
    },

    onClipboardPasted: function(e, info) {
        var me = rationCoeOprObj;
        if (me.libID) {
            // 修改第一列（编号）
            if (info.cellRange.col == 0) {
                me.tempDelArr = [];
                var coeNos = [];
                var items = sheetCommonObj.analyzePasteData({header:[{dataCode: "serialNo"}] }, info);
                let curCache = typeof me.cache["_Coe_" + me.curRation.ID] !== 'undefined' ? me.cache["_Coe_" + me.curRation.ID] : [];
                let isRefresh = false;
                for(let i = 0, len = items.length; i < len; i++){
                    if(!isNaN(items[i].serialNo)){
                        let row = i + info.cellRange.row;
                        //update
                        if(row < curCache.length){
                            let isExist = false;
                            for(let j = 0, jLen = curCache.length; j < jLen; j++){
                                if(items[i].serialNo === curCache[j].serialNo && j !== row){
                                    isExist = true;
                                    break;
                                }
                            }
                            if(!isExist){
                                me.tempDelArr.push({org: curCache[row], newNo: items[i].serialNo});
                                coeNos.push(items[i].serialNo);
                            }
                            else{
                                isRefresh = true;
                            }
                        }
                        else{
                            coeNos.push(items[i].serialNo);
                        }
                    }
                }
                //delete in front
                if(me.tempDelArr.length > 0){
                   for(let i = 0, len = me.tempDelArr.length; i < len; i++){
                       for(let j = 0; j < curCache.length; j++){
                           if(me.tempDelArr[i].org.serialNo === curCache[j].serialNo){
                               curCache.splice(j, 1);
                               break;
                           }
                       }
                   }
                }
                me.addCoeItems(coeNos);
                if(isRefresh){
                    me.showCoeItems(me.curRation.ID);
                }
            } else {
                //修改其它列。
            }
        }
    },
    onEditStarting: function (sender, args) {
        let me = rationCoeOprObj;
        let rationSection = rationOprObj.getCache();
        let rationRow = rationOprObj.workBook.getActiveSheet().getSelections()[0].row;
        me.curRation = rationRow < rationSection.length ? rationSection[rationRow] : null;
        if(!me.curRation || args.col !== 0){
            args.cancel = true;
        }

    },
    onEditEnded: function(sender, args){
        var me = rationCoeOprObj;
        if (args.col == 0 && args.editingText && args.editingText.toString().trim().length > 0 && !isNaN(args.editingText)) {   // 编号列
            let curCahe = typeof me.cache["_Coe_" + me.curRation.ID] !== 'undefined' ? me.cache["_Coe_" + me.curRation.ID] : [];
            me.tempDelArr = [];
            //update
            if(args.row < curCahe.length && args.editingText != curCahe[args.row].serialNo){
                let isExist = false;
                for(let i = 0, len = curCahe.length; i < len; i++){
                    if(args.editingText == curCahe[i].serialNo){
                        isExist = true;
                        break;
                    }
                }
                if(!isExist){
                    me.tempDelArr.push({org: curCahe[args.row], newNo: args.editingText});
                    curCahe.splice(args.row, 1);
                    me.addCoeItems([args.editingText]);
                }
                else{
                    me.showCoeItems(me.curRation.ID);
                }
            }
            //insert
            else{
                me.addCoeItems([args.editingText]);
            }
        }
        else{
            sheetCommonObj.cleanData(me.sheet, me.setting, -1);
            me.showCoeItems(me.curRation.ID);
        }
    },

    bindRationCoeDel: function () {
        if (locked) {
            return;
        }
        let me = rationCoeOprObj;
        let workBook = me.sheet.getParent();
        workBook.commandManager().register('rationCoeDel', function () {
            let sels = me.sheet.getSelections(), isUpdate = false;
            let curCahe = me.cache["_Coe_" + me.curRation.ID];
            for(let i = 0, len = sels.length; i < len; i ++ ){
                if(sels[i].colCount === me.setting.header.length){
                    if(sels[i].row < curCahe.length){
                        isUpdate = true;
                        curCahe.splice(sels[i].row, sels[i].rowCount);
                    }
                }
            }
            if(isUpdate){
                me.updateCurRation(function () {
                    me.sheet.getParent().focus(true);
                });
                sheetCommonObj.cleanData(me.sheet, me.setting, -1);
                me.showCoeItems(me.curRation.ID);
            }
        });
        workBook.commandManager().setShortcutKey(null, GC.Spread.Commands.Key.del, false, false, false, false);
        workBook.commandManager().setShortcutKey('rationCoeDel', GC.Spread.Commands.Key.del, false, false, false, false);
    },
    getRecoveryArr: function (tempDelArr, newArr) {//获得更新的coe不存在，恢复删除的被更新数据
        let rst = [];
        for(let i = 0, len = tempDelArr.length; i < len; i++){
            let isExist = false;
            for(let j = 0, jLen = newArr.length; j < jLen; j++){
                if(tempDelArr[i].newNo == newArr[j].serialNo){
                    isExist = true;
                    break;
                }
            }
            if(!isExist){
                rst.push(tempDelArr[i].org);
            }
        }
        return rst;
    },
    addCoeItems: function(coeNos) {
        var me = this;
        sheetCommonObj.cleanData(me.sheet, me.setting, -1);

        var curCache = me.cache["_Coe_" + me.curRation.ID];
        var temp = [];
        if (curCache) {
            for (var i = 0; i < coeNos.length; i++) {
                var isExist = false;
                for (let obj of curCache) {
                    if (obj.serialNo == coeNos[i]) {
                        isExist = true;
                        break;
                    };
                };
                if (!isExist) {
                    temp.push(coeNos[i]);
                };
            };
        }else{
            for (let obj of coeNos){temp.push(obj)};
        };

        if(temp.length == 0){
            me.showCoeItems(me.curRation.ID);
            //sheetCommonObj.lockCells(me.sheet, me.setting);
        }else{
            $.ajax({
                type:"POST",
                url:"api/getCoeItemsByNos",
                data: {"data": JSON.stringify({"libID": me.libID, "coeNos": temp})},
                dataType:"json",
                cache:false,
                timeout:5000,
                success:function(result){
                    if (result) {
                        var rstArr = [];
                        let newNo = curCache && curCache.length > 0 ? curCache[curCache.length - 1].no + 1 : 1;
                        for (let obj of result.data){
                            obj.no = newNo++;
                            rstArr.push(obj)
                        }
                        if (curCache) {
                            curCache = curCache.concat(rstArr);
                        }else{
                            curCache = rstArr;
                        }
                        let recoveryArr = me.getRecoveryArr(me.tempDelArr, result.data);
                        if(recoveryArr.length > 0){
                            curCache = curCache.concat(recoveryArr);
                        }
                        me.cache["_Coe_" + me.curRation.ID] = curCache;
                        me.updateCurRation(function () {
                            me.sheet.getParent().focus(true);
                        });
                        me.showCoeItems(me.curRation.ID);
                    };
                    //sheetCommonObj.lockCells(me.sheet, me.setting);
                },
                error:function(err){
                    alert(err);
                }
            });
        };
    },

    getCoeItems: function(ration, callback) {
        var me = this;
        me.curRation = ration;

        /*if (ration == undefined || ration.rationCoeList == undefined ||
            ration.rationCoeList.length == 0){return;};*/

        var coeList = ration.rationCoeList;
        let coeIDs = [];
        for(let i = 0, len = coeList.length; i < len; i++){
            coeIDs.push(coeList[i].ID);
        }
        var curCache = me.cache["_Coe_" + ration.ID];
        if (curCache) {
            me.showCoeItems(ration.ID);
            //sheetCommonObj.lockCells(me.sheet, me.setting);
        } else if(!curCache && typeof coeList !== 'undefined' && coeList.length > 0) {
            var data = {"libID": me.libID, "coeIDs": coeIDs};
            $.ajax({
                type:"POST",
                url:"api/getCoeItemsByIDs",
                data: {"data": JSON.stringify(data)},
                dataType:"json",
                cache:false,
                timeout:5000,
                success:function(result){
                    sheetCommonObj.cleanData(me.sheet, me.setting, -1);
                    if (result.data) {
                        var tempResult = [];
                        for (let obj of result.data) {
                            for(let i = 0, len = coeList.length; i < len; i++){
                                if(obj.ID === coeList[i].ID){
                                    obj.no = coeList[i].no;
                                    tempResult.push(obj);
                                    break;
                                }
                            }
                        };


                        me.cache["_Coe_" + ration.ID] = tempResult;

                        me.showCoeItems(ration.ID);
                    }
                    //sheetCommonObj.lockCells(me.sheet, me.setting);
                    if(callback) callback();
                },
                error:function(err){
                    alert(err);
                }
            });
        };
    },

    showCoeItems: function(rationID) {
        var me = this;
        var curCache = me.cache["_Coe_" + rationID];
        if (curCache) {
            curCache.sort(function(a, b) {
                var rst = 0;
                if (a.no > b.no) rst = 1
                else if (a.no < b.no) rst = -1;
                return rst;
            });
            sheetsOprObj.showData(me.sheet, me.setting, curCache);
        }
    },

    updateCurRation: function(callback) {
        var me = this, updateArr = [];
        if (me.curRation) {
            var rst = [];
            var curCache = me.cache["_Coe_" + me.curRation.ID];
            if (curCache) {
                for (let obj of curCache) {
                    rst.push({ID: obj.ID, no: obj.no});
                }
                me.curRation.rationCoeList = rst;
                updateArr.push(me.curRation);
                rationOprObj.mixUpdateRequest(updateArr, [], [], function () {
                    if(callback) callback();
                });
            }
        }
    },

    //更新本节所有定额
    updateSectionRation: function (rations, coe, callback) {
        let me = this;
        let updateArr = [];
        for(let i = 0, len = rations.length; i < len; i++){
            if(rations[i].ID !== me.curRation.ID){
                let rationCoeList = rations[i].rationCoeList;
                let isExist = false;
                let newNo = 1;
                for(let j = 0, jLen = rationCoeList.length; j < jLen; j++){
                    if(rationCoeList[j].no >= newNo){
                        newNo = rationCoeList[j].no + 1;
                    }
                    if(rationCoeList[j].ID === coe.ID){
                        isExist = true;
                    }
                }
                if(!isExist){
                    rationCoeList.push({ID: coe.ID, no: newNo});
                    updateArr.push(rations[i]);
                }
            }
        }
        if(updateArr.length > 0){
            rationOprObj.mixUpdateRequest(updateArr, [], [], function () {
                if(callback) callback(updateArr);
            });
        }
    }
}


