/**
 * Created by vian on 2017/4/12.
 */
var dbController = {
    insert: function(controller){
        if(controller.tree.items.length === 0){
            controller.tree.maxNodeID(0);
            controller.insert();
            controller.tree.selected.jobs = new Array();
            controller.tree.selected.items = new Array();
            billsAjax.createBills(billsLibId, controller.tree.selected.getID(), -1 , -1);
        }
        else {
            var node = controller.tree.selected;
            if(node){
                var updateId = node.getID(), createpid = node.getParentID(), createnid = node.getNextSiblingID();
                controller.insert();
                controller.tree.selected.jobs = new Array();
                controller.tree.selected.items = new Array();
                billsAjax.createBills(billsLibId, node.getNextSiblingID(), createpid, createnid, function(){
                    billsAjax.updatePNId(billsLibId, [{ID: updateId, NextSiblingID: node.getNextSiblingID()}]);
                    rechargeController.createRecharge(controller.tree.selected);
                });
            }
            else {
                var updateNode = controller.tree.roots[controller.tree.roots.length - 1];
                var updateId = updateNode.getID();
                controller.insert();
                controller.tree.selected.jobs = new Array();
                controller.tree.selected.items = new Array();
                billsAjax.createBills(billsLibId, updateNode.getNextSiblingID(), -1, -1, function(){
                    billsAjax.updatePNId(billsLibId, [{ID: updateId, NextSiblingID: updateNode.getNextSiblingID()}]);
                    rechargeController.createRecharge(controller.tree.selected);
                });
            }
        }
    },

    delete: function(controller, totalJobs, totalItems){
        var node = controller.tree.selected;
        var deleteIds = [];
        var getDeleteIds = function(node){
            if(node){
                deleteIds.push(node.getID());
                var length = node.children.length;
                if(length > 0){
                    for(var i=0; i<length; i++){
                        getDeleteIds(node.children[i]);
                    }
                }
            }
        };
        getDeleteIds(node);
        billsAjax.deleteBills(billsLibId, deleteIds, function(){
            if(node.preSibling){
                billsAjax.updatePNId(billsLibId, [{ID: node.preSibling.getID(), NextSiblingID: node.getNextSiblingID()}]);
            }
        });
        //controller.delete();
        tools.delteSheets(controller, totalJobs, totalItems, jobsSpread.getActiveSheet(), itemsSpread.getActiveSheet());
    },

    upLevel: function(controller){
        var node = controller.tree.selected;
        var ids = [];
        var updateData = [];
        var getNextSibling = function(node){
            if(node.nextSibling){
                ids.push(node.getNextSiblingID());
                getNextSibling(node.nextSibling);
            }
        }
        //node
        if(node){
            if(node.parent){
                var updateA = {
                    ID: node.getID(),
                    ParentID: node.parent.getParentID(),
                    NextSiblingID: node.parent.getNextSiblingID()
                };
                updateData.push(updateA);
                //parent
                var updateB = {
                    ID: node.getParentID(),
                    NextSiblingID: node.getID()
                }
                updateData.push(updateB);
                if(node.nextSibling){
                    getNextSibling(node);
                    var updateC = {
                        ID: ids,
                        ParentID: node.getID()
                    }
                    updateData.push(updateC);
                }
                if(node.preSibling){
                    var updateD = {
                        ID: node.preSibling.getID(),
                        NextSibingID: -1
                    }
                    updateData.push(updateD);
                }
                billsAjax.updatePNId(billsLibId, updateData);
                controller.upLevel();
                rechargeController.createRecharge(controller.tree.selected);
            }
        }
    },

    downLevel: function(controller){
        var node = controller.tree.selected;
        var updateData = [];
        if(node){
            if(node.preSibling){
                var updateA = {
                    ID: node.preSibling.getID(),
                    NextSiblingID: node.getNextSiblingID()
                };
                var updateB = {
                    ID: node.getID(),
                    ParentID: node.preSibling.getID(),
                    NextSiblingID: -1
                };
                updateData.push(updateA);
                updateData.push(updateB);
                if(node.preSibling.children.length > 0){
                    var updateC  = {
                        ID: node.preSibling.children[node.preSibling.children.length -1].getID(),
                        NextSiblingID: node.getID()
                    }
                    updateData.push(updateC);
                }
                billsAjax.updatePNId(billsLibId, updateData);
                controller.downLevel();
                rechargeController.createRecharge(controller.tree.selected);
            }
        }
    },

    upMove: function(controller){
        var node = controller.tree.selected;
        var updateData = [];
        if(node){
            if(node.preSibling){
                var updateA = {
                    ID: node.preSibling.getID(),
                    NextSiblingID: node.getNextSiblingID()
                };
                var updateB = {
                    ID: node.getID(),
                    NextSiblingID: node.preSibling.getID()
                };
                updateData.push(updateA);
                updateData.push(updateB);
                if(node.preSibling.preSibling){
                    var updateC = {
                        ID: node.preSibling.preSibling.getID(),
                        NextSiblingID: node.getID()
                    }
                    updateData.push(updateC);
                }
                billsAjax.updatePNId(billsLibId, updateData);
                controller.upMove();
            }
        }
    },

    downMove: function(controller){
        var node = controller.tree.selected;
        var updateData = [];
        if(node){
            if(node.nextSibling){
                var updateA = {
                    ID: node.getNextSiblingID(),
                    NextSiblingID: node.getID()
                };
                var updateB = {
                    ID: node.getID(),
                    NextSiblingID: node.nextSibling.getNextSiblingID()
                };
                updateData.push(updateA);
                updateData.push(updateB);
                if(node.preSibling){
                    var updateC = {
                        ID: node.preSibling.getID(),
                        NextSiblingID: node.getNextSiblingID()
                    };
                    updateData.push(updateC);
                }
                billsAjax.updatePNId(billsLibId, updateData);
                controller.downMove();
            }
        }
    },

    editData: function(controller){
        controller.sheet.bind(GC.Spread.Sheets.Events.EditEnded, function(sender, args){
            var node = controller.tree.selected, updateId, field;
            if(node){
                updateId = node.getID();
                billsLibSetting.cols.forEach(function(col, idx){
                    if(args.col === idx){
                        field = col.data.field;
                        node.data[field] = args.editingText;
                    }
                });
                billsAjax.updateBills(billsLibId, updateId, field, args.editingText);
            }
            else {
                args.sheet.getCell(args.row, args.col, GC.Spread.Sheets.SheetArea.viewport).value('');
            }
        });
    }

};

