/**
 * Created by Zhong on 2018/1/25.
 */
let rationInstObj = {
    IDMapping: null, //ID - name
    feeItem: null, //name - ID
    sheet: null,
    curRation: null,
    cache: [],
    setting: {
        header:[
            {headerName:"费用项",headerWidth:120,dataCode:"feeItem", dataType: "String", hAlign: 'left'},
            {headerName:"分册章节",headerWidth:400,dataCode:"section", dataType: "String", hAlign: 'left'}
        ],
        view:{
            comboBox:[],
            lockColumns:[]
        },
    },
    buildSheet: function(sheet) {
        let me = this;
        me.sheet = sheet;
        me.sheet.options.clipBoardOptions = GC.Spread.Sheets.ClipboardPasteOptions.values;
        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.EnterCell, me.onEnterCell);
        me.sheet.bind(GC.Spread.Sheets.Events.EditStarting, me.onEditStarting);
        me.sheet.bind(GC.Spread.Sheets.Events.EditEnded, me.onEditEnded);
        //右键
        //  me.onContextmenuOpr();
    },
    renderFunc: function (sheet, func) {
        sheet.suspendPaint();
        sheet.suspendEvent();
        if(func){
            func();
        }
        sheet.resumePaint();
        sheet.resumeEvent();
    },
    isDef: function (v) {
        return v !== undefined && v !== null;
    },
    getInstallation: function (installationData) {
        //建立name - ID 映射, ID - name 映射
        this.feeItem = {};
        this.IDMapping = {feeItem: {}, section: {}};
        for(let feeItem of installationData){
            this.feeItem[feeItem.feeItem] = {ID: feeItem.ID, section: {}};
            this.IDMapping['feeItem'][feeItem.ID] = feeItem.feeItem;
            for(let section of feeItem.section){
                this.feeItem[feeItem.feeItem]['section'][section.name] = section.ID;
                this.IDMapping['section'][section.ID] = section.name;
            }
        }
    },
    getFeeItemCombo: function () {
        let feeItemArr = [];
        for(let name in this.feeItem){
            feeItemArr.push(name);
        }
        let combo = sheetCommonObj.getDynamicCombo();
        combo.items(feeItemArr).itemHeight(10).editable(false);
        return combo;
    },
    getSectionCombo: function (feeItem) {
        let sectionObjs = this.feeItem[feeItem]['section'];
        let sectionArr = [];
        for(let name in sectionObjs){
            sectionArr.push(name);
        }
        let combo = sheetCommonObj.getDynamicCombo();
        combo.items(sectionArr).itemHeight(10).editable(false);
        return combo;
    },
    getInstItems: function (ration, callback) {
        let me = this, rst = [];
        me.curRation = ration;
        me.cache = ration.rationInstList;
        for(let inst of me.cache){
            let data = Object.create(null);
            let feeItem = me.IDMapping['feeItem'][inst.feeItemId];
            let section = me.IDMapping['section'][inst.sectionId];
            data.feeItem = me.isDef(feeItem) ? feeItem : '';
            data.section = me.isDef(section) ? section : '';
            rst.push(data);
        }
        me.showInstItems(rst);
        if(callback){
            callback();
        }
    },
    showInstItems: function (data) {
        let me = this;
        sheetCommonObj.showData(this.sheet, this.setting, data);
        //init combo
        this.renderFunc(this.sheet, function () {
            let feeIemCombo = me.getFeeItemCombo();
            let rowCount = me.sheet.getRowCount();
            for(let i = 0, len = rowCount.length; i < len; i++){
                me.getRange(i, -1, 1, -1).cellType(null);
            }
            me.sheet.getRange(-1, 0, -1, 1).cellType(feeIemCombo);
            for(let i = 0, len = data.length; i < len; i++){
                let sectionCombo = me.getSectionCombo(data[i].feeItem);
                me.sheet.getCell(i, 1).cellType(sectionCombo);
            }
        });
    },
    onEnterCell: function (sender, args) {
        args.sheet.repaint();
    },
    onEditStarting: function (sender, args) {
        let me = rationInstObj;
        if(!me.isDef(me.curRation)){
            args.cancel = true;
            return;
        }
        if(!me.isDef(me.cache[args.row]) && args.col === 1){
            args.cancel = true;
            return;
        }
    },
    onEditEnded: function (sender, args) {
        let me = rationInstObj;
        let v = me.isDef(args.editingText) ? args.editingText.toString().trim() : '';
        let field = me.setting.header[args.col]['dataCode'];
        let inst = me.cache[args.row];
        let toUpdate = false;
        //update
        if(me.isDef(inst)){
            if(field === 'feeItem'){
                let feeItemId = me.isDef(me.feeItem[v]) ? me.feeItem[v]['ID'] : null;
                if(feeItemId){
                    inst.feeItemId = feeItemId;
                    toUpdate = true;
                }
                else {
                    me.sheet.setValue(args.row, args.col, me.IDMapping['feeItem'][inst.feeItemId]);
                    return;
                }
            }
            else{
                let sectionId = me.isDef(me.feeItem[me.IDMapping['feeItem'][inst.feeItemId]]) ? me.feeItem[me.IDMapping['feeItem'][inst.feeItemId]]['section'][v] : null;
                inst.sectionId = sectionId;
                toUpdate = true;
            }
        }
        //insert
        else{
            let feeItemId = me.isDef(me.feeItem[v]) ? me.feeItem[v]['ID'] : null;
            if(feeItemId){
                let obj = {feeItemId: feeItemId, sectionId: null};
                me.cache.push(obj);
                toUpdate = true;
            }
        }
        if(toUpdate){
            me.updateRation(me.curRation, function () {
                me.getInstItems(me.curRation);
            });
        }
    },
    validUpdatePaste: function (rowData, data) {
        if(this.isDef(data.feeItem) && this.isDef(data.section) && data.feeItem !== '' && data.section !== ''){
            if(!this.isDef(this.feeItem[data.feeItem])){
                return false;
            }
            if(!this.isDef(this.feeItem[data.feeItem]['section'][data.section])){
                return false;
            }
        }
        else if(this.isDef(data.feeItem) && data.feeItem !== ''){
            if(!this.isDef(this.feeItem[data.feeItem])){
                return false;
            }
        }
        else if(this.isDef(data.section) && data.section !== ''){
            if(!this.isDef(this.feeItem[this.IDMapping['feeItem'][rowData.feeItemId]]['section'][data.section])){
                return false;
            }
        }
        return true;
    },
    validInsertPaste: function (data) {
        if(!this.isDef(data.feeItem) || data.feeItem == ''){
            return false;
        }
        if(!this.isDef(this.feeItem[data.feeItem])){
            return false;
        }
        if(this.isDef(data.section) && data.section !== '' && !this.isDef(this.feeItem[data.feeItem]['section'][data.section])){
            return false;
        }
        return true;
    },
    toSaveData: function (data, rowData = null) {
        let obj = {feeItemId: null, sectionId: null};
        if(this.isDef(data.feeItem) && data.feeItem !== ''){
            obj.feeItemId = this.isDef(this.feeItem[data.feeItem]) ? this.feeItem[data.feeItem]['ID'] : null;
        }
        else if(this.isDef(rowData)){
            obj.feeItemId = rowData.feeItemId;
        }
        if(this.isDef(data.section) && data.section !== ''){
            obj.sectionId = this.isDef(this.feeItem[this.IDMapping['feeItem'][obj.feeItemId]]['section'][data.section]) ?
                this.feeItem[this.IDMapping['feeItem'][obj.feeItemId]]['section'][data.section]: null;
        }
        return obj;
    },
    bindRationInstDel: function () {
        let me = this;
        let workBook = me.sheet.getParent();
        workBook.commandManager().register('rationInstDel', function () {
            let toUpdate = false;
            let sels = me.sheet.getSelections();
            for(let i = 0, len = sels.length; i < len; i++){
                let sel = sels[i];
                //delete
                if(sel.colCount === me.setting.header.length){
                    for(let j = 0, jLen = sel.rowCount; j < jLen; j++){
                        let row = sel.row + j;
                        let inst = me.cache[row];
                        //有数据，删除数据
                        if(me.isDef(inst)){
                            if(!toUpdate){
                                toUpdate = true;
                            }
                        }
                    }
                    //front delete
                    me.cache.splice(sel.row, sel.rowCount);
                }
            }
            if(toUpdate && me.curRation){
                me.updateRation(me.curRation, function () {
                    me.getInstItems(me.curRation);
                });
            }
        });
        workBook.commandManager().setShortcutKey(null, GC.Spread.Commands.Key.del, false, false, false, false);
        workBook.commandManager().setShortcutKey('rationInstDel', GC.Spread.Commands.Key.del, false, false, false, false);
    },
    onClipboardPasting: function (sender, info) {
        let me = rationInstObj;
        if(!me.isDef(me.curRation)){
            info.cancel = true;
        }
    },
    onClipboardPasted: function (sender, info) {
        let me = rationInstObj;
        let items = sheetCommonObj.analyzePasteData(me.setting, info);
        let toUpdate = false;
        for(let i = 0, len = items.length; i < len; i++){
            let row = info.cellRange.row + i;
            //update
            let inst = me.cache[row];
            if(me.isDef(inst)){
                if(me.validUpdatePaste(inst, items[i])){
                    let updateObj = me.toSaveData(items[i], inst);
                    for(let attr in updateObj){
                        inst[attr] = updateObj[attr];
                    }
                    toUpdate = true;
                }
            }
            //insert
            else{
                if(me.validInsertPaste(items[i])){
                    me.cache.push(me.toSaveData(items[i]));
                    toUpdate = true;
                }
            }
        }
        if(toUpdate){
            me.updateRation(me.curRation, function () {
                me.getInstItems(me.curRation);
            });
        }
        else {
            me.getInstItems(me.curRation);
        }
    },
    updateRation: function (ration,callback) {
        rationOprObj.mixUpdateRequest([ration], [], [], function () {
            if(callback){
                callback();
            }
        });
    }
};