'use strict';

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

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

const BillsSub = (function() {
    //清单子树挂载的地方,selected：当前选中的清单,mapping:以前九位清单编码为索引, 'xxx' : {sub: {datas, tree, controller}}
    let bills = {selected: null, mapping: {}};
    // 指引类型
    const itemType = {
        // 工作内容
        job: 0,
        // 定额
        ration: 1
    };
    // 库类型
    const libType = {
        // 清单指引
        guidance: 1,
        // 清单精灵
        elf: 2
    };
    // 清单精灵
    const elfItem = {
        dom: $('#billsSubItems_JL'),
        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 guideItem = {
        dom: $('#billsSubItems_ZY'),
        workBook: null,
        tree: null,
        controller: null,
        treeSetting: {
            treeCol: 0,
            emptyRows: 0,
            headRows: 1,
            headRowHeight: [40],
            defaultRowHeight: 21,
            cols: [
                {
                    width: 420,
                    readOnly: true,
                    head: {
                        titleNames: ["项目指引"],
                        spanCols: [1],
                        spanRows: [1],
                        vAlign: [1],
                        hAlign: [1],
                        font: ["Arial"]
                    },
                    data: {
                        field: "name",
                        vAlign: 1,
                        hAlign: 0,
                        font: "Arial"
                    }
                },
                {
                    width: 35,
                    readOnly: false,
                    head: {
                        titleNames: ["选择"],
                        spanCols: [1],
                        spanRows: [1],
                        vAlign: [1],
                        hAlign: [1],
                        font: ["Arial"]
                    },
                    data: {
                        field: "select",
                        vAlign: 1,
                        hAlign: 1,
                        font: "Arial"
                    }
                }
            ]
        },
        headers: [
            {name: '项目指引', dataCode: 'name', width: 300, vAlign: 'center', hAlign: 'left', formatter: '@'},
            {name: '选择', dataCode: 'select', width: 35, vAlign: 'center', hAlign: 'center', formatter: '@'},
        ],
        rowHeaderWidth:25,
        events: {
            /*EditStarting: function (sender, args) {
                if(!bills.tree || guideItem.headers[args.col]['dataCode'] === 'name'){
                    args.cancel = true;
                }
            },*/
            ButtonClicked: function (sender, args) {
                if(args.sheet.isEditing()){
                    args.sheet.endEdit(true);
                }
                //refreshInsertRation();
            },
        }
    };

    // 目前的模块：清单精灵或清单指引，默认是清单指引
    let curModule = guideItem;
    let curModules = [];// 清单指引和清单精灵共存
    let isFirst = true;
    // 切换目前的模块
    // 1:清单指引 2:清单精灵
    function switchModule(type) {
       
        if(type === libType.guidance){
          curModules.push(guideItem);
          if(isFirst) gljOprObj.billsTab = "#linkQDZY";
        }else{
          curModules.push(elfItem);
          if(isFirst) gljOprObj.billsTab = "#linkQDJL";
        }
        //2020-03-20清单指引和清单精灵并且，暂不用切换显示，只需绑定事件
        /* let libText;
        if (type === libType.guidance) {  
            curModule = guideItem;
            libText = '清单指引';
            // 动态按钮
            $('#guidanceInsertRation').show();
            $('#elfInsertRation').hide();
            $('#elfInsertSingle').hide();
        } else {
            curModule = elfItem;
            libText = '清单精灵';
            // 动态按钮
            $('#guidanceInsertRation').hide();
            $('#elfInsertRation').show();
            $('#elfInsertSingle').show();
        }
        $('#qdjlTools').show();
        // 库名称、清单子菜单名称动态显示
        $('#linkQDJL').text(libText); */
        // 监听按钮事件
       if(isFirst == true) bindListener();//绑定一次事件就行了
       isFirst = false;
    }

    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(cmodule) {
        if(!cmodule.workBook){
            cmodule.workBook = new GC.Spread.Sheets.Workbook(cmodule.dom[0], {sheetCount: 1});
            sheetCommonObj.spreadDefaultStyle(cmodule.workBook);
            let sheet = cmodule.workBook.getActiveSheet();
            /*sheet.options.isProtected = true;
            sheet.getRange(-1, 0, -1, 1).locked(true);
            sheet.getRange(-1, 1, -1, 1).locked(false);*/
            if(cmodule.rowHeaderWidth) {
                sheet.setColumnWidth(0, cmodule.rowHeaderWidth, GC.Spread.Sheets.SheetArea.rowHeader);
            }
            setOptions(cmodule.workBook, options);
            buildHeader(cmodule.workBook.getActiveSheet(), cmodule.headers);
            bindEvent(cmodule.workBook, cmodule.events);
        }
    }

    function buildSheets(){
      for(let c of curModules){
        buildSheet(c);
      }
    }


    //刷新表
    //@return {void}
    function refreshWorkBook(){
        let eleID = "";
        let spreadEleID = "";
        let toolsID = "";
        if(gljOprObj.activeTab=='#linkQDZY'){
          curModule = guideItem;
           eleID = "qdzy";
           spreadEleID = "billsSubItems_ZY";
           toolsID = "qdzyTools";
        }else if(gljOprObj.activeTab=='#linkQDJL'){
           eleID = "qdjl";
           spreadEleID = "billsSubItems_JL";
           toolsID = "qdjlTools";
          curModule = elfItem;
        }
        if(eleID == "") return; 
        //计算内部的表格高度
        if ($('#'+eleID).is(':visible')) {
            let totalHeight = $('#'+eleID).height(),
                elfToolsHeight = $('#'+toolsID).height();
            $('#'+spreadEleID).height(totalHeight - elfToolsHeight);
            if (curModule.workBook) {
                curModule.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.sub.tree){
            node = billsNode.sub.tree.items[row];
            if(node){
                billsNode.sub.tree.selected = node;
            }
        }
    }
    // 清单精灵数据初始化
    function initElf(sheet, elf, treeData) {
        //定额数据删除编号信息，（编码后+空格才会去除编码）
        for(let rData of treeData){
            if(rData.type === itemType.ration){
                let nameArr = rData.name.split(' ');
                if(nameArr.length > 1){
                    nameArr.splice(0, 1);
                    rData.name = nameArr.join(' ');
                }
            }
        }
        elf.sub.datas = treeData;
        //第一层节点数据
        let firstLevelDatas = _.filter(treeData, function (data) {
            return data.ParentID == -1;
        });
        //第一层初始数据的选项显示
        for(let fData of firstLevelDatas){
            let options = getOptions(fData, treeData);
            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(sheet, function () {
            initTree(elf.sub, sheet, elfItem.treeSetting, firstLevelDatas);
            //初始选择选项
            let initOptsOpr = [];
            for(let elfNode of elf.sub.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, sheet, elf.sub.tree.items, false);
            setOptionsCellType(elf.sub.tree.items);
            //项目指引初始焦点
            elfItemInitSel(sheet.getActiveRowIndex() ? sheet.getActiveRowIndex() : 0);
        });
    }
    // 已经初始化过的清单精灵数据，重新展示
    function reshowElf(sheet, elf) {
        renderSheetFunc(sheet, function () {
            elf.sub.controller.showTreeData();
            setOptionsCellType(elf.sub.tree.items);
            //清单精灵初始焦点
            elfItemInitSel(sheet.getActiveRowIndex() ? sheet.getActiveRowIndex() : 0);
        });
    }
    //根据项目指引的类型设置单元格类型，定额类型的项目指引为复选框
    //@param {Array}nodes @return {void}
    function setItemCellType(nodes){
        //设置单元格类型
        const base = new GC.Spread.Sheets.CellTypes.Base();
        const checkBox = new GC.Spread.Sheets.CellTypes.CheckBox();
        const sheet = guideItem.workBook.getActiveSheet();
        renderSheetFunc(sheet, function(){
            for(let node of nodes){
                sheet.setCellType(node.serialNo(), 1, node.data.type === itemType.ration ?  checkBox : base);
            }
        });
    }
    // 清单指引数据初始化
    function initGuidance(sheet, guidance, treeData) {
        guidance.sub.datas = treeData;
        renderSheetFunc(sheet, function () {
            initTree(guidance.sub, sheet, guideItem.treeSetting, treeData);
            //TREE_SHEET_HELPER.refreshTreeNodeData(guideItem.treeSetting, sheet, guidance.sub.tree.items, false);
            setItemCellType(guidance.sub.tree.items);
        });
    }
    // 已经初始化过的清单指引数据，重新展示
    function reshowGuidance(sheet, guidance) {
        renderSheetFunc(sheet, function () {
            guidance.sub.controller.showTreeData();
            setItemCellType(guidance.sub.tree.items);
        });
    }
    //清单焦点变换-清单子界面操作，获取清单前九位编码的标准清单清单精灵选项 或 清单指引数据
    //@param {String}code @return {void}
    function billsSelSub(code) {
        let type = libType.guidance;//指引和精灵可共存，所以需要类型区分
        curModule = guideItem;
        if(gljOprObj.activeTab=='#linkQDJL'){
          type = libType.elf;
          curModule = elfItem;
        }
        let sheet = curModule.workBook.getActiveSheet();
        cleanData(sheet, curModule.headers, -1);
        if (!code || code === '') {
            return;
        }
        let nineCode = code.substr(0, 9);
        //查看此清单映射是否存在此编码映射数据,不存在，则新建映射
        if (!bills.mapping[nineCode+type]) {
            bills.mapping[nineCode+type] = {sub: {datas: [], tree: null, controller: null}};
        }
        let container = bills.mapping[nineCode+type];
        bills.selected = container;
        if(!container.sub.tree){
            let guidanceLibID;
            if (projectObj.project.projectInfo.engineeringInfo && projectObj.project.projectInfo.engineeringInfo.billsGuidance_lib) {
                for(let lib of projectObj.project.projectInfo.engineeringInfo.billsGuidance_lib){
                  if(lib && lib.type == type)  guidanceLibID = lib.id;
                }
            }
            CommonAjax.post('/billsGuidance/api/getItemsByCode', {guidanceLibID: guidanceLibID, code: nineCode}, function (rstData) {
                curModule === elfItem
                    ? initElf(sheet, container, rstData)
                    : initGuidance(sheet, container, rstData);
            });
        } else{
            curModule === elfItem
                ? reshowElf(sheet, container)
                : reshowGuidance(sheet, container);
        }
    }
    //获取选项的深度
    //@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.sub.datas);
        let subOpts = getOptions(data, bills.selected.sub.datas);
        let dataDepth = getOptionDepth(data, bills.selected.sub.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.sub.datas, {ID: subNode.data.ID});
                        //同层节点原本父选项数据
                        let subNodeOptParent = _.find(bills.selected.sub.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.sub.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.sub.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: 14px;"></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.sub.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.sub.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.sub.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() + $('#qdjlTools').height() + $('.resize-y').height();
                let node = bills.selected.sub.tree.items[elfSheet.getActiveRowIndex()];
                setOptionsDiv($editor, node, cellRect, cellStyle, top + cellRect.y);
                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.sub.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.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();
    }
    //原本清单存在此定额
    function existTheRation(nodes, rationID) {
        return nodes.find(node => node.data && node.data.stdID == rationID)
    }
    // 获取清单指生成的定额数据（不允许重复插入）
    function getInsertGuidanceRationData() {
        let rst = [];
        if(!bills.selected || !bills.selected.sub){
            return rst;
        }
        let tree = bills.selected.sub.tree;
        if(!tree){
            return rst;
        }
        let mainSelected = projectObj.project.mainTree.selected,
            mainSelRationNodes = mainSelected.children.filter(node => node.data && node.data.type === rationType.ration);
        // 从指引表从获取勾选的定额数据
        let sheet = guideItem.workBook.getSheet(0),
            rowCount = sheet.getRowCount();
        for (let row = 0; row < rowCount; row++) {
            let data = tree.items[row].data;
            // 勾选的定额，且该定额在目标清单下不存在才插入
            let isChecked = sheet.getValue(row, 1);
            if (isChecked
                && data.type === itemType.ration
                && !existTheRation(mainSelRationNodes, data.rationID)) {
                rst.push({
                    itemQuery: {
                        userID,
                        ID: data.rationID
                    },
                    rationType: rationType.ration
                });
            }
        }
        return rst;
    }

    //获取清单精灵生成的定额数据(跳过重复，不允许重复插入)
    //@return {Array}
    function getInsertElfRationData() {
        let rst = [];
        if(!bills.selected || !bills.selected.sub){
            return rst;
        }
        let tree = bills.selected.sub.tree;
        if(!tree){
            return rst;
        }
        let mainSelected = projectObj.project.mainTree.selected,
            mainSelRationNodes = mainSelected.children.filter(node => node.data && node.data.type === rationType.ration);
        //造价书当前选中清单下的定额
        for(let node of tree.items){
            for(let perChecked of node.data.optionChecked){
                //选项直接是定额
                if(perChecked.type === itemType.ration && !existTheRation(mainSelRationNodes, perChecked.rationID)){
                    rst.push({itemQuery: {userID: userID, ID: perChecked.rationID}, rationType: rationType.ration});
                }
                //选项下子选项是定额
                else {
                    let rationOpts = getOptions(perChecked, bills.selected.sub.datas);
                    for(let ration of rationOpts){
                        if(ration.type === itemType.ration && !existTheRation(mainSelRationNodes, 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.sub) {
            return rst;
        }
        let tree = bills.selected.sub.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,
            mainSelRationNodes = mainSelected.children.filter(node => node.data && node.data.type === rationType.ration);
        //选中的节点第一个选项时定额选项或第一个选项下的子选项时定额选项
        let firstOptionChecked = elfSelected.data.optionChecked[0];
        if (firstOptionChecked.type === itemType.ration && !existTheRation(mainSelRationNodes, firstOptionChecked.rationID)) {
            rst.push({itemQuery: {userID: userID, ID: firstOptionChecked.rationID}, rationType: rationType.ration});
        } else {
            let rationOpts = getOptions(firstOptionChecked, bills.selected.sub.datas);
            for(let ration of rationOpts){
                if(ration.type === itemType.ration && !existTheRation(mainSelRationNodes, 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();
            }
        }
    }
    function handleClick(getRationFunc) {
        if (!projectObj.project.Ration.canAdd(projectObj.project.mainTree.selected)) {
            return;
        }
        let addRationDatas = getRationFunc();
        insertRations(addRationDatas);
    }
    //各监听事件
    //@return {void}
    function bindListener(){
        // 插入定额
        $('#guidanceInsertRation').click(function () {
            handleClick(getInsertGuidanceRationData);
        });
        // 应用选项
        $('#elfInsertRation').click(function () {
            handleClick(getInsertElfRationData);
        });
        // 应用单条
        $('#elfInsertSingle').click(function () {
            handleClick(getInsertElfSingleRation);
        });
    }
    function toggleDiv(action){
       if(action=='hide'){
         $('#QDZY_div').hide(); 
         $('#QDJL_div').hide(); 
       }else{
          for(let c of curModules){
            if(c == guideItem)  $('#QDZY_div').show(); 
            if(c == elfItem)  $('#QDJL_div').show(); 
          }
       } 



    }
    return {
        toggleDiv,
        switchModule,
        buildSheets,
        refreshWorkBook,
        billsSelSub,
        setColumnWidthByRate
    };
})();