var createObj = {
    newJob: function(data){
        var Job = function(data){
            this.data = data;
            //count = 0则没有被引用了
            this.count = 0;
        };
        return new Job(data);
    },
    newJobs: function(){
        var TotalJobs = function(){
            this.jobs = {};
            this.jobsArr = [];
            this.prefix = '_id';
        };

        TotalJobs.prototype.findJob = function(id){
            return this.jobs[this.prefix + id] ? this.jobs[this.prefix + id] : null;
        }


        TotalJobs.prototype.loadJobs = function (nodes, datas){
            var me = this;
            datas.forEach(function(jobData){
                var job = createObj.newJob(jobData);
                me.jobs[me.prefix + jobData.id] = job;
                me.jobsArr.push(job);
            });
            if(nodes){
                nodes.forEach(function(node){
                    node.jobs = new Array();
                    node.data.jobs.forEach(function(jobId){
                        if(me.jobs[me.prefix + jobId]){
                            node.jobs.push(me.jobs[me.prefix + jobId]);
                            me.jobs[me.prefix + jobId].count ++;
                        }
                        else {
                            node.data.jobs.splice(node.data.jobs.indexOf(jobId), 1);
                        }
                    });
                });
            }
        };

        TotalJobs.prototype.getUpdateIds = function(nodes, repeatId){
            var ids = [];
            nodes.forEach(function(node){
                node.jobs.forEach(function(job){
                    if(job.data.id === repeatId){
                        ids.push(node.getID());
                    }
                });
            });
            return ids;
        };

        return new TotalJobs();
    },

    newItem: function(data){
        var Item = function(data){
            this.data = data;
            this.count = 0;
        };
        return new Item(data);
    },

    newItems: function(){
        var TotalItems = function(){
            this.items = {};
            this.itemsArr = [];
            this.prefix = '_id';
        };

        TotalItems.prototype.findItem = function(id){
            return this.items[this.prefix + id] ? this.items[this.prefix + id] : null;
        }

        TotalItems.prototype.loadItems = function (nodes, datas){
            var me = this;
            datas.forEach(function(itemData){
                var item = createObj.newItem(itemData);
                me.items[me.prefix + itemData.id] = item;
                me.itemsArr.push(item);
            });
            if(nodes){
                nodes.forEach(function(node){
                    node.items = new Array();
                    node.data.items.forEach(function(itemID){
                        if(me.items[me.prefix + itemID]){
                            node.items.push(me.items[me.prefix + itemID]);
                            me.items[me.prefix + itemID].count ++;
                        }
                        else {
                            node.data.items.splice(node.data.items.indexOf(itemID), 1);
                        }
                    });
                });
            }
        };

        TotalItems.prototype.getUpdateIds = function(nodes, repeatId){
            var ids = [];
            nodes.forEach(function(node){
                node.items.forEach(function(item){
                    if(item.data.id === repeatId){
                        ids.push(node.getID());
                    }
                });
            });
            return ids;
        };
        return new TotalItems();
    }
};

