'use strict';

/**
 *
 *
 * @author Zhong
 * @date 2018/6/1
 * @version
 */

const billsGuidance = (function () {
    //自执行函数全局变量定义
    const libID = getQueryString('libID');
    const bills = {
        dom: $('#billsSpread'),
        workBook: null,
        cache: [],
        tree: null,
        controller: null,
        treeSetting: {
            treeCol: 0,
            emptyRows: 0,
            headRows: 1,
            headRowHeight: [40],
            defaultRowHeight: 21,
            cols: [{
                width: 200,
                readOnly: true,
                head: {
                    titleNames: ["项目编码"],
                    spanCols: [1],
                    spanRows: [1],
                    vAlign: [1],
                    hAlign: [1],
                    font: ["Arial"]
                },
                data: {
                    field: "code",
                    vAlign: 1,
                    hAlign: 0,
                    font: "Arial"
                }
            }, {
                width: 200,
                readOnly: true,
                head: {
                    titleNames: ["项目名称"],
                    spanCols: [1],
                    spanRows: [1],
                    vAlign: [1],
                    hAlign: [1],
                    font: ["Arial"]
                },
                data: {
                    field: "name",
                    vAlign: 1,
                    hAlign: 0,
                    font: "Arial"
                }
            }]
        },
        headers: [
            {name: '项目编码', dataCode: 'code', width: 200, vAlign: 'center', hAlign: 'left', formatter: '@'},
            {name: '项目名称', dataCode: 'name', width: 200, vAlign: 'center', hAlign: 'left', formatter: '@'}
        ],
        events: {
            SelectionChanged: function (sender, info) {
                billsInitSel(info.newSelections[0].row);
            }
        }
    };
    //项目指引类型
    const itemType = {
        job: 0,
        ration: 1
    };
    const updateType = {
        create: 'create',
        update: 'update',
        del: 'delete'
    };
    const guideItem = {
        dom: $('#guideItemSpread'),
        workBook: null,
        tree: null,
        controller: null,
        treeSetting: {
            treeCol: 0,
            emptyRows: 0,
            headRows: 1,
            headRowHeight: [40],
            defaultRowHeight: 21,
            cols: [{
                width: 400,
                readOnly: false,
                head: {
                    titleNames: ["项目指引"],
                    spanCols: [1],
                    spanRows: [1],
                    vAlign: [1],
                    hAlign: [1],
                    font: ["Arial"]
                },
                data: {
                    field: "name",
                    vAlign: 1,
                    hAlign: 0,
                    font: "Arial"
                }
            }]
        },
        headers: [
            {name: '项目指引', dataCode: 'name', width: 400, vAlign: 'center', hAlign: 'left', formatter: '@'},
        ],
        events: {
            SelectionChanged: function (sender, info) {
                guideItemInitSel(info.newSelections[0].row)
            },
            EditEnded: function (sender, args) {
                edit(args.sheet, [{row: args.row, col: args.col}]);
            },
            RangeChanged: function (sender, args) {
                edit(args.sheet, args.changedCells);
            }
        }
    };
    const ration = {
        dom: $('#rationSpread'),
        workBook: null,
        datas: [],
        cache: [],
        headers: [
            {name: '选择', dataCode: 'select', width: 50, vAlign: 'center', hAlign: 'center'},
            {name: '编码', dataCode: 'code', width: 110, vAlign: 'center', hAlign: 'left', formatter: '@'},
            {name: '名称', dataCode: 'name', width: 250, vAlign: 'center', hAlign: 'left', formatter: '@'},
            {name: '单位', dataCode: 'unit', width: 100, vAlign: 'center', hAlign: 'left', formatter: '@'}
        ],
        events: {
            ButtonClicked: function (sender, args) {
                if(args.sheet.isEditing()){
                    args.sheet.endEdit(true);
                }
            },
            CellDoubleClick: function (sender, args) {
                if(ration.headers[args.col].dataCode === 'name'){
                    let insertDatas = getInsertRations([args.row]);
                    if(insertDatas.length > 0){
                        insert(insertDatas);
                    }
                }
            }
        }
    };
    const options = {
        workBook: {
            tabStripVisible:  false,
            allowContextMenu: false,
            allowCopyPasteExcelStyle : false,
            allowExtendPasteRange: false,
            allowUserDragDrop : false,
            allowUserDragFill: false,
            scrollbarMaxAlign : true
        },
        sheet: {
            protectionOptions: {allowResizeRows: true, allowResizeColumns: true},
            clipBoardOptions: GC.Spread.Sheets.ClipboardPasteOptions.values
        }
    };

    //渲染时方法，停止渲染
    //@param {Object}sheet {Function}func @return {void}
    function renderSheetFunc(sheet, func){
        sheet.suspendEvent();
        sheet.suspendPaint();
        if(func){
            func();
        }
        sheet.resumeEvent();
        sheet.resumePaint();
    }
    //设置表选项
    //@param {Object}workBook {Object}opts @return {void}
    function setOptions (workBook, opts) {
        for(let opt in opts.workBook){
            workBook.options[opt] = opts.workBook[opt];
        }
        for(let opt in opts.sheet){
            workBook.getActiveSheet().options[opt] = opts.sheet[opt];
        }
    }
    //建表头
    //@param {Object}sheet {Array}headers @return {void}
    function buildHeader(sheet, headers) {
        let fuc = function () {
            sheet.setColumnCount(headers.length);
            sheet.setRowHeight(0, 40, GC.Spread.Sheets.SheetArea.colHeader);
            for(let i = 0, len = headers.length; i < len; i++){
                sheet.setValue(0, i, headers[i].name, GC.Spread.Sheets.SheetArea.colHeader);
                sheet.setColumnWidth(i, headers[i].width, GC.Spread.Sheets.SheetArea.colHeader);
                if(headers[i].formatter){
                    sheet.setFormatter(-1, i, headers[i].formatter);
                }
                sheet.getRange(-1, i, -1, 1).hAlign(GC.Spread.Sheets.HorizontalAlign[headers[i]['hAlign']]);
                sheet.getRange(-1, i, -1, 1).vAlign(GC.Spread.Sheets.VerticalAlign[headers[i]['vAlign']]);
            }
        };
        renderSheetFunc(sheet, fuc);
    }
    //表监听事件
    //@param {Object}workBook @return {void}
    function bindEvent(workBook, events) {
        if(Object.keys(events).length === 0){
            return;
        }
        const Events = GC.Spread.Sheets.Events;
        let sheet = workBook.getActiveSheet();
        for(let event in events){
            workBook.bind(Events[event], events[event]);
        }
    }
    //建表
    //@param {Object}module @return {void}
    function buildSheet(module) {
        if(!module.workBook){
            module.workBook = new GC.Spread.Sheets.Workbook(module.dom[0], {sheetCount: 1});
            let sheet = module.workBook.getActiveSheet();
            if(module === bills){
                //默认初始可控制焦点在清单表中
                module.workBook.focus();
                sheet.options.isProtected = true;
            }
            else if(module === ration){
                sheet.options.isProtected = true;
                sheet.getRange(-1, 0, -1, 1).locked(false);
                sheet.getRange(-1, 1, -1, -1).locked(true);
            }
            else if(module === guideItem){
                sheetCommonObj.bindEscKey(module.workBook, [{sheet: sheet, editStarting: null, editEnded: module.events.EditEnded}]);
            }
            setOptions(module.workBook, options);
            buildHeader(module.workBook.getActiveSheet(), module.headers);
            bindEvent(module.workBook, module.events);
        }
    }
    //清空表数据
    //@param {Object}sheet {Array}headers {Number}rowCount @return {void}
    function cleanData(sheet, headers, rowCount){
        renderSheetFunc(sheet, function () {
            sheet.clear(-1, 0, -1, headers.length, GC.Spread.Sheets.SheetArea.viewport, GC.Spread.Sheets.StorageType.data);
            if (rowCount > 0) {
                sheet.setRowCount(rowCount);
            }
        });
    }
    //根据清单获取项目指引
    //@param {String}guidanceLibID {Number}billsID {Function}callback @return {void}
    function getItemsByBills(guidanceLibID, billsID, callback){
        CommonAjax.post('/billsGuidance/api/getItemsByBills', {guidanceLibID: guidanceLibID, billsID: billsID}, function (rstData) {
            if(callback){
                callback(rstData);
            }
        });
    }
    //清单表焦点控制
    //@param {Number}row @return {void}
    function billsInitSel(row){
        let guideSheet = guideItem.workBook.getActiveSheet();
        cleanData(guideSheet, guideItem.headers, -1);
        let node = bills.tree.items[row];
        if(!node){
            return;
        }
        bills.tree.selected = node;
        if(!node.guidance.tree){
            getItemsByBills(libID, node.data.ID, function (rstData) {
                initTree(node.guidance, guideSheet, guideItem.treeSetting, rstData);
                //项目指引初始焦点
                guideItemInitSel(guideSheet.getActiveRowIndex() ? guideSheet.getActiveRowIndex() : 0);
            });
        }
        else{
            node.guidance.controller.showTreeData();
            //项目指引初始焦点
            guideItemInitSel(guideSheet.getActiveRowIndex() ? guideSheet.getActiveRowIndex() : 0);
        }
    }
    //节点子项是否全是工作内容
    //@param {Object}node @return {Boolean}
    function allJobChildren(node){
        for(let c of node.children){
            if(c.data.type === itemType.ration){
                return false;
            }
        }
        return true;
    }
    //节点子项是否全是定额
    //@param {Object}node @return {Boolean}
    function allRationChildren(node){
        for(let c of node.children){
            if(c.data.type === itemType.job){
                return false;
            }
        }
        return true;
    }
    //刷新按钮有效性
    //@param {Object}node @return {void}
    function refreshBtn(node){
        //全部设为无效
        $('.tools-btn').children().addClass('disabled');
        $('#insertRation').addClass('disabled');
        //插入
        if(bills.tree.selected && bills.tree.selected.guidance.tree){
            $('#insert').removeClass('disabled');
            if(node && node.data.type === itemType.ration){
                $('#insert').addClass('disabled');
            }
        }
        //删除
        if(node){
            $('#del').removeClass('disabled');
        }
        if(node && node.data.type === itemType.job){
            //升级
            if(node.parent){
                $('#upLevel').removeClass('disabled');
                if(node.nextSibling && node.children.length > 0 && !allJobChildren(node)){
                    $('#upLevel').addClass('disabled');
                }
            }
            //降级
            if(node.preSibling){
                $('#downLevel').removeClass('disabled');
                if(node.preSibling.children.length > 0 && !allJobChildren(node.preSibling)){
                    $('#downLevel').addClass('disabled');
                }
            }
        }
        //上移
        if(node && node.preSibling){
            $('#upMove').removeClass('disabled')
        }
        //下移
        if(node && node.nextSibling){
            $('#downMove').removeClass('disabled');
        }
        //插入定额
        if(node && (node.children.length === 0 || allRationChildren(node))){
            $('#insertRation').removeClass('disabled');
        }
    }
    //项目指引表焦点控制
    //@param {Number}row @return {void}
    function guideItemInitSel(row){
        let billsNode = bills.tree.selected;
        let node = null;
        if(billsNode && billsNode.guidance.tree){
            node = billsNode.guidance.tree.items[row];
            if(node){
                billsNode.guidance.tree.selected = node;
            }
        }
        refreshBtn(node);
    }
    //初始化当前库名
    //@param {String} @return {void}
    function initLibName(libName) {
        $('#libName')[0].outerHTML = $('#libName')[0].outerHTML.replace("XXX清单指引", libName);
    }
    //初始化各工作表
    //@param {Array}modules @return {void}
    function initWorkBooks(modules){
        for(let module of modules){
            buildSheet(module);
        }
    }
    //输出表数据(定额表)
    //@param {Object}sheet {Array}headers {Array}datas @return {void}
    function showData(sheet, headers, datas){
        let fuc = function () {
            sheet.setRowCount(datas.length);
            //复选框
            let checkBoxType = new GC.Spread.Sheets.CellTypes.CheckBox();
            sheet.setCellType(-1, 0, checkBoxType);
            for(let col = 0, cLen = headers.length; col < cLen; col++){
                for(let row = 0, rLen = datas.length; row < rLen; row++){
                    sheet.setValue(row, col, datas[row][headers[col]['dataCode']]);
                }
            }
        };
        renderSheetFunc(sheet, fuc);
    }
    //初始化定额条目
    //@param {Number}rationLibId @return {void}
    function initRationItems(rationLibId){
        $.bootstrapLoading.start();
        CommonAjax.post('/rationRepository/api/getRationItemsByLib', {rationLibId: rationLibId}, function (rstData) {
            rstData.sort(function (a, b) {
                let rst = 0;
                if(a.code > b.code){
                    rst = 1;
                }
                else if(a.code < b.code){
                    rst = -1;
                }
                return rst;
            });
            ration.datas = rstData;
            ration.cache = rstData;
            showData(ration.workBook.getActiveSheet(), ration.headers, rstData);
            $.bootstrapLoading.end();
        });
    }
    //初始化定额库选择
    //@param {String}compilationId @return {void}
    function initRationLibs(compilationId){
        CommonAjax.post('/rationRepository/api/getRationLibsByCompilation', {compilationId: compilationId}, function (rstData) {
            $('#rationLibSel').empty();
            for(let rationLib of rstData){
                let opt = `<option value="${rationLib.ID}">${rationLib.dispName}</option>`;
                $('#rationLibSel').append(opt);
            }
            //初始选择
            initRationItems(parseInt($('#rationLibSel').select().val()));
            $('#rationLibSel').change(function () {
                let rationLibId = parseInt($(this).select().val());
                initRationItems(rationLibId);
            })
        });
    }
    //获取指引库信息及关联的清单
    //@param {Number}libID {Function}callback @return {Object}
    function getLibWithBills(libID, callback){
        CommonAjax.post('/billsGuidance/api/getLibWithBills', {libID: libID}, function (rstData) {
            initRationLibs(rstData.guidanceLib.compilationId);
            bills.cache = rstData.bills;
            initLibName(rstData.guidanceLib.name);
            initTree(bills, bills.workBook.getActiveSheet(), bills.treeSetting, bills.cache);
            //每一棵项目指引树挂在清单节点上
            for(let node of bills.tree.items){
                node.guidance = {tree: null, controller: null};
            }
            //默认初始节点
            billsInitSel(0);
            if(callback){
                callback(rstData);
            }
        }, function (msg) {
            window.location.href = '/billsGuidance/main';
        });
    }
    //初始化并输出树
    //@param {Object}module {Object}sheet {Object}treeSetting {Array}datas
    function initTree(module, sheet, treeSetting, datas){
        module.tree = idTree.createNew({id: 'ID', pid: 'ParentID', nid: 'NextSiblingID', rootId: -1, autoUpdate: true});
        module.controller = TREE_SHEET_CONTROLLER.createNew(module.tree, sheet, treeSetting);
        module.tree.loadDatas(datas);
        module.controller.showTreeData();
    }
    //更新项目指引
    //@param {Array}updateDatas {Function}callback @return {void}
    function updateGuideItems(updateDatas, callback){
        CommonAjax.post('/billsGuidance/api/updateItems', {updateDatas: updateDatas}, function (rstData) {
            if(callback){
                callback(rstData);
            }
        });
    }
    //项目指引编辑
    //@param {Object}sheet {Array}cells
    function edit(sheet, cells){
        let updateDatas = [];
        //同步节点数据
        let syncDatas = [];
        for(let cell of cells){
            let text = sheet.getValue(cell.row, cell.col);
            text = text ? text : '';
            let node = bills.tree.selected.guidance.tree.items[cell.row];
            if(node.data.name != text){
                syncDatas.push({node: node, text: text});
                updateDatas.push({updateType: updateType.update, findData: {ID: node.getID()}, updateData: {name: text}});
            }
        }
        if(updateDatas.length > 0){
            updateGuideItems(updateDatas, function () {
                for(let syncData of syncDatas){
                    syncData.node.data.name = syncData.text;
                }
            }, function () {
                //失败恢复
                renderSheetFunc(sheet, function () {
                    for(let syncData of syncDatas){
                        sheet.setValue(syncData.node.serialNo(), 0, syncData.node.data.name ? syncData.node.data.name : '');
                    }
                });
            });
        }
    }
    //项目指引插入，支持一次插入多条数据
    //@param {Array}datas {Function}callback @return {void}
    function insert(datas, callback = null){
        $.bootstrapLoading.start();
        let sheet = guideItem.workBook.getActiveSheet();
        let controller = bills.tree.selected.guidance.controller;
        let selected = bills.tree.selected.guidance.tree.selected;
        let updateDatas = [];
        //建立数组下标索引
        let newDataIndex = {};
        for(let i = 0; i < datas.length; i++){
            let newNodeData = {
                libID: libID, ID: uuid.v1(), ParentID: selected ? selected.getParentID() : -1, NextSiblingID: selected ? selected.getNextSiblingID() : -1,
                billsID: bills.tree.selected.getID()
            };
            //定额类型插入当前工作内容焦点行，
            if(selected && selected.data.type === itemType.job && datas[i].type === itemType.ration){
                newNodeData.ParentID = selected.getID();
                newNodeData.NextSiblingID = -1;
            }
            Object.assign(newNodeData, datas[i]);
            newDataIndex[i] = newNodeData;
        }
        for(let i = 0; i < datas.length; i++){
            //第一个节点
            if(i === 0){
                //非插入成子节点,更新选中节点NestSiblingID
                if(selected && !(selected.data.type === itemType.job && datas[i].type === itemType.ration)){
                    updateDatas.push({updateType: updateType.update, findData: {ID: selected.getID()}, updateData: {NextSiblingID: newDataIndex[i].ID}});
                }
            }
            //非最后一个节点
            if(i !== datas.length - 1){
                newDataIndex[i].NextSiblingID = newDataIndex[i + 1].ID;
            }
            updateDatas.push({updateType: updateType.create, updateData: newDataIndex[i]});
        }
        updateGuideItems(updateDatas, function () {
            for(let updateData of updateDatas){
                if(updateData.updateType === updateType.create){
                    let newNode = controller.insertByIDS(updateData.updateData.ID, updateData.updateData.ParentID, updateData.updateData.NextSiblingID);
                    //同步data
                    Object.assign(newNode.data, updateData.updateData);
                    sheet.setValue(newNode.serialNo(), 0, newNode.data.name);
                    refreshBtn(newNode);
                }
            }
            if(callback){
                callback();
            }
            $.bootstrapLoading.end();
        });
    }
    //项目指引删除操作
    //@return {void}
    function del(){
        $.bootstrapLoading.start();
        let controller = bills.tree.selected.guidance.controller;
        let selected = bills.tree.selected.guidance.tree.selected;
        let updateDatas = [];
        function getDelDatas(node){
            updateDatas.push({updateType: updateType.del, findData: {ID: node.getID()}, updateData: {deleted: true}});
            if(node.children.length > 0){
                for(let c of node.children){
                    getDelDatas(c);
                }
            }
        }
        getDelDatas(selected);
        updateGuideItems(updateDatas, function () {
            controller.delete();
            refreshBtn(bills.tree.selected.guidance.tree.selected);
            $.bootstrapLoading.end();
        });
    }
    //项目指引升级
    //@return {void}
    function upLevel(){
        $.bootstrapLoading.start();
        let controller = bills.tree.selected.guidance.controller;
        let selected = bills.tree.selected.guidance.tree.selected;
        let updateDatas = [];
        //更新父节点
        updateDatas.push({updateType: updateType.update, findData: {ID: selected.getParentID()}, updateData: {NextSiblingID: selected.getID()}});
        //更新选中节点
        updateDatas.push({udpateType: updateType.update, findData: {ID: selected.getID()},
            updateData: {ParentID: selected.parent.getParentID(), NextSiblingID: selected.parent.getNextSiblingID()}});
        if(selected.nextSibling && selected.children.length > 0){
            //更新选中节点最末子节点
            let lastChild = selected.children[selected.children.length - 1];
            updateDatas.push({updateType: updateType.update, findData: {ID: lastChild.getID()}, updateData: {NextSiblingID: selected.getNextSiblingID()}});
        }
        updateGuideItems(updateDatas, function () {
            controller.upLevel();
            refreshBtn(bills.tree.selected.guidance.tree.selected);
            $.bootstrapLoading.end();
        });
    }
    //项目指引降级
    //@return {void}
    function downLevel(){
        $.bootstrapLoading.start();
        let controller = bills.tree.selected.guidance.controller;
        let selected = bills.tree.selected.guidance.tree.selected;
        let updateDatas = [];
        //更新前兄弟节点
        updateDatas.push({updateType: updateType.update, findData: {ID: selected.preSibling.getID()}, updateData: {NextSiblingID: selected.getNextSiblingID()}});
        //更新前兄弟节点最末子节点
        if(selected.preSibling.children.length > 0){
            let lastChild = selected.preSibling.children[selected.preSibling.children.length - 1];
            updateDatas.push({updateType: updateType.update, findData: {ID: lastChild.getID()}, updateData: {NextSiblingID: selected.getID()}});
        }
        //更新选中节点
        updateDatas.push({updateType: updateType.update, findData: {ID: selected.getID()}, updateData: {ParentID: selected.preSibling.getID(), NextSiblingID: -1}});
        updateGuideItems(updateDatas, function () {
            controller.downLevel();
            refreshBtn(bills.tree.selected.guidance.tree.selected);
            $.bootstrapLoading.end();
        });
    }
    //项目指引上移
    //@return {void}
    function upMove(){
        $.bootstrapLoading.start();
        let controller = bills.tree.selected.guidance.controller;
        let selected = bills.tree.selected.guidance.tree.selected;
        let updateDatas = [];
        //更新前节点
        updateDatas.push({updateType: updateType.update, findData: {ID: selected.preSibling.getID()}, updateData: {NextSiblingID: selected.getNextSiblingID()}});
        //更新前前节点
        if(selected.preSibling.preSibling){
            updateDatas.push({udpateType: updateType.update, findData: {ID: selected.preSibling.preSibling.getID()}, updateData: {NextSiblingID: selected.getID()}});
        }
        //更新选中节点
        updateDatas.push({updateType: updateType.update, findData: {ID: selected.getID()}, updateData: {NextSiblingID: selected.preSibling.getID()}});
        updateGuideItems(updateDatas, function () {
            controller.upMove();
            refreshBtn(bills.tree.selected.guidance.tree.selected);
            $.bootstrapLoading.end();
        });
    }
    //项目指引下移
    //@return {void}
    function downMove(){
        $.bootstrapLoading.start();
        let controller = bills.tree.selected.guidance.controller;
        let selected = bills.tree.selected.guidance.tree.selected;
        let updateDatas = [];
        //更新下节点
        updateDatas.push({updateType: updateType.update, findData: {ID: selected.getNextSiblingID()}, updateData: {NextSiblingID: selected.getID()}});
        //更新前节点
        if(selected.preSibling){
            updateDatas.push({updateType: updateType.update, findData: {ID: selected.preSibling.getID()}, updateData: {NextSiblingID: selected.getNextSiblingID()}});
        }
        //更新选中节点
        updateDatas.push({updateType: updateType.update, findData: {ID: selected.getID()}, updateData: {NextSiblingID: selected.nextSibling.getNextSiblingID()}});
        updateGuideItems(updateDatas, function () {
            controller.downMove();
            refreshBtn(bills.tree.selected.guidance.tree.selected);
            $.bootstrapLoading.end();
        });
    }
    //获取定额类型的项目指引名称，通过定额转换
    //@param {Object}ration @return {String}
    function getRationItemName(ration){
        let arr = [];
        arr.push(ration.code ? ration.code : '');
        arr.push(ration.name ? ration.name : '');
        arr.push(ration.basePrice ? ration.basePrice : '');
        let rst = arr.join(' ');
        rst += `/${ration.unit ? ration.unit : ''}`;
        return rst;
    }
    //获取选中的定额表行
    //@return {Array}
    function getCheckedRationRows(){
        let rst = [];
        let sheet = ration.workBook.getActiveSheet();
        for(let i = 0; i < sheet.getRowCount(); i++){
            let checked = sheet.getValue(i, 0);
            if(checked){
                rst.push(i);
            }
        }
        return rst;
    }
    //清空选中定额表行
    //@param {Array}rows @return {void}
    function clearCheckedRation(rows) {
        let sheet = ration.workBook.getActiveSheet();
        renderSheetFunc(sheet, function () {
            for(let row of rows){
                sheet.setValue(row, 0, 0);
            }
        });
    }
    //获取要插入的定额数据
    //@param {Array}rows @return {Array}
    function getInsertRations(rows){
        let rst = [];
        //当前已存在定额
        let curRationIems = [];
        let selected = bills.tree.selected.guidance.tree.selected;
        if(selected){
            if(selected.data.type === itemType.job){
                curRationIems = selected.children;
            }
            else {
                curRationIems = selected.parent ? selected.parent.children : selected.tree.roots;
            }
        }
        for(let row of rows){
            let selRation = ration.cache[row];
            if(selRation){
                //添加的定额是否已存在，不重复添加
                let isExist = false;
                for(let curRation of curRationIems){
                    if(curRation.data.rationID == selRation.ID){
                        isExist = true;
                        break;
                    }
                }
                if(!isExist){
                    rst.push({type: itemType.ration, name: getRationItemName(selRation), rationID: selRation.ID});
                }
            }
        }
        return rst;
    }
    //初始化个按钮点击
    //@return {void}
    function initBtn(){
        $('#insert').click(function () {
            insert([{type: itemType.job, name: ''}]);
        });
        $('#delConfirm').click(function () {
            del();
            $('#delAlert').modal('hide');
        });
        $('#del').click(function () {
            $('#delAlert').modal('show');
        });
        $('#upLevel').click(function () {
            upLevel();
        });
        $('#downLevel').click(function () {
            downLevel();
        });
        $('#upMove').click(function () {
            upMove();
        });
        $('#downMove').click(function () {
            downMove();
        });
        $('#insertRation').click(function () {
            let checkedRows = getCheckedRationRows();
            let insertDatas = getInsertRations(checkedRows);
            if(insertDatas.length > 0){
                insert(insertDatas, function () {
                    //清空选择
                    clearCheckedRation(checkedRows);
                });
            }
            else {
                clearCheckedRation(checkedRows);
            }
        });
        //搜索定额
        $('#searchBtn').click(function () {
            let searchStr = $('#searchText').val();
            if(!searchStr || searchStr === ''){
                ration.cache = ration.datas;
            }
            else{
                ration.cache = _.filter(ration.datas, function (data) {
                    return data.code.includes(searchStr);
                });
            }
            let rationSheet = ration.workBook.getActiveSheet();
            renderSheetFunc(rationSheet, function () {
                showData(rationSheet, ration.headers, ration.cache);
            })
        });
    }
    //初始化视图
    //@param {void} @return {void}
    function initViews(){
        let modules = [bills, guideItem, ration];
        initWorkBooks(modules);
        getLibWithBills(libID);
        initBtn();
    }


    return {initViews};
})();

$(document).ready(function () {
    billsGuidance.initViews();
});