'use strict';

/**
 *
 *
 * @author Zhong
 * @date 2018/11/25
 * @version
 */

/*
* 造价书下方清单精灵
* */
//选项单选多选状态(按住alt为多选) 单选：0 多选：1
let billsGuidanceSelMode = 0;

const BillsElf = (function() {
    //清单精灵树挂载的地方,selected：当前选中的清单,mapping:以前九位清单编码为索引, 'xxx' : {elf: {datas, tree, controller}}
    let bills = {selected: null, mapping: {}};
    const itemType = {
        job: 0,
        ration: 1
    };
    const elfItem = {
        dom: $('#elfItems'),
        workBook: null,
        tree: null,
        controller: null,
        treeSetting: {
            treeCol: 0,
            emptyRows: 0,
            headRows: 1,
            headRowHeight: [40],
            defaultRowHeight: 21,
            cols: [
                {
                    width: 250,
                    readOnly: true,
                    head: {
                        titleNames: ["施工工序"],
                        spanCols: [1],
                        spanRows: [1],
                        vAlign: [1],
                        hAlign: [1],
                        font: ["Arial"]
                    },
                    data: {
                        field: "name",
                        vAlign: 1,
                        hAlign: 0,
                        font: "Arial"
                    }
                },
                {
                    width: 250,
                    readOnly: false,
                    head: {
                        titleNames: ["选项"],
                        spanCols: [1],
                        spanRows: [1],
                        vAlign: [1],
                        hAlign: [1],
                        font: ["Arial"]
                    },
                    data: {
                        field: "options",
                        vAlign: 1,
                        hAlign: 0,
                        font: "Arial"
                    }
                }
            ]
        },
        headers: [
            {name: '施工工序', dataCode: 'name', width: 180, rateWidth: 0.5, vAlign: 'center', hAlign: 'center', formatter: '@'},
            {name: '选项', dataCode: 'options', width: 180, rateWidth: 0.5,  vAlign: 'center', hAlign: 'left', formatter: '@'},
        ],
        rowHeaderWidth:25,
        events: {
            SelectionChanging: function (sender, info) {
                elfItemInitSel(info.newSelections[0].row);
            },
            CellClick: function (sender, args) {
                if(elfItem.headers[args.col]['dataCode'] === 'options' && args.sheetArea === 3){
                    if(!args.sheet.getCell(args.row, args.col).locked() && !args.sheet.isEditing()){
                        args.sheet.startEdit();
                    }
                }
            },
            ClipboardPasting: function (sender, info) {
                info.cancel = true;
            }
        }
    };
    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, 30, GC.Spread.Sheets.SheetArea.colHeader);
            sheet.setColumnWidth(0, sheet.getParent() === bills.workBook ? 15 : 25, GC.Spread.Sheets.SheetArea.rowHeader);
            if(sheet.getParent() === elfItem.workBook || sheet.getParent() === guideItem.workBook){
                sheet.setRowHeight(0, 20, 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;
        for(let event in events){
            workBook.bind(Events[event], events[event]);
        }
    }
    //根据宽度比例设置列宽
    //@param {Object}workBook {Number}workBookWidth {Array}headers @return {void}
    function setColumnWidthByRate() {
        let workBook = elfItem.workBook,
            workBookWidth = ($(window).width() - $('.main').find('.main-nav').width() - $('.main-side').width()) * 5 / 6,
            headers = elfItem.headers;
        if(workBook){
            workBookWidth -= 55;
            const sheet = workBook.getActiveSheet();
            sheet.suspendEvent();
            sheet.suspendPaint();
            for(let col = 0; col < headers.length; col++){
                if(headers[col]['rateWidth'] !== undefined && headers[col]['rateWidth'] !== null && headers[col]['rateWidth'] !== ''){
                    let width = workBookWidth * headers[col]['rateWidth'];
                    if(headers[col]['dataCode'] === 'options'){
                        width = width;
                    }
                    sheet.setColumnWidth(col, width, GC.Spread.Sheets.SheetArea.colHeader)
                }
                else {
                    if(headers[col]['headerWidth'] !== undefined && headers[col]['headerWidth'] !== null && headers[col]['headerWidth'] !== ''){
                        sheet.setColumnWidth(col, headers[col]['headerWidth'], GC.Spread.Sheets.SheetArea.colHeader)
                    }
                }
            }
            sheet.resumeEvent();
            sheet.resumePaint();
        }
    }
    //建表
    //@param {Object}module @return {void}
    function buildSheet() {
        if(!elfItem.workBook){
            elfItem.workBook = new GC.Spread.Sheets.Workbook(elfItem.dom[0], {sheetCount: 1});
            sheetCommonObj.spreadDefaultStyle(elfItem.workBook);
            let sheet = elfItem.workBook.getActiveSheet();
            sheet.options.isProtected = true;
            sheet.getRange(-1, 0, -1, 1).locked(true);
            sheet.getRange(-1, 1, -1, 1).locked(false);
            if(elfItem.rowHeaderWidth) {
                sheet.setColumnWidth(0, elfItem.rowHeaderWidth, GC.Spread.Sheets.SheetArea.rowHeader);
            }
            setOptions(elfItem.workBook, options);
            buildHeader(elfItem.workBook.getActiveSheet(), elfItem.headers);
            //setColumnWidthByRate(elfItem.workBook, $('#elfItems').width(), elfItem.headers);
            bindEvent(elfItem.workBook, elfItem.events);
        }
    }
    //刷新表
    //@return {void}
    function refreshWorkBook(){
        //计算内部的表格高度
        if ($('#qdjl').is(':visible')) {
            let totalHeight = $('#qdjl').height(),
                elfToolsHeight = $('#qdjlTools').height();
            $('#elfItems').height(totalHeight - elfToolsHeight);
            if (elfItem.workBook) {
                elfItem.workBook.refresh();
            }
        }
    }
    //清空表数据
    //@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);
            } else {
                sheet.setRowCount(0);
            }
        });
    }
    //初始化并输出树
    //@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, false);
        module.tree.loadDatas(datas);
        module.controller.showTreeData();
    }
    //清单精灵表焦点控制
    //@param {Number}row @return {void}
    function elfItemInitSel(row){
        let billsNode = bills.selected;
        let node = null;
        if(billsNode && billsNode.elf.tree){
            node = billsNode.elf.tree.items[row];
            if(node){
                billsNode.elf.tree.selected = node;
            }
        }
    }
    //清单焦点变换-清单精灵操作，获取清单前九位编码的标准清单清单精灵选项
    //@param {String}code @return {void}
    function billsSelElf(code) {
        let elfSheet = elfItem.workBook.getActiveSheet();
        cleanData(elfSheet, elfItem.headers, -1);
        if (!code || code === '') {
            return;
        }
        let nineCode = code.substr(0, 9);
        //查看此清单映射是否存在此编码映射数据,不存在，则新建映射
        if (!bills.mapping[nineCode]) {
            bills.mapping[nineCode] = {elf: {datas: [], tree: null, controller: null}};
        }
        let node = bills.mapping[nineCode];
        bills.selected = node;
        if(!node.elf.tree){
            let guidanceLibID;
            if (projectObj.project.projectInfo.engineeringInfo && projectObj.project.projectInfo.engineeringInfo.billsGuidance_lib) {
                guidanceLibID = projectObj.project.projectInfo.engineeringInfo.billsGuidance_lib[0] ? projectObj.project.projectInfo.engineeringInfo.billsGuidance_lib[0].id : null;
            }
            CommonAjax.post('/billsGuidance/api/getItemsByCode', {guidanceLibID: guidanceLibID, code: nineCode}, function (rstData) {
                //定额数据删除编号信息，（编码后+空格才会去除编码）
                for(let rData of rstData){
                    if(rData.type === itemType.ration){
                        let nameArr = rData.name.split(' ');
                        if(nameArr.length > 1){
                            nameArr.splice(0, 1);
                            rData.name = nameArr.join(' ');
                        }
                    }
                }
                node.elf.datas = rstData;
                //第一层节点数据
                let firstLevelDatas = _.filter(rstData, function (data) {
                    return data.ParentID == -1;
                });
                //第一层初始数据的选项显示
                for(let fData of firstLevelDatas){
                    let options = getOptions(fData, rstData);
                    fData.options = options.length > 0 ? options[0].name : '';
                    //下挂的选项
                    fData.optionsData = options && options.length > 0 ? _.cloneDeep(options) : [];
                    fData.optionChecked = options && options.length > 0 ? [_.cloneDeep(options[0])] : [];
                }
                renderSheetFunc(elfSheet, function () {
                    initTree(node.elf, elfSheet, elfItem.treeSetting, firstLevelDatas);
                    //初始选择选项
                    let initOptsOpr = [];
                    for(let elfNode of node.elf.tree.items){
                        if(elfNode.data.optionsData.length > 0){
                            initOptsOpr.push({node: elfNode, data: elfNode.data.optionsData[0]});
                        }
                    }
                    for(let opr of initOptsOpr){
                        insertNodeByData(opr.node, opr.data);
                    }
                    TREE_SHEET_HELPER.refreshTreeNodeData(elfItem.treeSetting, elfSheet, node.elf.tree.items, false);
                    setOptionsCellType(node.elf.tree.items);
                    //项目指引初始焦点
                    elfItemInitSel(elfSheet.getActiveRowIndex() ? elfSheet.getActiveRowIndex() : 0);
                });
            });
        }
        else{
            renderSheetFunc(elfSheet, function () {
                node.elf.controller.showTreeData();
                setOptionsCellType(node.elf.tree.items);
                //项目指引初始焦点
                elfItemInitSel(elfSheet.getActiveRowIndex() ? elfSheet.getActiveRowIndex() : 0);
            });
        }
    }
    //获取选项的深度
    //@param {Object}opt {Array}options(当前清单所有选项) @return {Array}
    function getOptionDepth(opt, options) {
        let parent = _.find(options, {ID: opt.ParentID});
        let depth = 0;
        while (parent){
            depth++;
            parent = _.find(options, {ID: parent.ParentID});
        }
        return depth;
    }
    //获取施工工序含有的选项(即当前施工工序的子项),获取的顺序按照NextSiblingID排序
    //@param {Object}process {Array}datas @return {Array}
    function getOptions(process, datas) {
        let rst = [];
        if(!process || !process.ID){
            return [];
        }
        let options = _.filter(datas, function (data) {
            return data.ParentID == process.ID;
        });
        if(options.length === 0){
            return [];
        }
        //根据NextSiblingID排序
        let IDMapping = {};
        for(let opt of options){
            IDMapping[opt.ID] = {self: opt, next: null, pre: null};
        }
        for(let opt of options){
            let next = IDMapping[opt.NextSiblingID] ? IDMapping[opt.NextSiblingID] : null;
            if(next){
                next.pre = IDMapping[opt.ID];
                IDMapping[opt.ID]['next'] = next;
            }
        }
        let first = null,
            rank = 0;
        for(let ID in IDMapping){
            let obj = IDMapping[ID];
            if(!obj.pre){
                first = obj;
                break;
            }
        }
        while(first){
            rank++;
            first.self.rank = rank;
            rst.push(first.self);
            first = first.next;
        }
        //兼容同层节点NextSibling错误的情况下，同层节点还是能显示出来（但是无法保证正确的顺序）
        //兼容模式下，不按照NextSibling排序，直接按照options元素位置排序
        if (rank !== options.length) {
            rst = [];
            rank = 0;
            for (let opt of options) {
                rank++;
                opt.rank = rank;
                rst.push(opt);
            }
        }

        return rst;
    }
    //设置清单精灵选项单元格
    //@param {Array}nodes @return {void}
    function setOptionsCellType(nodes) {
        let elfSheet = elfItem.workBook.getActiveSheet();
        for(let node of nodes){
            if(node.data.optionsData && node.data.optionsData.length > 0){
                elfSheet.getCell(node.serialNo(), 1).locked(false).cellType(getOptionsCellType());
            }
            else {
                elfSheet.getCell(node.serialNo(), 1).locked(true).cellType(new GC.Spread.Sheets.CellTypes.Base());
            }
        }
    }
    //递归插入节点:原始项目指引数据奇数层为需要插入的节点，偶数层为下拉选项
    //@param {Object}node(当前操作的节点) {Object}data(选项) @return {void}
    function insertNodeByData(node, data) {
        let elfSheet = elfItem.workBook.getActiveSheet();
        let sameDepthNodes = node.children;
        let insertNextSiblingID = -1,
            insertParentID = node.data.ID;
        //当前操作节点的选项
        let nodeOpts = getOptions(node.data, bills.selected.elf.datas);
        let subOpts = getOptions(data, bills.selected.elf.datas);
        let dataDepth = getOptionDepth(data, bills.selected.elf.datas);
        if(subOpts.length >0 && subOpts[0].type !== itemType.ration){
            if((dataDepth + 1) % 2 === 0){
                //排序后的数据
                let dataWithRank = _.find(nodeOpts, {ID: data.ID});
                //确定插入位置
                for(let subOpt of subOpts){
                    for(let subNode of sameDepthNodes){
                        //同层节点原本选项数据
                        let subNodeOptData = _.find(bills.selected.elf.datas, {ID: subNode.data.ID});
                        //同层节点原本父选项数据
                        let subNodeOptParent = _.find(bills.selected.elf.datas, {ID: subNodeOptData.ParentID});
                        let subNodeOptParentWithRank = _.find(nodeOpts, {ID: subNodeOptParent.ID});
                        //父项顺序决定插入位置
                        if(dataWithRank.rank < subNodeOptParentWithRank.rank){
                            insertNextSiblingID = subNode.data.ID;
                            break;
                        }
                        //父项顺序相同，根据子项顺序决定插入位置
                        else if(dataWithRank.rank = subNodeOptParentWithRank.rank){
                            if(subOpt.rank < subNode.data.rank){
                                insertNextSiblingID = subNode.data.ID;
                                break;
                            }
                        }
                    }
                    let sub2Opts = getOptions(subOpt, bills.selected.elf.datas);
                    subOpt.options = sub2Opts.length > 0 ? sub2Opts[0].name : '';
                    let cloneOpt = _.cloneDeep(subOpt);//不改变原本的数据，比如ParentID
                    cloneOpt.optionChecked = sub2Opts.length > 0 ? [_.cloneDeep(sub2Opts[0])] : [];
                    cloneOpt.optionsData = sub2Opts.length > 0 ? _.cloneDeep(sub2Opts) : [];
                    let newNode = node.tree.insertByData(cloneOpt, insertParentID, insertNextSiblingID);
                    elfSheet.addRows(newNode.serialNo(), 1);
                    node.tree.selected = newNode;
                    elfSheet.setSelection(newNode.serialNo(), elfSheet.getSelections()[0].col, 1, 1);
                    if(sub2Opts.length > 0 && sub2Opts[0].type !== itemType.ration){
                        insertNodeByData(newNode, sub2Opts[0]);
                    }
                }
            }
            else {
                insertNodeByData(node, subOpts[0]);
            }
        }
    }
    //获取选项下拉多选单元格
    //@param {void} @return {void}
    function getOptionsCellType() {
        let me = this;
        let elfSheet= elfItem.workBook.getActiveSheet();
        function OptionsCellType() {
            this.isEscKey=false;
            this.displayText='';
        }
        function setOptionsDiv($editor, node, cellRect, cellStyle, top) {
            if(!node){
                return '';
            }
            let height = cellRect.height;
            let options = getOptions(node.data, bills.selected.elf.datas);
            top = options.length > 6 ? top - 6 * height : top - options.length * height;
            let $editInput = $(`<div style="height: ${height}px; background: ${cellStyle.backColor};overflow: hidden; white-space: nowrap; text-overflow: ellipsis">${node.data.options}</div>`),
                $optDiv = $(`<div style="position: fixed; width: ${cellRect.width}px; top: ${top}px;background: ${cellStyle.backColor};border: 1px solid; overflow: auto; height: ${options.length > 6 ? height*6+5 : height*options.length+5}px; font-size: 0.9rem;"></div>`);
            for(let opt of options){
                let $opt = $(`<div title="${opt.name ? opt.name : ''}" class="elf-options" style="cursor: pointer; height: ${height}px;overflow: hidden; white-space: nowrap; text-overflow: ellipsis"></div>`),
                    $optInput = $(`<input rank="${opt.rank}" value="${opt.ID}" style="cursor: pointer; margin-left: 5px; vertical-align: middle" type="checkbox" 
                    ${node.data.optionChecked && _.find(node.data.optionChecked, {ID: opt.ID}) ? 'checked' : ''} ${projectReadOnly ? 'disabled' : ''}>`);
                $opt.text(`${opt.name ? opt.name : ''}`);
                $opt.prepend($optInput);
                $optDiv.append($opt);
                //选项复选框点击监听
                if (!projectReadOnly) {
                    $opt.click(function () {
                        //单选
                        if(billsGuidanceSelMode === 0){
                            let $allInput = $optDiv.find('input');
                            for(let input of $allInput){
                                $(input).prop('checked', false);
                            }
                            $($optInput).prop('checked', 'checked');
                            elfItem.workBook.getSheet(0).endEdit();
                        } else {//多选

                        }
                    });
                }
            }
            $editor.append($editInput);
            $editor.append($optDiv);
        }
        //选择后处理
        function doAfterSel(node) {
            let checkedSels = $('.elf-options').find('input:checked');
            let checkedNameArr = [],
                optionChecked= [];
            for(let checkSel of checkedSels){
                let opt = _.cloneDeep(_.find(bills.selected.elf.datas, {ID: $(checkSel).val()}));
                opt.rank = $(checkSel).attr('rank');
                checkedNameArr.push(opt.name);
                optionChecked.push(opt);
            }
            this.displayText = checkedNameArr.length > 0 ? checkedNameArr.join(';') : '';
            node.data.options = this.displayText;
            node.data.optionChecked = optionChecked;
            //删除节点
            let deleteNodes = getDeleteNodes(node, optionChecked);
            for(let dNode of deleteNodes){
                elfSheet.deleteRows(dNode.serialNo(), dNode.posterityCount() + 1);
                node.tree.delete(dNode);
            }
            //插入节点
            for(let perCheked of optionChecked){
                let exist = false;
                let subOpts = getOptions(perCheked, bills.selected.elf.datas);
                for(let subNode of node.children){
                    for(let subOpt of subOpts){
                        if(subNode.data.ID === subOpt.ID){
                            exist = true;
                            break;
                        }
                    }
                }
                //不重复且不为定额时插入
                if(!exist && perCheked.type !== itemType.ration){
                    insertNodeByData(node, perCheked);//这里递归，默认第一个
                }
            }
            TREE_SHEET_HELPER.refreshTreeNodeData(elfItem.treeSetting, elfSheet, node.tree.items, false);
            setOptionsCellType(node.tree.items);
        }
        //获取删除节点
        function getDeleteNodes(node, optionChecked) {
            let rst = [];
            for(let subNode of node.children){
                let exist = false;
                for(let perChecked of optionChecked){
                    let subOpts = getOptions(perChecked, bills.selected.elf.datas);
                    for(let subOpt of subOpts){
                        if(subNode.data.ID === subOpt.ID){
                            exist = true;
                            break;
                        }
                    }
                }
                if(!exist){
                    rst.push(subNode);
                }
            }
            return rst;
        }
        OptionsCellType.prototype = new GC.Spread.Sheets.CellTypes.Base();

        OptionsCellType.prototype.createEditorElement = function (context) {
            let element = document.createElement("div");//这里创建的，会自动销毁
            return element
        };
        OptionsCellType.prototype.activateEditor = function (editorContext, cellStyle, cellRect, context) {
            if (editorContext) {
                let $editor = $(editorContext);
                $editor.css("position", "fixed");
                $editor.css("background", "white");
                $editor.css("width", cellRect.width);
                $editor.attr("gcUIElement", "gcEditingInput");
                //编辑文本框距离浏览器的top
                let top = $('.header').height() + $('#zaojiashu').find('.toolsbar').height() + $('#top_div').height() + $('#bottom_div_ul').height() + 1 + $('.resize-y').height();
                let activeCellTop = $editor.parent().parent().css('top');
                activeCellTop = parseFloat(activeCellTop.replace('px', ''));
                let node = bills.selected.elf.tree.items[elfSheet.getActiveRowIndex()];
                setOptionsDiv($editor, node, cellRect, cellStyle, top + activeCellTop);
                this.isEscKey = false;
            }
        }
        OptionsCellType.prototype.deactivateEditor = function (editorContext, context) {

        };
        OptionsCellType.prototype.setEditorValue = function (editor, value, context) {
            this.displayText = value;
        };
        OptionsCellType.prototype.getEditorValue = function (editor, context) {
            let me = this;
            let node = bills.selected.elf.tree.items[elfSheet.getActiveRowIndex()];
            if(this.isEscKey !=true){
                renderSheetFunc(elfSheet, function () {
                    doAfterSel.call(me, node);
                });
            }
            this.isEscKey = false;
            return this.displayText;
        };
        OptionsCellType.prototype.updateEditor = function (editorContext, cellStyle, cellRect, context) {

        };
        OptionsCellType.prototype.isReservedKey = function (e, context) {
            //cell type handle tab key by itself
            this.isEscKey = e.keyCode === GC.Spread.Commands.Key.esc;
            return false;
        };
        /* OptionsCellType.prototype.paint = function (ctx, value, x, y, w, h, style, options) {
         if(style.backColor){
         ctx.fillStyle = style.backColor;
         ctx.fillRect(x, y, w, h);
         ctx.save();
         }
         //边长
         const l = 7;
         let leftPointX = x + w - 15,
         rightPointX = leftPointX + l,
         middlePointX = (leftPointX + rightPointX)/2;
         const cos30 = Math.cos(2*Math.PI * 30 / 360);
         let hL = l * cos30;
         let beginY = y + h/2 - hL;
         ctx.beginPath();
         ctx.moveTo(leftPointX, beginY);
         ctx.lineTo(rightPointX, beginY);
         ctx.lineTo(middlePointX, beginY + hL);
         ctx.fillStyle = 'black';
         ctx.fill();
         ctx.save();
         };*/
        // override getHitInfo to allow cell type get mouse messages
        OptionsCellType.prototype.getHitInfo = function (x, y, cellStyle, cellRect, context) {
            return {
                x: x,
                y: y,
                row: context.row,
                col: context.col,
                cellStyle: cellStyle,
                cellRect: cellRect,
                sheetArea: context.sheetArea
            };
        };
        return new OptionsCellType();
    }
    //获取清单精灵生成的定额数据(跳过重复，不允许重复插入)
    //@return {Array}
    function getInsertElfRationData(){
        let rst = [];
        if(!bills.selected || !bills.selected.elf){
            return rst;
        }
        let tree = bills.selected.elf.tree;
        if(!tree){
            return rst;
        }
        let mainSelected = projectObj.project.mainTree.selected;
        let mainSelRationNodes = _.filter(mainSelected.children, function (c) {
            return c.data && c.data.type === rationType.ration;
        });
        //原本清单存在此定额
        function existTheRation(rationID) {
            let r = _.find(mainSelRationNodes, function (node) {
                return node.data && node.data.stdID && node.data.stdID == rationID;
            });
            return r;
        }
        //造价书当前选中清单下的定额
        for(let node of tree.items){
            for(let perChecked of node.data.optionChecked){
                //选项直接是定额
                if(perChecked.type === itemType.ration && !existTheRation(perChecked.rationID)){
                    rst.push({itemQuery: {userID: userID, ID: perChecked.rationID}, rationType: rationType.ration});
                }
                //选项下子选项是定额
                else {
                    let rationOpts = getOptions(perChecked, bills.selected.elf.datas);
                    for(let ration of rationOpts){
                        if(ration.type === itemType.ration && !existTheRation(ration.rationID)){
                            rst.push({itemQuery: {userID: userID, ID: ration.rationID}, rationType: rationType.ration});
                        }
                    }
                }
            }
        }
        return rst;
    }
    //获取清单精灵插入单条定额的数据
    //@return {Array}
    function getInsertElfSingleRation() {
        let rst = [];
        if (!bills.selected || !bills.selected.elf) {
            return rst;
        }
        let tree = bills.selected.elf.tree;
        if (!tree) {
            return rst;
        }
        let elfSelected = tree.selected;
        if (!elfSelected || !elfSelected.data.optionChecked || !elfSelected.data.optionChecked[0]) {
            return rst;
        }
        let mainSelected = projectObj.project.mainTree.selected;
        let mainSelRationNodes = _.filter(mainSelected.children, function (c) {
            return c.data && c.data.type === rationType.ration;
        });
        //原本清单存在此定额
        function existTheRation(rationID) {
            let r = _.find(mainSelRationNodes, function (node) {
                return node.data && node.data.stdID && node.data.stdID == rationID;
            });
            return r;
        }
        //选中的节点第一个选项时定额选项或第一个选项下的子选项时定额选项
        let firstOptionChecked = elfSelected.data.optionChecked[0];
        if (firstOptionChecked.type === itemType.ration && !existTheRation(firstOptionChecked.rationID)) {
            rst.push({itemQuery: {userID: userID, ID: firstOptionChecked.rationID}, rationType: rationType.ration});
        } else {
            let rationOpts = getOptions(firstOptionChecked, bills.selected.elf.datas);
            for(let ration of rationOpts){
                if(ration.type === itemType.ration && !existTheRation(ration.rationID)){
                    rst.push({itemQuery: {userID: userID, ID: ration.rationID}, rationType: rationType.ration});
                    break;
                }
            }
        }
        return rst;
    }
    //插入定额
    //@return {void}
    async function insertRations(addRationDatas){
        if(addRationDatas.length > 0){
            try {
                $.bootstrapLoading.start();
                await projectObj.project.Ration.addMultiRation(addRationDatas);
                projectObj.setActiveCell('quantity', true);
            } catch (err) {
                console.log(err);
                if (!$('hintBox_form').is(':visible')) {
                    alert(err);
                }
            } finally {
                $.bootstrapLoading.end();
            }
        }
    }
    //各监听事件
    //@return {void}
    function bindListener(){
        //插入定额
        $('#elfInsertRation').click(function () {
            let addRationDatas =  getInsertElfRationData();
            insertRations(addRationDatas);
        });
        //插入单条
        $('#elfInsertSingle').click(function () {
            let addRationDatas = getInsertElfSingleRation();
            insertRations(addRationDatas);
        })
    }
    return {buildSheet, refreshWorkBook, billsSelElf, setColumnWidthByRate, bindListener};
})();

$(document).ready(function () {
    BillsElf.bindListener();
});