var tools = {
    isExist: function (totalArr, field, newData, orgData){
        var isExist = false;
        if(totalArr.length > 0){
            totalArr.forEach(function(item){
                if(item.data[field] == newData && newData !== orgData){
                    isExist = true;
                }
            });
        }
        return isExist;
    },
    isRepeat: function(arr, field, newData, ref){
        var isRepeat = false;
        if(arr){
            arr.forEach(function(item){
                if(ref === 'reference' && item.data[field] == newData){
                    isRepeat = true;
                }
                else if(ref === 'document' && item[field] === newData){
                    isRepeat = true;
                }
            });
        }
        return isRepeat;
    },

    addAttr: function(attr){
        if(!attr){
            attr = new Array();
        }
    },

    reSetCell: function(sheet, rowIdx, colIdx, value, id){
        if(value && colIdx){
            sheet.getCell(rowIdx, colIdx, GC.Spread.Sheets.SheetArea.viewport).value(value);
        }
        sheet.setTag(rowIdx, 0, id);
        sheet.setTag(rowIdx, 1, id);
    },

    getIndex: function(arr, id){
        var index;
        arr.forEach(function(item){
            if(item.data.id === id){
                index = arr.indexOf(item);
            }
        });
        return index;
    },

    delteSheets: function(controller, totalJobs, totalItems, jobsSheet, itemsSheet){
        var delJobs = controller.tree.selected.jobs;
        var delItems = controller.tree.selected.items;
        var delJobsIds = [];
        var delItemsIds = [];
        if(delJobs.length > 0){
            delJobs.forEach(function(job){
                job.count --;
                if(job.count <=0){
                    totalJobs.jobsArr.splice(totalJobs.jobsArr.indexOf(job), 1);
                    delJobsIds.push(job.data.id)
                }
            });
            jobsAjax.deleteJobContent(delJobsIds);
            tools.clearData(jobsSheet);
            tools.reshowData(jobsSheet, controller.tree.selected.jobs, jobsSetting, true);
        }
        if(delItems.length > 0){
            delItems.forEach(function(item){
                item.count --;
                if(item.count <=0){
                    totalItems.itemsArr.splice(totalItems.itemsArr.indexOf(item), 1);
                    delItemsIds.push(item.data.id)
                }
            });
            itemsAjax.deleteItemCharacter(delItemsIds);
            tools.clearData(itemsSheet);
            tools.reshowData(itemsSheet, controller.tree.selected.items, itemsSetting, true);
        }
        controller.delete();

    },

    deleteELes: function (arr, delIds, callback){
        var ids = [];
        delIds.forEach(function(delId){
            arr.forEach(function(ele){
                if(ele.data.id === delId){
                    arr.splice(arr.indexOf(ele), 1);
                    ele.count--;
                    if(ele.count <= 0){
                        ids.push(ele.data.id);
                    }
                }
            });
        });
        if(callback){
            callback(ids);
        }

    },

    resort: function(arr, attr, isValue){
       //var arr = node.jobs;
       function compare(attr){
           return function (a, b){
               var valA, valB;
               if(isValue){
                   valA = a[attr];
                   valB = a[attr];
               }
               else {
                   valA = a.data[attr];
                   valB = b.data[attr];
               }
               return valA - valB;
           }
       }
       arr.sort(compare(attr));
    },
    reshowData: function(sheet, arr, setting, isResort){
        tools.clearData(sheet);
        if(isResort){
            tools.resort(arr, 'code', false);
        }
        if(arr.length > 0){
            var length = arr.length;
            for(var i=0; i<length; i++){
                setting.cols.forEach(function(col, colIdx){
                    sheet.setTag(i, colIdx, arr[i].data.id);
                    if(arr[i].data[col.data.field]){
                        sheet.getCell(i, colIdx).value(arr[i].data[col.data.field]);
                    }
                    else {
                        sheet.getCell(i, colIdx).value('');
                    }
                });
            }
        }
    },

    reshowValue: function(sheet, arr, setting, isResort){
        tools.clearData(sheet);
        if(isResort){
            tools.resort(arr, 'code', true);
        }
        if(arr.length > 0){
            var length = arr.length;
            for(var i=0; i<length; i++){
                setting.cols.forEach(function(col, colIdx){
                    sheet.setTag(i, colIdx, arr[i].code);
                    if(arr[i][col.data.field]){
                        sheet.getCell(i, colIdx).value(arr[i][col.data.field]);
                    }
                    else {
                        sheet.getCell(i, colIdx).value('');
                    }
                });
            }
        }
    },

    clearData: function(sheet){
        sheet.clear(0, 0, sheet.getRowCount(), sheet.getColumnCount(), GC.Spread.Sheets.SheetArea.viewport,GC.Spread.Sheets.StorageType.data);
        sheet.clear(0, 0, sheet.getRowCount(), sheet.getColumnCount(), GC.Spread.Sheets.SheetArea.viewport,GC.Spread.Sheets.StorageType.tag);
    },

    getRoot: function(node){
        return node.parent ? tools.getRoot(node.parent) : node;
    },

    getBillsIds: function(callback){
        billsAjax.getBills(billsLibId, function(datas){
            var ids = [];
            datas.forEach(function(data){
                ids.push(data.ID);
            });
            if(callback){
                callback(ids);
            }
        });
    },

    delIds: function(sheet){
        var ids = [];
        var sels = sheet.getSelections();
        sels.forEach(function(sel){
            var orgRow = sel.row, rowCount = sel.rowCount, colCount = sel.colCount;
            var orgCol = sel.col === -1 ? 0 : sel.col;
            var maxRow = orgRow + rowCount - 1;
            for(var i=orgRow; i<= maxRow; i++){
                if(sheet.getTag(i, orgCol)){
                    ids.push(sheet.getTag(i, orgCol));
                }
            }
        });
        return ids;
    },

    redirect: function(billsLibId, newHref){
        mainAjax.getABillsLib(billsLibId, function(result){
            if(result.length === 0){
                window.location.href = newHref;
            }
        });
    }

}

var jobsController = {
    editData: function(controller, sheet, totalJobs, setting){
        sheet.bind(GC.Spread.Sheets.Events.EnterCell, function(sender, args){
            orgJobData = sheet.getCell(args.row, args.col).value();
        });
        sheet.bind(GC.Spread.Sheets.Events.EditEnded, function(sender, args) {
            var field, newData = args.editingText, id = sheet.getTag(args.row, args.col);
            setting.cols.forEach(function (col, idx) {
                if (args.col === idx) {
                    field = col.data.field;
                }
            });
            if (controller.tree.selected) {
                var isExist = tools.isExist(totalJobs.jobsArr, field, newData, orgJobData);
                var isRepeat = tools.isRepeat(controller.tree.selected.jobs, field ,newData, 'reference');
                //create
                if(!id && newData && !isRepeat){
                        if(isExist){
                            jobsController.createExist(sheet, controller, totalJobs, field, newData, args, setting);
                        }
                        else {
                            jobsController.createNew(sheet, controller, totalJobs, field, newData, args, setting);
                        }
                }
                //update
                else if(id && newData !== orgJobData && !isRepeat){
                    jobsController.update(sheet, controller, totalJobs, field, newData, id, isExist, args, setting);
                }
                //处理重复
                if(isRepeat){
                    if(id && newData){
                        sheet.getCell(args.row, args.col, GC.Spread.Sheets.SheetArea.viewport).value(orgJobData);
                    }
                    else {
                        sheet.getCell(args.row, args.col, GC.Spread.Sheets.SheetArea.viewport).value('');
                    }
                }
            }
            else {
                sheet.getCell(args.row, args.col).value('');
            }
        });
    },

    createNew: function(sheet, controller, totalJobs, field, newData, args, setting){
        if(field === 'content'){
            maxJobsNumber++;
            jobsAjax.createJobContent(billsLibId, field, newData, maxJobsNumber, function(id){
                var newJobData, newJob;
                newJobData = {id: id, content: newData, code: maxJobsNumber};
                newJob = createObj.newJob(newJobData);
                newJob.count = 1;
                totalJobs.jobs[totalJobs.prefix + id] = newJob;
                totalJobs.jobsArr.push(newJob);
                billsAjax.updateBills(billsLibId, controller.tree.selected.getID(), 'jobs', id);
                controller.tree.selected.jobs.push(newJob);
                tools.reshowData(sheet, controller.tree.selected.jobs, setting, true);
            });
        }
        else {
            sheet.getCell(args.row, args.col).value('');
        }
    },

    createExist: function(sheet, controller, totalJobs, field, newData, args, setting){
        totalJobs.jobsArr.forEach(function(job){
            if(field === 'content'&& newData === job.data.content){
                billsAjax.updateBills(billsLibId, controller.tree.selected.getID(), 'jobs', job.data.id);
                job.count++;
                controller.tree.selected.jobs.push(job);
                tools.reshowData(sheet, controller.tree.selected.jobs, setting, true);
            }
            else if(field == 'code' && newData == job.data.code){
                billsAjax.updateBills(billsLibId, controller.tree.selected.getID(), 'jobs', job.data.id);
                job.count++;
                controller.tree.selected.jobs.push(job);
                tools.reshowData(sheet, controller.tree.selected.jobs, setting, true);
            }
        });
    },

    update: function(sheet, controller, totalJobs, field, newData, id, isExist, args, setting){
        if(isExist){
            totalJobs.jobsArr.forEach(function(job){
                if(field == 'code' && job.data[field] == newData){
                    var index = tools.getIndex(controller.tree.selected.jobs, id);
                    job.count++;
                    controller.tree.selected.jobs.splice(index, 1);
                    controller.tree.selected.jobs.splice(index, 0, job);
                    billsAjax.updateBillsArr(billsLibId, controller.tree.selected.getID(), id, job.data.id, 'update', 'jobs');
                    tools.reshowData(sheet, controller.tree.selected.jobs, setting, true);
                }
                if(field === 'content' && job.data[field] === newData){
                    var index = tools.getIndex(controller.tree.selected.jobs, id);
                    job.count++;
                    controller.tree.selected.jobs.splice(index, 1);
                    controller.tree.selected.jobs.splice(index, 0, job);
                    billsAjax.updateBillsArr(billsLibId, controller.tree.selected.getID(), id, job.data.id, 'update', 'jobs');
                    tools.reshowData(sheet, controller.tree.selected.jobs, setting, true);
                }
            });
        }
        else{
            if(field === 'content'){
                maxJobsNumber++;
                jobsAjax.createJobContent(billsLibId, field, newData, maxJobsNumber, function(newId){
                    var newJobData, newJob;
                    newJobData = {id: newId, content: newData, code: maxJobsNumber};
                    newJob = createObj.newJob(newJobData);
                    newJob.count = 1;
                    totalJobs.jobs[totalJobs.prefix + newId] = newJob;
                    totalJobs.jobsArr.push(newJob);
                    billsAjax.updateBillsArr(billsLibId, controller.tree.selected.getID(), id, newId, 'update', 'jobs');
                    var index = tools.getIndex(controller.tree.selected.jobs, id);
                    controller.tree.selected.jobs.splice(index, 1);
                    controller.tree.selected.jobs.splice(index, 0, newJob);
                    tools.reshowData(sheet, controller.tree.selected.jobs, setting, true);
                });
            }
            else {
                //todo: 提示窗口
                if(typeof newData === 'number'){
                    sheet.getCell(args.row, args.col).value(orgJobData);
                }
                else {
                  //编号只能是数字
                }
            }
        }
    },

};

var itemsController = {
    editData: function(controller, sheet, totalItems, setting){
        sheet.bind(GC.Spread.Sheets.Events.EnterCell, function(sender, args){
            orgItemData = sheet.getCell(args.row, args.col).value();
        });
        sheet.bind(GC.Spread.Sheets.Events.EditEnded, function(sender, args) {
            var field, newData = args.editingText, id = sheet.getTag(args.row, args.col);
            setting.cols.forEach(function (col, idx) {
                if (args.col === idx) {
                    field = col.data.field;
                }
            });
            if (controller.tree.selected) {
                var isExist = tools.isExist(totalItems.itemsArr, field, newData, orgItemData);
                var isRepeat = tools.isRepeat(controller.tree.selected.items, field ,newData, 'reference');
                //create
                if(!id && newData && !isRepeat){
                    if(isExist){
                        itemsController.createExist(sheet, controller, totalItems, field, newData, args, setting);
                    }
                    else {
                        itemsController.createNew(sheet, controller, totalItems, field, newData, args, setting);
                    }
                }
                //update
                else if(id && newData !== orgItemData && !isRepeat){
                    itemsController.update(sheet, controller, totalItems, field, newData, id, isExist, args, setting);
                }
                //处理重复
                if(isRepeat){
                    //todo:redirect focus
                    if(id && newData){
                        sheet.getCell(args.row, args.col, GC.Spread.Sheets.SheetArea.viewport).value(orgItemData);
                    }
                    else {
                        sheet.getCell(args.row, args.col, GC.Spread.Sheets.SheetArea.viewport).value('');
                    }
                }
            }
            else {
                sheet.getCell(args.row, args.col).value('');
            }
        });
    },

    createNew: function(sheet, controller, totalItems, field, newData, args, setting){
        if(field === 'content'){
            maxItemsNumber++;
            itemsAjax.createItemCharacter(billsLibId, field, newData, maxItemsNumber, function(id){
                var newItemData, newItem;
                newItemData = {id: id, content: newData, code: maxItemsNumber};
                newItem = createObj.newItem(newItemData);
                newItem.count = 1;
                totalItems.items[totalItems.prefix + id] = newItem;
                totalItems.itemsArr.push(newItem);
                billsAjax.updateBills(billsLibId, controller.tree.selected.getID(), 'items', id);
                controller.tree.selected.items.push(newItem);
                tools.reshowData(sheet, controller.tree.selected.items, setting, true);
            });
        }
        else {
            if(typeof newData === 'number'){
                sheet.getCell(args.row, args.col).value('');
            }
            else {
                //编号只能为数字
            }
        }
    },

    createExist: function(sheet, controller, totalItems, field, newData, args, setting){
        totalItems.itemsArr.forEach(function(item){
            //todo:整合代码
            if(field === 'content'&& newData === item.data.content){
                //isExist = true;
                billsAjax.updateBills(billsLibId, controller.tree.selected.getID(), 'items', item.data.id);
                //整合
                //tools.addAttr(controller.tree.selected.items);
                item.count++;
                controller.tree.selected.items.push(item);
                tools.reshowData(sheet, controller.tree.selected.items, setting, true);
            }
            else if(field == 'code' && newData == item.data.code){
                //isExist = true;
                billsAjax.updateBills(billsLibId, controller.tree.selected.getID(), 'items', item.data.id);
               // tools.addAttr(controller.tree.selected.items);
                item.count++;
                controller.tree.selected.items.push(item);
                tools.reshowData(sheet, controller.tree.selected.items, setting, true);
            }
        });
    },

    update: function(sheet, controller, totalItems, field, newData, id, isExist, args, setting){
        if(isExist){
            totalItems.itemsArr.forEach(function(item){
                if(field == 'code' && item.data[field] == newData){
                    var index = tools.getIndex(controller.tree.selected.items, id);
                    item.count++;
                    controller.tree.selected.items.splice(index, 1);
                    controller.tree.selected.items.splice(index, 0, item);
                    //var newItemData = {id: item.data.id, code: newData, content: item.data.content}
                    billsAjax.updateBillsArr(billsLibId, controller.tree.selected.getID(), id, item.data.id, 'update', 'items');
                    tools.reshowData(sheet, controller.tree.selected.items, setting, true);
                }
                if(field === 'content' && item.data[field] === newData){
                    var index = tools.getIndex(controller.tree.selected.items, id);
                    item.count++;
                    controller.tree.selected.items.splice(index, 1);
                    controller.tree.selected.items.splice(index, 0, item);
                    //var newItemData = {id: item.data.id, code: item.data.code, content: newData}
                    billsAjax.updateBillsArr(billsLibId, controller.tree.selected.getID(), id, item.data.id, 'update', 'items');
                    tools.reshowData(sheet, controller.tree.selected.items, setting, true);
                }
            });
        }
        else{
            if(field === 'content'){
                maxItemsNumber++;
                itemsAjax.createItemCharacter(billsLibId, field, newData, maxItemsNumber, function(newId){
                    var newItemData, newItem;
                    newItemData = {id: newId, content: newData, code: maxItemsNumber};
                    newItem = createObj.newItem(newItemData);
                    newItem.count = 1;
                    totalItems.items[totalItems.prefix + newId] = newItem;
                    totalItems.itemsArr.push(newItem);
                    billsAjax.updateBillsArr(billsLibId, controller.tree.selected.getID(), id, newId, 'update', 'items');
                 //   tools.addAttr(controller.tree.selected.items);
                    var index = tools.getIndex(controller.tree.selected.items, id);
                    controller.tree.selected.items.splice(index, 1);
                    controller.tree.selected.items.splice(index, 0, newItem);
                    tools.reshowData(sheet, controller.tree.selected.items, setting, true);
                });
            }
            else {
                if(typeof newData === 'number'){
                    sheet.getCell(args.row, args.col).value(orgItemData);
                }
                else {
                    //编号只能为数字
                }
            }
        }
    },

};

var valueController = {
    editData: function(totalItems, sheet, setting){
        sheet.bind(GC.Spread.Sheets.Events.EnterCell, function(sender, args){
            orgValue = sheet.getValue(args.row, args.col);
        });
        sheet.bind(GC.Spread.Sheets.Events.EditEnded, function(sender, args){
            var newValue = sheet.getValue(args.row, args.col), tagId = sheet.getTag(args.row, args.col), field, isRepeat;
            setting.cols.forEach(function(col, colIdx){
                if(args.col === colIdx){
                    field = col.data.field;
                }
            });
            if(selectedId){
                isRepeat = tools.isRepeat(valueController.getValues(totalItems, selectedId), field, newValue, 'document');
                if(!tagId && !isRepeat && newValue){//create
                        valueController.createValue(sheet, totalItems, selectedId, field, newValue);
                }
                else if(tagId && !isRepeat && newValue !== orgValue){//update
                        valueController.updateValue(totalItems, tagId, newValue, field);
                }
                if(isRepeat){
                    if(tagId && newValue){
                        sheet.getCell(args.row, args.col, GC.Spread.Sheets.SheetArea.viewport).value(orgValue);
                    }
                    else {
                        sheet.getCell(args.row, args.col, GC.Spread.Sheets.SheetArea.viewport).value('');
                    }
                }
            }
        });
    },

    createValue: function(sheet, totalItems, id, field, newValue){
        var newData;
        if(field === 'value'){
            var newCode = valueController.getCode(totalItems, id);
            newData = {code: newCode, value: newValue};
            tools.reSetCell(sheet, sheet.getActiveRowIndex(), 0, newCode, newCode);
        }
        else {
            if(typeof newValue === 'number'){
                newData = {code: newValue, value: ''};
                tools.reSetCell(sheet, sheet.getActiveRowIndex(), null, null, newValue);
            }
            else {
                //编号只能为数字!
            }
        }
        totalItems.findItem(id).data.itemValue.push(newData);
        itemsAjax.updateValue(id, newData, null, 'create');
    },

    updateValue: function(totalItems, tagId, newData, field){
        var updateData = {code: tagId, newData: newData, field: field};
        var itemVals = totalItems.findItem(selectedId).data.itemValue;
        if(field === 'value'){
            var updateEle = {code: tagId, value: newData};
            if(itemVals){
                var index;
                itemVals.forEach(function(val){
                    if(val.code === tagId){
                        index = itemVals.indexOf(val);
                        itemVals.splice(index, 1);
                    }
                });
                itemVals.splice(index, 0, updateEle);
            }
            itemsAjax.updateValue(selectedId, updateData, null, 'update');
        }
        else {
            if(typeof newData === 'number'){
                if(itemVals){
                    var updateEle;
                    var index;
                    itemVals.forEach(function(val){
                        if(val.code === tagId){
                            updateEle = {code: newData, value: val.value};
                            index = itemVals.indexOf(val);
                            itemVals.splice(index, 1);
                        }
                    });
                    itemVals.splice(index, 0, updateEle);
                }
                itemsAjax.updateValue(selectedId, updateData, null, 'update');
            }
            else {
                //编号只能为数字!
            }
        }
    },

    getValues: function(totalItems, id){
        return totalItems.findItem(id).data.itemValue;
    },

    getTopItem: function(totalItems){
        tools.resort(totalItems.itemsArr, 'code', false);
        return totalItems.itemsArr.length > 0 ? totalItems.itemsArr[0] : null
    },

    getCode: function(totalItems, id){
        var valArr = totalItems.findItem(id).data.itemValue;
        tools.resort(valArr, 'code', true);
        return valArr.length > 0 ? valArr[valArr.length - 1].code + 1 : 1;
    },

    isRepeat: function(arr, newValue){
        var isRepeat = false;
        arr.forEach(function(itemValue){
            if(itemValue.value === newValue){
                isRepeat = true;
            }
        });
        return isRepeat;
    }
};

var totalJobsController = {
    eiditData: function(totalJobs, sheet, setting){
        sheet.bind(GC.Spread.Sheets.Events.EnterCell, function(sender, args){
            orgJobData = sheet.getCell(args.row, args.col).value();
        });
        sheet.bind(GC.Spread.Sheets.Events.EditEnded, function(sender, args){
            var newData = sheet.getValue(args.row, args.col), tagId = sheet.getTag(args.row, args.col), field, isRepeat;
            setting.cols.forEach(function(col, colIdx){
                if(args.col === colIdx){
                    field = col.data.field;
                }
            });
            isRepeat = tools.isRepeat(totalJobs.jobsArr, field, newData, 'reference');
            if(!tagId && !isRepeat && newData){//create
                totalJobsController.createJob(sheet, totalJobs, field, newData, args);
            }
            else if(tagId && !isRepeat && newData !== orgJobData){//update
                    totalJobsController.updateJob(totalJobs, tagId, field, newData);
            }
            if(isRepeat){
                if(tagId && newData){
                    sheet.getCell(args.row, args.col, GC.Spread.Sheets.SheetArea.viewport).value(orgJobData);
                }
                else {
                    sheet.getCell(args.row, args.col, GC.Spread.Sheets.SheetArea.viewport).value('');
                }
            }
        });
    },

    createJob: function(sheet, totalJobs, field, newData, args){
        if(field === 'content'){
            maxJobsNumber++;
            jobsAjax.createJobContent(billsLibId, field, newData, maxJobsNumber, function(id){
                var newJobData, newJob;
                newJobData = {id: id, content: newData, code: maxJobsNumber};
                newJob = createObj.newJob(newJobData);
                totalJobs.jobsArr.push(newJob);
                tools.reSetCell(sheet, args.row, 0, maxJobsNumber, id);
            });
        }
        else {
            if(typeof newData === 'number'){
                maxJobsNumber = maxJobsNumber >= newData ? maxJobsNumber : newData;
                jobsAjax.createJobContent(billsLibId, field, '', newData, function(id){
                    var newJobData, newJob;
                    newJobData = {id: id, content: '', code: newData};
                    newJob = createObj.newJob(newJobData);
                    totalJobs.jobsArr.push(newJob);
                    tools.reSetCell(sheet, args.row, 0, null, id);
                });
            }
            else {
                //编号只能为数字!
            }
        }
    },

    updateJob: function(totalJobs, id, field, newData){
        if(field === 'code' && typeof newData !== 'number'){
            //编号只能为数字
        }
        else {
            totalJobs.jobsArr.forEach(function(job){
                if(job.data[field] === newData){
                    job.data[field] = newData;
                }
            });
            jobsAjax.updateJobContent(id, field, newData);
        }
    }
};

var totalItemsController = {
    eiditData: function(totalItems, sheet, setting){
        sheet.bind(GC.Spread.Sheets.Events.EnterCell, function(sender, args){
            orgItemData = sheet.getCell(args.row, args.col).value();
        });
        sheet.bind(GC.Spread.Sheets.Events.EditEnded, function(sender, args){
            var newData = sheet.getValue(args.row, args.col), tagId = sheet.getTag(args.row, args.col), field, isRepeat;
            setting.cols.forEach(function(col, colIdx){
                if(args.col === colIdx){
                    field = col.data.field;
                    console.log('colIdx' + colIdx);
                }
            });
            isRepeat = tools.isRepeat(totalItems.itemsArr, field, newData, 'reference');
            if(!tagId && !isRepeat && newData){//create
                totalItemsController.createItem(sheet, totalItems, field, newData, args);
            }
            else if(tagId && !isRepeat && newData !== orgItemData){//update
                    totalItemsController.updateItem(totalItems, tagId, field, newData);
            }
            if(isRepeat){
                if(tagId && newData){
                    sheet.getCell(args.row, args.col, GC.Spread.Sheets.SheetArea.viewport).value(orgItemData);
                }
                else {
                    sheet.getCell(args.row, args.col, GC.Spread.Sheets.SheetArea.viewport).value('');
                }
            }
        });
    },

    createItem: function(sheet, totalItems, field, newData, args){
        if(field === 'content'){
            maxItemsNumber++;
            itemsAjax.createItemCharacter(billsLibId, field, newData, maxItemsNumber, function(id){
                var newItemData, newItem;
                newItemData = {id: id, content: newData, code: maxItemsNumber};
                newItem = createObj.newItem(newItemData);
                totalItems.itemsArr.push(newItem);
                tools.reSetCell(sheet, args.row, 0, maxItemsNumber, id);
            });
        }
        else {
            if(typeof newData === 'number'){
                maxItemsNumber = maxItemsNumber >= newData ? maxItemsNumber : newData;
                itemsAjax.createItemCharacter(billsLibId, field, '', newData, function(id){
                    var newItemData, newItem;
                    newItemData = {id: id, content: '', code: newData};
                    newItem = createObj.newItem(newItemData);
                    totalItems.itemsArr.push(newItem);
                    tools.reSetCell(sheet, args.row, 0, null, id);
                });
            }
            else {
                //编号只能为数字
            }
        }
    },

    updateItem: function(totalItems, id, field, newData){
        if(field === 'code' && typeof newData !== 'number'){
            //编号只能为数字
        }
        else {
            totalItems.itemsArr.forEach(function(item){
                if(item.data[field] === newData){
                    item.data[field] = newData;
                }
            });
            itemsAjax.updateItemCharacter(id, field, newData);
        }
    }
};

var rechargeController = {
    updateRechar: function(selectedNode, newData){
        if(selectedNode){
            var  updateIds = [];
            var getupdateIds = function(node){
                updateIds.push(node.getID());
                node.data.recharge = newData;
                if(node.children.length > 0){
                    node.children.forEach(function(node){
                        getupdateIds(node);
                    });
                }
            }
            getupdateIds(tools.getRoot(selectedNode));
            billsAjax.updateRecharge(billsLibId, updateIds, newData);
        }
        else {
            $('exampleTextarea').val('');
        }
    },
    createRecharge: function(node){
        if(node){
            var tempId = [];
            tempId.push(node.getID());
            var rootNode = tools.getRoot(node);
            if(rootNode.data.recharge && rootNode !== node){
                billsAjax.updateRecharge(billsLibId, tempId, rootNode.data.recharge);
                node.data.recharge = rootNode.data.recharge;
                $('#exampleTextarea').val(node.data.recharge);
            }
            else {
                node.data.recharge = '';
                $('#exampleTextarea').val('');
            }
        }
        else {
            $('exampleTextarea').val('');
        }
    }
};




