/**
 * 项目管理相关js
 *
 * @author CaiAoLin
 * @date 2017/8/22
 * @version
 */
let Tree = null;//
let movetoZTree = null;
let copytoZTree = null;
let engineering = [];
let feeRateData = [];
let isSaving = false;
let projectProperty = [];
let fileDelObj = null;
let curStep = 1; //当前在第几步
let infoData = null; //建设项目基本信息数据 （完整）
//需要的建设项目基本信息 （根据文件类型，因为需要切换文件类型获取不同的基本信息
//为了减少请求，infoData获取完整的基本信息数据，needfulInfoData标记当前文件类型所需基本信息数据）
let needfulInfoData = null;
let featureData = null; //工程特征数据
let projectType = {
    folder: 'Folder',
    project: 'Project',
    engineering: 'Engineering',
    tender: 'Tender'
};
let fileType = {
    unitPriceFile: 'UnitPriceFile',
    feeRateFile: 'FeeRateFile'
};

let taxTypeMap = {
    1:"一般计税",
    2:"简易计税"
};
//文件类型：招标，投标
const FileKind = {
    tender: 1, //投标
    bid: 2  //招标
};
let curTaxType = 1; //1:"一般计税",2:"简易计税"
let curValutionType = 'bill',   //计价方式默认只有清单计价
    curValuation = billValuation[0].id, //计价规则初始取第一个
    curValuationName = billValuation[0].name; //计价规则初始取第一个
/*
* 地区，同一费用定额下不同地区有不同单价，则新建单位工程时需要选择地区项
* 地区项为空的时候，前端不显示该下拉项，地区的赋值覆盖在over_write相关文件中
* */
let regions = [];

function isDef(v) {
    return typeof v !== 'undefined' && v !== null;
}

const addPath = {p_e_t: 'p_e_t', e_t: 'e_t', t: 't'};
//操作状态
const STATE = {
    addingTender: false,
    addingEng: false,
    addingProject: false,
    addingFolder: false,
    deleting: false,
    importing: false,
    moving: false
};
const projTreeObj = {
    tree: null,
    workBook: null,
    copyToWorkBook:null,
    replaceWorkBook:null,
    copySelected:null,
    preSelection: null,
    changeInfo:null,
    setting: {
        tree: {
            id: 'ID',
            pid: 'ParentID',
            nid: 'NextSiblingID',
            rootId: -1,
            autoUpdate: false
        },
        //0.48 0.13 0.15 0.15 0.09
        header: [
            {name: '工程列表', dataCode: 'name', width: 300, vAlign: 'center', hAlign: 'left'},
            {name: '工程造价', dataCode: 'engineeringCost', width: 100, vAlign: 'center', hAlign: 'right', formatter: '0.00'},
            {name: '工程专业', dataCode: 'feeStandardName', width: 100, vAlign: 'center', hAlign: 'left'},
            {name: '单价文件', dataCode: 'unitPriceFile', width: 140, vAlign: 'center', hAlign: 'left'},
            {name: '费率文件', dataCode: 'feeRateFile', width: 140, vAlign: 'center', hAlign: 'left'},
            {name: '创建日期', dataCode: 'createDateTime', width: 100, vAlign: 'center', hAlign: 'center'},
            {name: '分部分项合计', dataCode: 'subEngineering', width: 100, vAlign: 'center', hAlign: 'right', formatter: '0.00'},
            {name: '措施项目合计', dataCode: 'measure', width: 100, vAlign: 'center', hAlign: 'right', formatter: '0.00'},
            {name: '其他项目合计', dataCode: 'other', width: 100, vAlign: 'center', hAlign: 'right', formatter: '0.00'},
            //{name: '安全文明施工费', dataCode: 'safetyConstruction', width: 100, vAlign: 'center', hAlign: 'right', formatter: '0.00'},
            {name: '规费', dataCode: 'charge', width: 100, vAlign: 'center', hAlign: 'right', formatter: '0.00'},
            {name: '税金', dataCode: 'tax', width: 100, vAlign: 'center', hAlign: 'right', formatter: '0.00'},
            {name: '占造价比例(%)', dataCode: 'rate', width: 100, vAlign: 'center', hAlign: 'right', formatter: '0.00'},
            {name: '建筑面积', dataCode: 'buildingArea', width: 100, vAlign: 'center', hAlign: 'right', formatter: '0.00'},
            {name: '单方造价', dataCode: 'perCost', width: 100, vAlign: 'center', hAlign: 'right', formatter: '0.00'}
        ],
        //选中行颜色
        style: {
            defalutBackColor: 'White',
            selectedColor: '#BBFFFF'
        },
        options: {
            tabStripVisible:  false,
            allowContextMenu: false,
            allowCopyPasteExcelStyle : false,
            allowExtendPasteRange: false,
            allowUserDragDrop : false,
            allowUserDragFill: false,
            scrollbarMaxAlign : true,
            showDragDropTip:false
        }
    },
    copyToSetting:{
        header: [
            {name: '工程列表', dataCode: 'name', width: 550, vAlign: 'center', hAlign: 'left'}
        ],
        //选中行颜色
        style: {
            defalutBackColor: 'White',
            selectedColor: '#BBFFFF'
        },
        options: {

            tabStripVisible:  false,
            allowCopyPasteExcelStyle : false,
            allowExtendPasteRange: false,
            allowUserDragDrop : false,
            allowUserDragFill: false,
            scrollbarMaxAlign : true,
            showDragDropTip:false,
            allowContextMenu: false
        }
    },
    replaceSetting:{
        header: [
            {name: '工程列表', dataCode: 'name', width: 250, vAlign: 'center', hAlign: 'left'},
            {name: '选择', dataCode: 'selected', width: 50, vAlign: 'center', cellType:'checkBox'}
        ],
        //选中行颜色
        style: {
            defalutBackColor: 'White',
            selectedColor: '#BBFFFF'
        },
        options: {
            tabStripVisible:  false,
            allowCopyPasteExcelStyle : false,
            allowExtendPasteRange: false,
            allowUserDragDrop : false,
            allowUserDragFill: false,
            scrollbarMaxAlign : true,
            showDragDropTip:false,
            allowContextMenu: false
        }
    },
    renderSheetFuc: function (sheet, fuc) {
        sheet.suspendPaint();
        sheet.suspendEvent();
        fuc();
        sheet.resumePaint();
        sheet.resumeEvent();
    },
    setOptions: function (workbook, opts) {
        for(let opt in opts){
            workbook.options[opt] = opts[opt];
        }
    },
    bindEvent: function (workBook) {
        const _events = GC.Spread.Sheets.Events;
        let sheet = workBook.getActiveSheet();
        //改变选中节点set selected
        sheet.bind(_events.SelectionChanging, this.onSelectionChanging);
        sheet.bind(_events.EditStarting, this.onCellEditing);
        sheet.bind(_events.ClipboardPasting,this.onCellEditing);
        workBook.bind(_events.DragDropBlock, this.onDragDropBlock);
        workBook.bind(GC.Spread.Sheets.Events.ButtonClicked, this.changeFileClick)
    },
    buildHeader: function (sheet, headers) {
        let me = this;
        let fuc = function () {
            //sheet.options.isProtected = true;  //为了拖动功能，这里不设置protect,输入限制在editstarting控制
            sheet.options.protectionOptions = {
                allowResizeRows: true,
                allowResizeColumns: true
            };
            sheet.setColumnCount(headers.length);
            sheet.setRowHeight(0, 40, GC.Spread.Sheets.SheetArea.colHeader);
            let workBookWidth = getWorkBookWidth();
            for(let i = 0, len = headers.length; i < len; i++){
                sheet.setValue(0, i, headers[i].name, GC.Spread.Sheets.SheetArea.colHeader);
                let width = headers[i].width;
                sheet.setColumnWidth(i, width, GC.Spread.Sheets.SheetArea.colHeader);
                if (headers[i].formatter) {
                    sheet.setFormatter(-1, i, headers[i].formatter, GC.Spread.Sheets.SheetArea.viewport);
                }
            }
        };
        me.renderSheetFuc(sheet, fuc);
    },
    buildSheet: function (workBook,spreadID,setting) {//改成和复制项目spread共用
        let newWorkBook = workBook;
        if(!workBook){
            newWorkBook = new GC.Spread.Sheets.Workbook($('#'+spreadID)[0], {sheetCount: 1});
            this.setOptions(newWorkBook, setting.options);
            this.buildHeader(newWorkBook.getActiveSheet(), setting.header);
            this.bindEvent(newWorkBook);
            this.loadContextMenu();
            this.loadStartMenu();
        }else {
            workBook.refresh();
        }
        return newWorkBook;
    },
    // 获取新建按钮是否是disabled
    getAddBtnDisabled: function (action) {
        switch (action) {
            case projectType.folder:
            case projectType.project:
            case projectType.tender:
                return false;
            case projectType.engineering:
                const node = projTreeObj.tree.selected;
                return !node || node.data.projType === projectType.folder;
            default:
                return true;
        }
    },
    refreshAddMenuItems: function () {
        const items = [{
            el: $('#addFolderSub'),
            action: projectType.folder,
        }, {
            el: $('#addProjectSub'),
            action: projectType.project,
        }, {
            el: $('#addEngSub'),
            action: projectType.engineering,
        }, {
            el: $('#addTenderSub'),
            action: projectType.tender,
        }];
        items.forEach(item => {
            const disabled = this.getAddBtnDisabled(item.action);
            if (disabled) {
                item.el.addClass('disabled');
            } else {
                item.el.removeClass('disabled');
            }
        });
    },
    //右键菜单项
    contextMenuItems: {
        addFolder: {
            name: "新建文件夹",
            icon: 'fa-folder-o',
            disabled: function () {
                return projTreeObj.getAddBtnDisabled(projectType.folder);
            },
            callback: function (key, opt) {
                $("#add-folder-dialog").modal("show");
            }
        },
        addProject: {
            name: "新建建设项目",
            icon: 'fa-cubes',
            disabled: function () {
                return projTreeObj.getAddBtnDisabled(projectType.project);
            },
            callback: function (key, opt) {
                $('#add-project-dialog').modal('show');
            },
        },
        addEngineering: {
            name: "新建单项工程",
            icon: 'fa-cube',
            disabled: function () {
                return projTreeObj.getAddBtnDisabled(projectType.engineering);
            },
            callback: function (key, opt) {
                let selectedItem = projTreeObj.tree.selected;
                try {
                    if(selectedItem !== null  && selectedItem.data.projType !== projectType.folder){
                        $("#add-engineering-dialog").modal("show");
                    }

                } catch (error) {
                    alert(error);
                }
            }
        },
        addTender: {
            name: "新建单位工程",
            icon: 'fa-sticky-note-o',
            disabled: function () {
                return projTreeObj.getAddBtnDisabled(projectType.tender);
            },
            callback: function (key, opt) {
                //弹出新建单位工程之前，判断当前使用版本，且当前使用单位工程数是否已到最大值
                let selectedItem = projTreeObj.tree.selected;
                $("#add-tender-dialog").modal("show");
            }
        },
        rename: {
            name: "重命名",
            icon: 'fa-edit',
            disabled: function () {
                return !projTreeObj.tree.selected;
            },
            callback: function (key, opt) {
                $('#rename-name').val(projTreeObj.tree.selected.data.name ? projTreeObj.tree.selected.data.name : '');
                $('#rename-dialog').modal('show');
                setTimeout(function () {
                    $('#rename-name').focus();
                }, 300);
            }
        },
        delete: {
            name: "删除",
            icon: 'fa-remove',
            disabled: function () {
                let node = projTreeObj.tree.selected;
                return !node || (node.data.projType === projectType.folder && node.children.length > 0);
            },
            callback: function (key, opt) {
                if (projTreeObj.tree && projTreeObj.tree.selected) {
                    $('#del').modal('show');
                }
            }
        },
        copyTo: {
            name: "复制到",
            icon: 'fa-copy',
            disabled: function () {
                let node = projTreeObj.tree.selected;
                return !(node && node.data.projType === projectType.tender);
            },
            callback: function (key, opt) {
                let selectedItem = projTreeObj.tree.selected;
                try {
                    let selectedType = selectedItem !== null && selectedItem.data !== undefined ?
                        selectedItem.data.projType : '';
                    if (selectedType !== projectType.tender) {
                        throw '请选择单位工程进行复制';
                    }
                } catch (error) {
                    alert(error);
                    return false;
                }
                //更新选中项目缓存
                $('#copy-to-dialog').modal('show');
            }
        },
        share: {
            name: "分享",
            icon: 'fa-share',
            disabled: function () {
                let selectedItem = projTreeObj.tree.selected;
                return !selectedItem;
            },
            callback: function (key, opt) {
                const selected = projTreeObj.tree.selected;
                if (selected && selected.data.ID) {
                    SHARE_TO.initModal(SHARE_TO.Mode.PROJECT, selected.data.ID);
                }
            }
        },
        importInterface: {
            name: '导入招投标接口文件',
            icon: 'fa-cloud-upload',
            visible: function () {
                const names = ['重庆定额(2018)', '广东定额(2018)'];
                return compilationData && names.includes(compilationData.name);
            },
            callback: function () {
                $('#importInterface').modal('show');
            }
        },
        manageFiles: {
            name: "管理相关文件",
            icon: 'fa-list',
            disabled: function () {
                let selectedItem = projTreeObj.tree.selected;
                return !(selectedItem && selectedItem.data.projType !== projectType.folder);
            },
            callback: function (key, opt) {
                setDataToSideBar();
                $(".slide-sidebar").animate({width:"440"}).addClass("open");
                setTimeout(function () {
                    $("body").bind('click', function (event) {
                        var e = event || window.event; //浏览器兼容性
                        if (!$(event.target).is('a')) {
                            var elem = event.target || e.srcElement;
                            while (elem) { //循环判断至跟节点，防止点击的是div子元素
                                if (elem.className == "open-sidebar" || elem.className == 'slide-sidebar open') {
                                    return false;
                                }
                                if($(elem).attr('id') && $(elem).attr('id') === 'del-wj'){
                                    return false;
                                }
                                elem = elem.parentNode;
                            }
                            $(".slide-sidebar").animate({width: "0"}).removeClass("open")// 关闭处理
                            $('body').unbind('click');
                        }
                    });
                }, 500);
            }
        },
        refreshSummary: {
            name: "刷新项目造价",
            icon: 'fa-refresh',
            disabled: function () {
                let selectedItem = projTreeObj.tree.selected;
                return !(selectedItem && selectedItem.data.projType !== projectType.folder);
            },
            callback: function (key, opt) {
                //获取当前节点的建设项目ID
                projTreeObj.refreshProjectData();
            }
        },
        exportProject: {
            name: "导出建设项目",
            icon: 'fa-cloud-download',
            disabled: function () {
                let selectedItem = projTreeObj.tree.selected;
                if(selectedItem) return selectedItem.data.projType === projectType.folder;
                return true;
            },
            /* visible:function () {
             return false
             },*/
            callback: function (key, opt) {
                //获取当前节点的建设项目ID
                let selectedItem = projTreeObj.tree.selected;
                let projectNode = selectedItem; //取建设项目节点
                if(selectedItem.data.projType === projectType.engineering){
                    projectNode = selectedItem.parent;
                }
                if(selectedItem.data.projType === projectType.tender){
                    projectNode = selectedItem.parent.parent;
                }
                projTreeObj.exportProject(projectNode.data.ID,projectNode.data.name);
            }
        },
        importProject:{
            name: "导入建设项目",
            icon: 'fa-upload',
            disabled: function () {
                let selectedItem = projTreeObj.tree.selected;
                if(selectedItem){
                    //if(selectedItem.data.projType === projectType.project) return false;//如果是建设项目，可用
                    if(selectedItem.data.projType === projectType.folder){//如果是文件夹
                        if(selectedItem.children){
                            if(selectedItem.children.length == 0) return false;//如果文件夹没有子项，可用
                            if(selectedItem.children[0] .projType === projectType.project ) return false;//如果文件夹有子项，并且是建设项目，可用
                        }
                    }else{//除了文件夹，都可用
                        return false;
                    }
                } else {//列表为空时可以导入
                    return false;
                }
                return true;
            },
            /*  visible:function () {
             return false
             },*/
            callback: function (key, opt) {

                $("#confirm-import").hide();
                $("#import").modal('show');
                projTreeObj.getUploadToken();
            }
        },
        importExampleProject:{
            name: "加载例题",
            icon: 'fa-refresh',
            visible: function () {
                return false;
            },
            callback: function (key, opt) {

                projTreeObj.importExampleProjects();
            }
        }
    },
    //全部-开始（新建）按钮弹出菜单（新建单位工程）
    loadStartMenu: function () {
        let me = this;
        $('#startA').click(me.contextMenuItems.addTender.callback);
    },
    //spread中鼠标右键弹出菜单
    loadContextMenu: function () {
        let me = this;
        $.contextMenu({
            selector: '#projSpread',
            build: function ($trigger, e) {
                let target = SheetDataHelper.safeRightClickSelection($trigger, e, me.workBook);
                me.initSelection({row: target.row, rowCount: 1}, me.preSelection ? me.preSelection : null, me.workBook.getActiveSheet());
                return target.hitTestType === GC.Spread.Sheets.SheetArea.viewport || target.hitTestType === GC.Spread.Sheets.SheetArea.rowHeader;
            },
            items: {
                "addFolder": me.contextMenuItems.addFolder,
                "addProject": me.contextMenuItems.addProject,
                "addEngineering": me.contextMenuItems.addEngineering,
                "addTender": me.contextMenuItems.addTender,
                "spr1": '--------',
                "rename": me.contextMenuItems.rename,
                "delete": me.contextMenuItems.delete,
                "copyTo": me.contextMenuItems.copyTo,
                "spr2": '--------',
                "share": me.contextMenuItems.share,
                "importInterface": me.contextMenuItems.importInterface,
                "spr3": '--------',
                "manageFiles": me.contextMenuItems.manageFiles,
                "refreshSummary": me.contextMenuItems.refreshSummary,
                "exportProject":me.contextMenuItems.exportProject,
                "importProject":me.contextMenuItems.importProject,
                "importExampleProject":me.contextMenuItems.importExampleProject
            }
        });
    },
    //刷新按钮有效性（升降级、上下移）
    refreshBtn: function (selected) {
        const upLevel = $('#upLevel');
        const downLevel = $('#downLevel');
        const upMove = $('#upMove');
        const downMove = $('#downMove');
        if (!selected) {
            upLevel.addClass('disabled');
            downLevel.addClass('disabled');
            upMove.addClass('disabled');
            downMove.addClass('disabled');
            return;
        }
        /* 升级有效
         * 当前选中文件夹，且文件夹有父项，且父项是文件夹
         * 当前选中建设项目，且建设项目有父项，且父项是文件夹
         */
        if ([projectType.project, projectType.folder].includes(selected.data.projType)
            && selected.parent && selected.parent.data && selected.parent.data.projType === projectType.folder) {
            upLevel.removeClass('disabled');
        } else {
            upLevel.addClass('disabled');
        }
        /*
         * 降级有效
         * 当前选中文件夹，且文件夹有前兄弟，且前兄弟是文件夹
         * 当前选中建设项目，且建设项目有前兄弟，且前兄弟是文件夹
         * */
        if ([projectType.project, projectType.folder].includes(selected.data.projType)
            && selected.preSibling() && selected.preSibling().data.projType === projectType.folder) {
            downLevel.removeClass('disabled');
        } else {
            downLevel.addClass('disabled');
        }
        /*
         * 上移有效
         * 当前选中行有前兄弟，不论前兄弟类型
         * */
        selected.preSibling() ? upMove.removeClass('disabled') : upMove.addClass('disabled');
        /*
         * 后移有效
         * 当前选中行有后兄弟，不论后兄弟类型
         * */
        selected.nextSibling ? downMove.removeClass('disabled') : downMove.addClass('disabled');

    },
    doAfterTreeOpr: function ({selected, parent, next, projectMap}, action) {
        const me = this;
        $.bootstrapLoading.start();
        moveProjects({"user_id": userID, rootProjectID: null, projectMap: projectMap, feeRateMap: {}, unitPriceMap: {}},function (result) {
            for (let key in result) {//更新前端节点数据
                let updateData = result[key].update;
                let node = projTreeObj.tree.findNode(result[key].query.ID);
                if (node) {
                    for (let ukey in updateData) {
                        _.set(node.data,ukey,updateData[ukey]);
                    }
                }
            }
            projTreeObj.moveTo(selected, null, parent, next, null, action);
            $.bootstrapLoading.end();
            STATE.moving = false;
            projTreeObj.emitTreeChange();
        });
    },
    //升级后选中节点的后兄弟节点不成为其子节点，因为有层级类型限制(相当于选中节点移动到父项后成为其后兄弟)
    upLevel: function () {
        if (STATE.moving) {
            return;
        }
        STATE.moving = true;
        let selected = projTreeObj.tree.selected,
            parent = selected.parent.parent,
            next = selected.parent.nextSibling,
            projectMap = {};
        //更新父节点
        projectMap[selected.pid()] = {query: {ID: selected.pid()}, update: {NextSiblingID: selected.id()}};
        //更新选中节点前兄弟节点
        let orgPre = selected.preSibling();
        if (orgPre) {
            projectMap[orgPre.id()] = {query: {ID: orgPre.id()}, update: {NextSiblingID: selected.nid()}};
        }
        //更新选中节点
        projectMap[selected.id()] = {query: {ID: selected.id()}, update: {ParentID: selected.parent.pid(), NextSiblingID: selected.parent.nid()}};
        this.doAfterTreeOpr({selected, parent, next, projectMap});
    },
    downLevel: function () {
        if (STATE.moving) {
            return;
        }
        STATE.moving = true;
        let selected = projTreeObj.tree.selected,
            parent = null,
            next = null,
            projectMap = {};
        const maxFolderLevel = getMaxFolderLevel(selected);
        if (maxFolderLevel === 3) {
            return alert('文件夹不能超过3层');
        }
        //更新前兄弟节点
        let orgPre = selected.preSibling();
        parent = orgPre;
        projectMap[orgPre.id()] = {query: {ID: orgPre.id()}, update: {NextSiblingID: selected.nid()}};
        //更新前兄弟最后子节点
        if (orgPre.children.length > 0) {
            let lastChild = orgPre.lastChild();
            projectMap[lastChild.id()] = {query: {ID: lastChild.id()}, update: {NextSiblingID: selected.id()}};
        }
        //更新选中节点
        projectMap[selected.id()] = {query: {ID: selected.id()}, update: {ParentID: orgPre.id(), NextSiblingID: -1}};
        this.doAfterTreeOpr({selected, parent, next, projectMap}, 'downLevel');
    },
    upMove: function () {
        if (STATE.moving) {
            return;
        }
        STATE.moving = true;
        let selected = projTreeObj.tree.selected,
            parent = selected.parent,
            next = selected.preSibling(),
            projectMap = {};
        //更新前前兄弟
        let prepre = selected.preSibling().preSibling();
        if (prepre) {
            projectMap[prepre.id()] = {query: {ID: prepre.id()}, update: {NextSiblingID: selected.id()}};
        }
        //更新前兄弟
        let pre = selected.preSibling();
        projectMap[pre.id()] = {query: {ID: pre.id()}, update: {NextSiblingID: selected.nid()}};
        //更新选中节点
        projectMap[selected.id()] = {query: {ID: selected.id()}, update: {NextSiblingID: pre.id()}};
        this.doAfterTreeOpr({selected, parent, next, projectMap});
    },
    downMove: function () {
        if (STATE.moving) {
            return;
        }
        STATE.moving = true;
        let selected = projTreeObj.tree.selected,
            parent = selected.parent,
            next = selected.nextSibling.nextSibling,
            projectMap = {};
        //更新前兄弟
        let pre = selected.preSibling();
        if (pre) {
            projectMap[pre.id()] = {query: {ID: pre.id()}, update: {NextSiblingID: selected.nid()}};
        }
        //更新后兄弟
        projectMap[selected.nid()] = {query: {ID: selected.nid()}, update: {NextSiblingID: selected.id()}};
        //更新选中节点
        projectMap[selected.id()] = {query: {ID: selected.id()}, update: {NextSiblingID: selected.nextSibling.nid()}};
        this.doAfterTreeOpr({selected, parent, next, projectMap});
    },
    loadBtn: function () {
        $('#upLevel').click(this.upLevel.bind(this));
        $('#downLevel').click(this.downLevel.bind(this));
        $('#upMove').click(this.upMove.bind(this));
        $('#downMove').click(this.downMove.bind(this));
    },
    getSelStyle: function (backColor) {
        let style = new GC.Spread.Sheets.Style();
        style.backColor = backColor;
        style.borderLeft = new GC.Spread.Sheets.LineBorder("#D4D4D4", GC.Spread.Sheets.LineStyle.thin);
        style.borderTop = new GC.Spread.Sheets.LineBorder("#D4D4D4", GC.Spread.Sheets.LineStyle.thin);
        style.borderRight = new GC.Spread.Sheets.LineBorder("#D4D4D4", GC.Spread.Sheets.LineStyle.thin);
        style.borderBottom = new GC.Spread.Sheets.LineBorder("#D4D4D4", GC.Spread.Sheets.LineStyle.thin);
        return style;
    },
    //设置选中行底色
    setSelStyle: function (sel, backColor,sheet) {
        let me = this;
        //let sheet = me.workBook.getSheet(0);
        sel.row = sel.row === -1 ? 0 : sel.row;
        me.renderSheetFuc(sheet, function () {
            let style = me.getSelStyle(backColor);
            for(let i = 0; i < sel.rowCount; i++){
                let row = i + sel.row;
                sheet.setStyle(row, -1, style);
            }
        });
    },
    initSelection: function (newSel, oldSel = null,sheet) {
        let me = this;
        let node = me.tree.items[newSel.row];
        node = node ? node : null;
        me.refreshBtn(node);
        //恢复底色
        if(oldSel){
            me.setSelStyle(oldSel, me.setting.style.defalutBackColor,sheet);
        }
        //设置选中行底色
        if(newSel){
            me.setSelStyle(newSel, me.setting.style.selectedColor,sheet);
        }
        if(sheet.name()=="copyToSheet"){ //复制到
            me.copySelected = node;
            let canCopy = false;
            if(node){
                canCopy = node.data.projType == projectType.tender|| node.data.projType == projectType.engineering;
            }
            canCopy == true?$("#copy-to-confirm").removeClass("disabled"):$("#copy-to-confirm").addClass("disabled");
            return;//如果是复制到表，不用做后面的操作
        }else if(sheet.name() == "replaceSheet"){//如果是替换文件，不用做后面的操作
            return;
        }
        me.tree.selected = node;
        me.preSelection = newSel;
    },
    onSelectionChanging: function (sender, args) {
        let me = projTreeObj;
        me.initSelection(args.newSelections[0], args.oldSelections[0],args.sheet);
    },
    changeFileClick:async function (sender,args) {
        if(args.sheet.name() == "projectSheet"){
            await projTreeObj.initFileChangePage(projTreeObj.setting.header[args.col].dataCode);
            $("#mr_from").val(projTreeObj.setting.header[args.col].dataCode);
            $('#m_replace_file').modal('show');
        }else if(args.sheet.name() == "replaceSheet"){
            let cellType = args.sheet.getCellType(args.row, args.col);
            if(cellType instanceof GC.Spread.Sheets.CellTypes.CheckBox){
                projTreeObj.onReplaceNodeCheck(sender,args);
            }
        }
    },
    cusButtonClick:async function(info){
        projTreeObj.changeFileClick(null,info);
    },
    onDragDropBlock : function (sender,args) {//拖动移动项目位置
        let selected = projTreeObj.tree.selected;
        let targetNode = projTreeObj.tree.items[args.toRow];
        let projectMap = {},feeRateMap={},unitPriceMap = {},parent=null,next = null,oldProject=null;
        let rootProjectID = null;//记录建设项目ID
        //let updateObj = {project:[],feeRateFile:[],unitPriceFile:[]};
        args.cancel = true;//首先取消填充的动作
        if(args.sheet.name()=="copyToSheet"){ //如果是复制到表，不用做后面的操作
            return;
        }
        if(selected.preSibling()!=null&&selected.preSibling() == targetNode&&selected.data.projType == targetNode.data.projType){//如果目标节点与选中节点的前一节点一样，并且选中节点与目标节点项目类型也一样的话，不用移动
            return;
        }
        if(selected == targetNode){
            return;
        }

        if(selected.data.projType=="Tender"){//移动单位工程
            oldProject = selected.parent.parent;//记录原来的建设项目
            if(targetNode.data.projType=="Tender"||targetNode.data.projType=="Engineering"){//只能移动到这两个地方
                if(targetNode.data.projType=="Tender"){//移动到单位工程后面
                    [parent,next] = getMoveUpdateData(selected,targetNode,projectMap,true);
                    rootProjectID = targetNode.parent.pid();
                }else{//移动后成为单项工程的子项
                    [parent,next] =getMoveUpdateData(selected,targetNode,projectMap,false);
                    rootProjectID = targetNode.pid();
                }
                if(selected.data.property.rootProjectID != rootProjectID){//如果不属于同一个建设项目，要检查是否移动或复制单价文件和费率文件
                    projectMap[selected.id()].update['property.rootProjectID'] = rootProjectID; //要改变根项目ID
                    //检查费率文件和单价文件
                    moveOrCopy(selected,rootProjectID,feeRateMap,unitPriceMap,false);
                }
            }
        }
        if(selected.data.projType=="Engineering"){//移动的是单项工程
            oldProject = selected.parent;//记录原来的建设项目
            if(targetNode.data.projType=="Engineering"||targetNode.data.projType=="Project"){//目标位置是单项工程和建设项目
                if(targetNode.data.projType=="Engineering"){
                    [parent,next] = getMoveUpdateData(selected,targetNode,projectMap,true);
                    rootProjectID = targetNode.pid();
                }else {
                    [parent,next]  = getMoveUpdateData(selected,targetNode,projectMap,false);
                    rootProjectID = targetNode.id();
                }
                if(selected.pid() != rootProjectID){//跨了建设项目，更新子项目，同时要检查是否移动或复制子项的单价文件和费率文件。
                    //检查费率文件和单价文件
                    for(let c of selected.children){
                        projectMap[c.id()] = {query:{'ID':c.id()},update:{'property.rootProjectID':rootProjectID}};
                        moveOrCopy(c,rootProjectID,feeRateMap,unitPriceMap,true);
                    }
                }
            }
        }
        if(selected.data.projType=="Project"){//移动的是建设项目
            if(targetNode.data.projType=="Project"||targetNode.data.projType=="Folder") {//目标位置是建设项目和文件夹
                if(targetNode.data.projType=="Project"){
                    [parent,next]  = getMoveUpdateData(selected,targetNode,projectMap,true);
                }else {
                    [parent,next]  = getMoveUpdateData(selected,targetNode,projectMap,false);
                }
            }
        }
        if(selected.data.projType=="Folder"&&targetNode.data.projType=="Folder") {//文件夹只能移动到文件夹下
            [parent,next]  =  getMoveUpdateData(selected,targetNode,projectMap,false);//成为子项
        }
        if(_.isEmpty(projectMap)){//项目数据为空
            return;
        }
        $.bootstrapLoading.start();
        moveProjects({"user_id": userID,rootProjectID:rootProjectID,projectMap:projectMap,feeRateMap:feeRateMap,unitPriceMap:unitPriceMap},function (result) {
            for(let key in result){//更新前端节点数据
                let updateData = result[key].update;
                let node = projTreeObj.tree.findNode(result[key].query.ID);
                if(node){
                    for(let ukey in updateData){
                        _.set(node.data,ukey,updateData[ukey]);
                    }
                }
            }
            projTreeObj.moveTo(selected,targetNode,parent,next,oldProject);
            $.bootstrapLoading.end();
        });
        function getMoveUpdateData(sel,target,projectMap,sameLevel) {
            let tem_parent = null,tem_next = null;
            if(sameLevel==true){//移动后的位置的级别相同
                tem_parent = target.parent;
                tem_next = target.nextSibling;
                //移动到target的后面
                projectMap[target.id()] = {query:{'ID':target.id()},update:{'NextSiblingID':sel.id()}};
            }else {//移动后变成子项
                tem_parent = target;
                tem_next = target.firstChild();
            }
            let nextID = tem_next?tem_next.id():-1;
            if(sel.preSibling() != null){//如果原来有前项，更新下一节点
                projectMap[sel.preSibling().id()] = {query:{'ID':sel.preSibling().id()},update:{'NextSiblingID':sel.data.NextSiblingID}};
            }
            if(sel.parent.id() == tem_parent.id()){//移动前移动后的父项相同，只改变next
                if(selected.id() != nextID){//父项相同的情况下， 下一节点ID如果等于选中的ID即项目没有移动，不用做处理
                    projectMap[selected.id()] = {query:{'ID':selected.id()},update:{'NextSiblingID':nextID}};
                }
            }else {//
                let temData = {query:{'ID':selected.id()},update:{'ParentID':tem_parent.id(),'NextSiblingID':nextID}};
                let reName = projTreeObj.projectNameChecking(tem_parent,selected);//重名检查
                if(reName){
                    temData.update['name'] = reName
                }
                projectMap[selected.id()] = temData;
            }
            return [tem_parent,tem_next]
        }

        function moveOrCopy(sel,rootProjectID,feeRateMap,unitPriceMap,sameCheck) {//检查选中的项目使用的费率文件和单价文件是要移动还是复制一份
            let project = sel.parent.parent;//取建设项目
            let sameParent_f = true;
            let sameParent_u = true;
            let useFeeRateProject = getTendersByFile(fileType.feeRateFile,sel.data.property.feeFile.id,project);
            let useUnitPriceProject = getTendersByFile(fileType.unitPriceFile,sel.data.property.unitPriceFile.id,project);
            let tem_feeRate = {action:'copy',rootProjectID:rootProjectID,name:sel.data.property.feeFile.name,query:{ID:sel.data.property.feeFile.id}};
            let tem_unitPrice = {action:'copy',rootProjectID:rootProjectID,name:sel.data.property.unitPriceFile.name,query:{id:sel.data.property.unitPriceFile.id}}
            if(useFeeRateProject.length==1){//如果没有其它项目使用同一个费率文件，则移动
                tem_feeRate.action = 'move';
                tem_feeRate.update = {rootProjectID:rootProjectID};
            }
            if(useUnitPriceProject.length == 1){//如果没有其它项目使用同一个单价文件，则移动
                tem_unitPrice.action =  'move';
                tem_unitPrice.update = {root_project_id:rootProjectID};
            }
            feeRateMap[sel.id()] = tem_feeRate;
            unitPriceMap[sel.id()] = tem_unitPrice;
            if(sameCheck == true){//需要检查是否属于同一个单项工程，移动单项工程的时候用
                if(useUnitPriceProject.length > 1){
                    for(let f of useFeeRateProject){
                        if(f.pid()!=sel.pid()){//父节点不同
                            sameParent_f = false;
                            break;
                        }
                    }
                    if(sameParent_f == true){//如果使用的都是同属于一个单项工程，在移动单项工程的时候，移动费率文件和单价文件就可以了
                        feeRateMap[sel.id()].action = 'move';
                        feeRateMap[sel.id()].update = {rootProjectID:rootProjectID};
                    }
                }
                if(useUnitPriceProject.length > 1){
                    for(let u of useUnitPriceProject){
                        if(u.pid()!=sel.pid()){//父节点不同
                            sameParent_u = false;
                            break;
                        }
                    }
                    if(sameParent_u == true){
                        unitPriceMap[sel.id()].action =  'move';
                        unitPriceMap[sel.id()].update = {root_project_id:rootProjectID};
                    }
                }
            }
        }


    },
    projectNameChecking:function (parent,node,type) {
        //decDate = '（' + new Date().Format('MM-dd hh:mm:ss') + '恢复）';
        type=type?type:'移动';
        for(let c of parent.children){
           if(c.data.name == node.data.name){//如果存在同名的项目
               return  node.data.name + '（' + new Date().Format('MM-dd hh:mm:ss') + type+'）';
           }
        }
        return null;
    },
    onCellEditing:function (sender,args) {
        args.cancel = true;
    },
    getShowData: function (datas) {
        for(let data of datas){
            data.name = data.name ? data.name : '';
            if(data.projType !== projectType.tender){
                data.engineeringCost = '';
                data.unitPriceFile = '';
                data.feeRateFile = '';
                data.createDateTime = '';
            }
            else{
                data.engineeringCost = data.engineeringCost ? data.engineeringCost : 0;
                data.unitPriceFile = data.property && data.property.unitPriceFile && data.property.unitPriceFile.name ? data.property.unitPriceFile.name : '';
                data.feeRateFile = data.property && data.property.feeFile && data.property.feeFile.name ? data.property.feeFile.name : '';
                data.createDateTime = data.createDateTime ? new Date(data.createDateTime).Format('yyyy-MM-dd') : '';
            }
        }
    },
    openTender: function (ID, parent, timeoutTime) {
        setTimeout(function () {
            let newTab = window.open('about:blank');
            BeforeOpenProject(ID, {'fullFolder': GetFullFolder(parent)}, function () {
                let mainUrl = `/main?project=${ID}`;
                newTab.location.replace(mainUrl); //不能后退
                /* CommonAjax.get(mainUrl, [], function () {
                }); */
            });
        }, timeoutTime);
    },
    getTreeNodeCell: function (tree) {
        let me = projTreeObj;
        let indent = 20;
        let levelIndent = -5;
        let halfBoxLength = 5;
        let halfExpandLength = 3;
        let imgWidth = 18;
        let imgHeight = 14;
        let shareImg = document.getElementById('share_pic'),
            shareImgWidth = 13,
            shareImgHeight = 13;
        let defaultHeight = 17; // 单元格默认高度，getAutoFitHeight返回17时，单元格高度才是20...不清楚原因
        let TreeNodeCellType = function () {
        };
        TreeNodeCellType.prototype = new GC.Spread.Sheets.CellTypes.Text();
        // 自动行高处理 此函数在每次调用autoFitRow后调用，返回的值作为新的单元格高度
        // 在单元格设置为自动行高后，单元格的内容有空格时，spreadjs会将空格认为是换行，会导致高度计算不正确，因此在setCellValue中处理空格
        TreeNodeCellType.prototype.getAutoFitHeight = function(value, text, cellStyle, zoomFactor, context){
            if (!defaultHeight) {
                defaultHeight = context.sheet.getCell(context.row, -1).height();
            }
            const node = me.tree.items[context.row];
            const nodeIndent = node ? (node.depth() + 1) * indent +  node.depth() * levelIndent + imgWidth + 5 : 0;
            const cellWidth = context.sheet.getCell(-1, context.col).width();
            const textLength = this.getAutoFitWidth(...arguments);
            const tempNum = textLength / (cellWidth - nodeIndent);
            const lineNum = tempNum % 1 > 0.92 ? Math.ceil(tempNum + 1) : Math.ceil(tempNum); // 不这么处理的话有些行高算出来不对
            //const lineNum = Math.ceil(textLength / (cellWidth - nodeIndent));
            return lineNum * defaultHeight;
        };
        TreeNodeCellType.prototype.paint = function (ctx, value, x, y, w, h, style, options) {
            if(style.backColor == undefined) style.backColor = "white"  
            if (style.backColor) {
                ctx.save();
                ctx.fillStyle = style.backColor;
                ctx.fillRect(x, y, w, h);
                ctx.restore();
            } else {
                ctx.clearRect(x, y, w, h);
            }
            let drawLine = function (canvas, x1, y1, x2, y2, color) {
                ctx.save();
                ctx.translate(0.5, 0.5);
                ctx.beginPath();
                ctx.moveTo(x1, y1);
                ctx.lineTo(x2, y2);
                ctx.strokeStyle = color;
                ctx.stroke();
                ctx.restore();
            };
            let drawExpandBox = function (ctx, x, y, w, h, centerX, centerY, expanded) {
                let rect = {}, h1, h2, offset = 1;
                rect.top = centerY - halfBoxLength;
                rect.bottom = centerY + halfBoxLength;
                rect.left = centerX - halfBoxLength;
                rect.right = centerX + halfBoxLength;

                if (rect.left < x + w) {
                    rect.right = Math.min(rect.right, x + w);

                    ctx.save();
                    ctx.translate(0.5, 0.5);
                    ctx.strokeStyle = 'black';
                    ctx.beginPath();
                    ctx.moveTo(rect.left, rect.top);
                    ctx.lineTo(rect.left, rect.bottom);
                    ctx.lineTo(rect.right, rect.bottom);
                    ctx.lineTo(rect.right, rect.top);
                    ctx.lineTo(rect.left, rect.top);
                    ctx.stroke();
                    ctx.fillStyle = 'white';
                    ctx.fill();
                    ctx.restore();

                    // Draw Horizontal Line
                    h1 = centerX - halfExpandLength;
                    h2 = Math.min(centerX + halfExpandLength, x + w);
                    if (h2 > h1) {
                        drawLine(ctx, h1, centerY, h2, centerY, 'black');
                    }
                    // Draw Vertical Line
                    if (!expanded && (centerX < x + w)) {
                        drawLine(ctx, centerX, centerY - halfExpandLength, centerX, centerY + halfExpandLength, 'black');
                    }
                }

            }
            let node = tree.items[options.row];
            let showTreeLine = true;
            if (!node) { return; }

            let centerX = Math.floor(x) + node.depth() * indent + node.depth() * levelIndent + indent / 2;
            let x1 = centerX + indent / 2;
            let centerY = Math.floor((y + (y + h)) / 2);
            let y1;
            // Draw Sibling Line
            const lineColor = '#ababab';
            if (showTreeLine) {
                // Draw Horizontal Line
                if (centerX < x + w) {
                    drawLine(ctx, centerX, centerY, Math.min(x1, x + w), centerY, lineColor);
                    let img;
                    if(node.data.projType === projectType.folder){
                        img = document.getElementById('folder_open_pic');
                        imgWidth = 15;
                    }
                    else if(node.data.projType === projectType.project){
                        img = document.getElementById('proj_pic');
                        imgWidth = 18;
                    }
                    else if(node.data.projType === projectType.engineering){
                        img = document.getElementById('eng_pic');
                        imgWidth = 14;
                    }
                    else if(node.data.projType === projectType.tender){
                        //如果单位工程不是实时计算结果，则显示刷新标记
                        img = node.data.changeMark && node.data.changeMark!=""? document.getElementById('refresh_pic'):document.getElementById('tender_pic');
                        imgWidth = 14;
                    }
                    ctx.drawImage(img, centerX+indent/2+3, centerY - 7, imgWidth,imgHeight);
                }
                // Draw Vertical Line
                if (centerX < x + w) {
                    y1 = node.isLast() ? centerY : y + h;
                    if (node.isFirst() && !node.parent.parent) {
                        drawLine(ctx, centerX, centerY, centerX, y1, lineColor);
                    } else {
                        drawLine(ctx, centerX, y, centerX, y1, lineColor);
                    }
                }
            }
            // Draw Expand Box
            if (node.children.length > 0) {
                drawExpandBox(ctx, x, y, w, h, centerX, centerY, node.expanded);
            }
            // Draw Parent Line
            if (showTreeLine) {
                var parent = node.parent, parentCenterX = centerX - indent - levelIndent;
                while (parent.parent) {
                    if (!parent.isLast()) {
                        if (parentCenterX < x + w) {
                            drawLine(ctx, parentCenterX, y, parentCenterX, y + h, lineColor);
                        }
                    }
                    parent = parent.parent;
                    parentCenterX -= (indent + levelIndent);
                }
            };
            //分享标记在开头
            if (node.data.shareInfo && node.data.shareInfo.length > 0) {
                let nowY = Math.floor((y + (y + h)) / 2);
                ctx.drawImage(shareImg, x + 3, nowY - 7, shareImgWidth,shareImgHeight);
            }
            // Draw Text
            x = x + (node.depth() + 1) * indent +  node.depth() * levelIndent + imgWidth + 3;
            w = w - (node.depth() + 1) * indent - node.depth() * levelIndent - imgWidth - 3;
            GC.Spread.Sheets.CellTypes.Text.prototype.paint.apply(this, arguments);
        };
        TreeNodeCellType.prototype.getHitInfo = function (x, y, cellStyle, cellRect, context) {
            let info = {x: x, y: y, row: context.row, col: context.col, cellStyle: cellStyle, cellRect: cellRect, sheetArea: context.sheetArea};
            let node = tree.items[info.row];
            if (node && node.data.projType === projectType.tender) {
                info.isReservedLocation = true;
            }
            return info;
        };
        TreeNodeCellType.prototype.processMouseDown = function (hitinfo) {
            let offset = -1;
            let node = tree.items[hitinfo.row];
            let centerX = hitinfo.cellRect.x + offset + node.depth() * indent + node.depth() * levelIndent + indent / 2;
            let centerY = (hitinfo.cellRect.y + offset + (hitinfo.cellRect.y + offset + hitinfo.cellRect.height)) / 2;
            if(hitinfo.sheet.name() === "projectSheet"){//只有项目管理界面才执行
                if(node.data.projType === projectType.tender){
                    let thisClick = Date.now(),
                        open = false;
                    if (this.preNode === node && this.preClick && thisClick - this.preClick <= 300) {
                        open = true;
                        let timeoutTime = 200;
                        if($('.slide-sidebar').hasClass('open')){
                            timeoutTime = 500;
                        }
                        projTreeObj.openTender(node.data.ID, node.parent, timeoutTime);
                    }
                    this.preClick = open ? null : thisClick;
                    this.preNode = open ? null : node;
                }
                if (!node || node.children.length === 0) {
                    return;
                }
            }
            //统一改成方框外1像素内都有效
            if (hitinfo.x >= centerX - halfBoxLength - 2 && hitinfo.x <= centerX + halfBoxLength + 2 &&
                hitinfo.y >= centerY - halfBoxLength - 2 && hitinfo.y <= centerY + halfBoxLength + 2) {
                node.setExpanded(!node.expanded);
                TREE_SHEET_HELPER.massOperationSheet(hitinfo.sheet, function () {
                    let iCount = node.posterityCount(), i, child;
                    for (i = 0; i < iCount; i++) {
                        child = tree.items[hitinfo.row + i + 1];
                        hitinfo.sheet.setRowVisible(hitinfo.row + i + 1, child.visible, hitinfo.sheetArea);
                    }
                    hitinfo.sheet.invalidateLayout();
                });
                hitinfo.sheet.repaint();
            }
        };
        TreeNodeCellType.prototype.processMouseEnter = function (hitinfo) {
            let text = hitinfo.sheet.getText(hitinfo.row, hitinfo.col);
            let value = hitinfo.sheet.getValue(hitinfo.row, hitinfo.col);
            let acStyle = hitinfo.sheet.getActualStyle(hitinfo.row, hitinfo.col),
                zoom = hitinfo.sheet.zoom();
            let node = me.tree.items[hitinfo.row];
            let nodeIndent = node ? (node.depth() + 1) * indent +  node.depth() * levelIndent + imgWidth + 3 : 0;
            let textLength = this.getAutoFitWidth(value, text, acStyle, zoom, {sheet: hitinfo.sheet, row: hitinfo.row, col: hitinfo.col, sheetArea: GC.Spread.Sheets.SheetArea.viewport});
            let cellWidth = hitinfo.sheet.getCell(-1, hitinfo.col).width();
            if(textLength > cellWidth - nodeIndent){
                TREE_SHEET_HELPER.showTipsDiv(text,{pos: {}},hitinfo);
            }
        };
        TreeNodeCellType.prototype.processMouseLeave = function (hitinfo) {
            TREE_SHEET_HELPER.tipDiv = 'hide';
            if (TREE_SHEET_HELPER._toolTipElement) {
                $(TREE_SHEET_HELPER._toolTipElement).hide();
                TREE_SHEET_HELPER._toolTipElement = null;
            };
            TREE_SHEET_HELPER.tipDivCheck();//延时检查：当tips正在show的时候，就调用了hide方法，会导致tips一直存在，所以设置一个超时处理
        }
        return new TreeNodeCellType();
    },
    setCellValue: function (cell, node,sheet,setting) {
        //const sheet = this.workBook.getActiveSheet();
        if(!setting) setting = this.setting;
        const {row, col} = cell;
        let dataCode = setting.header[col]['dataCode'];
        let value = '';
        if (dataCode === 'name') {
             // 在单元格设置为自动行高后，单元格的内容有空格时，spreadjs会将空格认为是换行，因此需要处理空格
            value = node.data.name && node.data.name.replace(new RegExp(' ', 'g'), '\t') || '';
        }
        else if(dataCode === 'unitPriceFile'){
            if(node.data.projType === projectType.tender){
                value = node.data.property && node.data.property.unitPriceFile && node.data.property.unitPriceFile.name ? node.data.property.unitPriceFile.name : '';
            }
        }
        else if(dataCode === 'feeRateFile'){
            if(node.data.projType === projectType.tender){
                value = node.data.property && node.data.property.feeFile && node.data.property.feeFile.name ? node.data.property.feeFile.name : '';
            }
        }
        else if(dataCode === 'createDateTime'){
            value = node.data.createDateTime ? new Date(node.data.createDateTime).Format('yyyy-MM-dd') : '';
        }
        else {
            value = isDef(node.data[dataCode]) ? node.data[dataCode] : '';
        }
        sheet.setValue(row, col, value);
    },
    setFileSelectButton:function (row,col,node,sheet,setting) {
        if(!setting) setting = this.setting;
        let dataCode = setting.header[col]['dataCode'];
        if(node.data.projType == "Tender" && (dataCode=="feeRateFile" || dataCode == "unitPriceFile")){
            sheet.setCellType(row, col,sheetCommonObj.getCusButtonCellType(projTreeObj.cusButtonClick,false),GC.Spread.Sheets.SheetArea.viewport);
        }
    },
    showTreeData: function (nodes, setting,sheet) {
        let headers = setting.header;
        let me = this;
        let tree = nodes.length>0?nodes[0].tree:me.tree;//sheet.name() == "copyToSheet"?me.copyTree:me.tree;
        let fuc = function(){
            sheet.setRowCount(0);
            sheet.setRowCount(nodes.length);
            let treeNodeCell = me.getTreeNodeCell(tree);
            sheet.getRange(-1, 0, -1, 1).cellType(treeNodeCell);
            const rows = [];
            for(let i = 0; i < nodes.length; i++){
                rows.push(i);
                for(let j = 0; j < headers.length; j++){
                    sheet.getRange(-1, j, -1, 1).hAlign(GC.Spread.Sheets.HorizontalAlign[headers[j]['hAlign']]);
                    sheet.getRange(-1, j, -1, 1).vAlign(GC.Spread.Sheets.VerticalAlign[headers[j]['vAlign']]);
                    if(headers[j].cellType == "checkBox" && nodes[i].data.canSelect === true){
                        sheet.setCellType(i, j,new GC.Spread.Sheets.CellTypes.CheckBox(),GC.Spread.Sheets.SheetArea.viewport);
                        sheet.getCell(i, j).hAlign(GC.Spread.Sheets.HorizontalAlign.center);
                    }
                    me.setCellValue({row: i, col: j}, nodes[i],sheet,setting);
                    me.setFileSelectButton(i,j,nodes[i],sheet,setting);
                }
                sheet.getCell(i, 1,GC.Spread.Sheets.SheetArea.viewport).locked(true);
                if (typeof nodes[i].visible !== 'undefined') {
                    sheet.setRowVisible(nodes[i].serialNo(), nodes[i].visible);
                }
            }
            sheetCommonObj.setRowsAutoFit(sheet, rows, 0, true);
        };
        me.renderSheetFuc(sheet, fuc);
    },
    refreshNodeData: function (nodes) {
        let me = this;
        let sheet = me.workBook.getActiveSheet();
        let header = me.setting.header;
        me.renderSheetFuc(sheet, function () {

            if(_.isArray(nodes)){
                for(let t of nodes){
                    setSheetCellData(t,sheet);
                }
            }else {
                setSheetCellData(nodes,sheet);
            }
        });
        function setSheetCellData(n,sheet) {
            let rIdx = me.tree.items.indexOf(n);
            for(let i = 0; i < header.length; i++){
                me.setCellValue({row: rIdx, col: i}, n,sheet);
                me.setFileSelectButton(rIdx,i,n,sheet)
            }
        }

    },
    sumEngineeringCost:function(){
        let projectNodes = _.filter(projTreeObj.tree.items,function (item) {
            return item.data.projType == projectType.project;
        })
        for(let p of projectNodes){
            this.calEngineeringCost(p);
        }
    },
    calEngineeringCost:function (node) {
        let projectNode = null;//建设项目节点
        let refreshNodes = [];
        if(node.data.projType == projectType.folder){//如果是文件夹时不用计算
            return;
        }
        if(node.data.projType == projectType.project){
            projectNode = node;
        }
        if(node.data.projType == projectType.engineering){
            projectNode = node.parent;
        }
        if(node.data.projType == projectType.tender){
            projectNode = node.parent&&node.parent.parent?node.parent.parent:null;
        }
        if(projectNode){
            calNode(projectNode);
        }
        let children = projectNode.children;
        refreshNodes.push(projectNode);
        return  refreshNodes.concat(children);
        function calNode(node) {
            let tem_sum = 0;
            if(node.data.projType == projectType.tender){
                return;
            }
            for(let t of node.children){
                calNode(t);
                let temP = scMathUtil.roundForObj(t.data.engineeringCost,2);
                tem_sum = scMathUtil.roundForObj(temP+tem_sum,2);
            }
            node.data.engineeringCost =  scMathUtil.roundToString(tem_sum,2);
        }

    },
    initFileChangePage:async function (from) {
        let title = from == "unitPriceFile" ?"批量替换单价文件":"批量替换费率文件";
        $("#mr_title").text(title);
        this.initHtmlByFromRadio();
        let result = from == "unitPriceFile"?await this.setUnitFileChangeFileData():await this.setFeeRateChangeFileData();
        this.changeInfo = result;
        this.loadFileOptions(this.changeInfo,from);

    },
    setFeeRateChangeFileData:async function(){
        //userID
        let node = projTreeObj.tree.selected;
        let data={"user_id":userID, "projectID":node.data.ID, "rootProjectID":node.data.property.rootProjectID};
        let result = await ajaxPost("/feeRates/getChangeInfo",data);
        this.getFileListWithPath(result.others);
        return result;

    },
    setUnitFileChangeFileData:async function(){
        let node = projTreeObj.tree.selected;
        let data ={"project_id":node.data.ID,"rootProjectID":node.data.property.rootProjectID};
        let result = await ajaxPost("/glj/get-project-info",data);
        this.getFileListWithPath(result.other);
        //数据结构不一样，这里做一下转换
        let t_result = {
            currentProject:{
                ID:node.data.ID,
                currentOptions:result.self,
            },
            others:result.other
        }
        return t_result;
    },

    getFileListWithPath:function (list) {
        for(let n of list){
            let node = projTreeObj.tree.findNode(n.ID);
            if(node) {
                n.name = getPathName(node);
            }
            n.serialNo = node && node.serialNo() || 1;
        }
        // 按照正确的树结构排序
        list.sort((a, b) => a.serialNo - b.serialNo);

        function getPathName(node) {
            if(node.parent && node.parent.data){
                return getPathName(node.parent)+"\\"+node.data.name
            }else {
                return node.data?node.data.name:"";
            }
        }

    },
    loadFileOptions:function (data,from) {
        let idField = "ID",optionField ="optionList";
        if(from == "unitPriceFile"){
            idField = 'id';
            optionField = 'unitPriceList'
        }
        $('#currentOptions').empty();
        for(let c of data.currentProject.currentOptions){
            var option =  $("<option>").val(c[idField]).text(c.name);
            $('#currentOptions').append(option);
        }
        $('#otherProject').empty();
        for(let p of data.others){
            var option =  $("<option>").val(p.ID).text(p.name);
            $('#otherProject').append(option);
        }
        $('#otherFileOptions').empty();
        if(data.others.length>0){
            for(let f of data.others[0][optionField]){
                var option =  $("<option>").val(f[idField]).text(f.name);
                $('#otherFileOptions').append(option);
            }
        }
    },
    initHtmlByFromRadio:function () {
        var radioV= $("input[name='select_from']:checked").val();
        if(radioV == "0"){
            $("#fromProject").show();
            $("#fromOther").hide();
        } else {
            $("#fromProject").hide();
            $("#fromOther").show();
        }
    },
    initCopyToSpread:function () {
        let me = this;
        me.copyToWorkBook =  projTreeObj.buildSheet(me.copyToWorkBook,'copyToSpread',me.copyToSetting);
        let sheet = me.copyToWorkBook.getActiveSheet();
        sheet.options.isProtected = true;
        sheet.name('copyToSheet');
        let datas = [];
        for(let i of me.tree.items){
            datas.push(i.data);
        }
        me.copyTree  = pmTree.createNew(projTreeObj.setting, datas);
        initNodesVisibility(me.copyTree.items, false);
        me.showTreeData(me.copyTree.items, me.copyToSetting, sheet);
        me.copySelected = null;
        let initSel = sheet.getSelections()[0] ? sheet.getSelections()[0] : {row: 0, rowCount: 1};
        projTreeObj.initSelection(initSel,null,sheet);
    },
    initReplaceSpread:function () {
        let me = this;
        me.replaceWorkBook =  projTreeObj.buildSheet(me.replaceWorkBook,'replaceSpread',me.replaceSetting);
        let sheet = me.replaceWorkBook.getActiveSheet();
        sheet.options.isProtected = true;
        sheet.name('replaceSheet');
        let datas = [];
        for(let i of me.tree.items){//要挑出同个建设项目的节点
            if(me.isReplaceNode(i) == true){
                let tem = _.cloneDeep(i.data);
                if(tem.projType == "Tender") tem.canSelect = true;
                if(i == me.tree.selected) tem.selected = 1;
                datas.push(tem);
            }
        }
        me.replaceTree  = pmTree.createNew(projTreeObj.setting, datas);
        me.showTreeData(me.replaceTree.items, me.replaceSetting, sheet);
    },
    isReplaceNode:function (node) {//只加载本建设项目的节点
        let isReplaceNode = false;
        let selected = this.tree.selected;
        let rootProjectID = selected.data.property.rootProjectID;
        let rootNode = this.tree.findNode(rootProjectID)
        if(rootNode){
            let IDMap = this.getAllParentNodeID(selected);
            isReplaceNode = IDMap[node.data.ID]!==undefined ||node.data.ID == rootProjectID ||  node.data.ParentID == rootProjectID || (node.data.property &&node.data.property.rootProjectID == rootProjectID);
        }
        return isReplaceNode
    },
    getAllParentNodeID:function (node) {
       let IDMap = {};
       getPID(node,IDMap);
       return IDMap;
        function getPID(node,map) {
            if(node.parent && node.data.ParentID != -1){
                map[node.data.ParentID] = true;
                getPID(node.parent,map);
            }
        }
    },
    onReplaceNodeCheck:function(sender,args){
        let checkboxValue = args.sheet.getCell(args.row, args.col).value();
        let newval = checkboxValue?0:1;
        let node = projTreeObj.replaceTree.items[args.row];
        if(node.data.ID  === projTreeObj.tree.selected.data.ID) return; //如果是项目管理界面选中的节点，不给取消
        projTreeObj.setReplaceSelection(node,newval,args.row,args.col,args.sheet);
    },
    setReplaceSelection:function (node,value,row,col,sheet) {
        sheet.getCell(row, col).value(value);
        node.data.selected = value;
    },
    selectSameTypeProject:function (value) {
        let node = this.tree.selected;
        let engineering_id = node.data.property.engineering_id;
        for(let i=0 ;i< this.replaceTree.items.length ; i++){
            let tnode = this.replaceTree.items[i];
            if(tnode.data.ID == node.data.ID) continue;
            if(tnode && tnode.data.property && tnode.data.property.engineering_id == engineering_id){
                this.setReplaceSelection(tnode,value,i,1,this.replaceWorkBook.getActiveSheet());
            }
        }
    },
    confirmFileChange :async function(){
        let selectProjects =[],fileID=null,from = $("#mr_from").val(),name='',oldFileIDs = [],validate = true;
        for(let i of this.replaceTree.items) {
            if (i.data.selected === 1){
                selectProjects.push({
                    projectID: i.data.ID,
                    rootProjectID: i.data['property']['rootProjectID']
                });
                let fileField = from == "feeRateFile" ? "feeFile" : "unitPriceFile";
                oldFileIDs.push(i.data['property'][fileField]['id']);
            }
        }
        if(selectProjects.length > 0){
            let type = parseInt($("input[name='select_from']:checked").val());//0 从当前建设项目，1从其它建设项目中复制
            if(type == 0){
                fileID = $("#currentOptions").val();
                name = $("#currentOptions").find("option:selected").text()
            }else {
                fileID = $("#otherFileOptions").val();
                name = $("#otherFileOptions").find("option:selected").text();
            }
            if(fileID == null || fileID == undefined|| fileID ==""){
                alert("请选择替换文件")
            }
            //从其它项目复制才要做重名检查
            if(type == 1) validate = await projTreeObj.fileNameChecking({ name:name,rootProjectID:selectProjects[0].rootProjectID},from);
            if (validate == true){
                $('#m_replace_file').modal('hide');
                await projTreeObj.postChangeFile({projects:selectProjects,fileID:fileID,name:name,type:type,from:from},oldFileIDs);
            }else {
                alert(`当前的建设项目中已经有相同名字的${from == "feeRateFile"?"费率":"单价"}文件！`);
            }

        }
    },
    fileNameChecking:async function(data,from){
        let url =from == "feeRateFile" ? "/feeRates/checkFeeRateName" : "/glj/checkUnitFileName";
        let reuslt = await ajaxPost(url,data);
        return reuslt == false;//result 为true 则有重名的文件
    },

    postChangeFile:async function(data,oldFileIDs){
        data.user_id = userID;
        $.bootstrapLoading.start();
        let result = await ajaxPost("/pm/api/changeFile",data);
        $.bootstrapLoading.end();
        projTreeObj.refreshWhenFileDateChange(data.projects[0].projectID);
        //发送文件改变消息
        data.oldFileIDs = _.uniq(oldFileIDs);
        socket.emit('multiFileChangeNotify', data);
    },

    insert: function (data, parent, next) {
        let preNode = this.tree.items[this.preSelection.row];
        let node = this.tree.addNodeData(data, parent, next);
        this.addRow(node);
        let newSel = this.workBook.getSheet(0).getSelections()[0];
        this.initSelection(newSel,  preNode ? {row:preNode.serialNo(),rowCount:1} : null,this.workBook.getActiveSheet());//这里不能直接用this.preSelection，因为如果插入的记录在preSelection的前面时，之前old选中行已经变了，改不了old行的颜色
        return node;
    },
    addRow: function (node) {
        const me = this;
        const sheet = this.workBook.getActiveSheet();
        me.renderSheetFuc(sheet, function () {
            const items = me.tree.items;
            const rIdx = items.indexOf(node);
            const cIdx = sheet.getActiveColumnIndex();
            sheet.addRows(rIdx, 1);
            //set selection selected
            sheet.setSelection(rIdx, cIdx, 1, 1);
            me.tree.selected = node;
            //父节点收起时添加子节点,子节点添加完后隐藏
            /*if(node.parent && !node.parent.getRootExpandState()){
                sheet.setRowVisible(rIdx, false);
            }*/
            // 添加节点自动展开相关的隐藏节点
            me.tree.setNodesExpanded(node.getCollapseParents(), sheet);
            sheet.getCell(rIdx, 0).cellType(me.getTreeNodeCell(me.tree));
            me.refreshNodeData(node);
        });
    },
    remove: function (sheet, rIdx, count) {
        let me = this;
        me.renderSheetFuc(sheet, function () {
            sheet.deleteRows(rIdx, count);
            sheet.setRowCount(me.tree.items.length);
            me.initSelection({row: sheet.getActiveRowIndex(), rowCount: 1},null,sheet);
        });
    },
    move: function (orgRow, newRow) {
        this.workBook.getActiveSheet().deleteRows(orgRow, 1);
        this.addRow(this.tree.items[newRow]);
    },
    moveTo : function(select,target,parent,next,oldProject,action){
        let me = this;
        let fromRow = select.serialNo();
        let rCout = select.posterityCount() + 1;//删除的行数
        let sheet = me.workBook.getActiveSheet();
        let refreshNodes = [];
        me.tree.removeNode(select);//删除旧节点
        let newNode  = addNewNodes(select, parent, next);
        if(oldProject){
            refreshNodes = refreshNodes.concat(me.calEngineeringCost(oldProject));
            refreshNodes = refreshNodes.concat(me.calEngineeringCost(parent));
        }
        me.renderSheetFuc(sheet, function () {
            sheet.deleteRows(fromRow, rCout);
            sheet.addRows(newNode.serialNo(),rCout);
            let oldSelection = sheet.getSelections()[0];
            me.initSelection({row: newNode.serialNo(), rowCount: oldSelection.rowCount}, oldSelection,sheet);
            sheet.setSelection(newNode.serialNo(),oldSelection.col,oldSelection.rowCount,oldSelection.colCount);
            const newNodes = [newNode];
            const children = newNode.getAllChildren();
            newNodes.push(...children);
            for(let node of newNodes){
                const row = node.serialNo();
                sheet.getCell(row, 0).cellType(me.getTreeNodeCell(me.tree));
                const visible = node.visible;
                sheet.setRowVisible(row, visible);
            }
            refreshNodes = refreshNodes.concat(newNodes);
            me.refreshNodeData(refreshNodes);
        });
        if (action === 'downLevel') {
            me.tree.setNodesExpanded([parent], sheet);
        }

        function addNewNodes(node,parent,next) {
            const nodeState = {};
            if (typeof node.expanded !== 'undefined') {
                nodeState.expanded = node.expanded;
            }
            if (typeof node.visible !== 'undefined') {
                nodeState.visible = node.visible;
            }
            let newNode = me.tree.addNodeData(node.data, parent, next, nodeState);
            for(let c of node.children){
                addNewNodes(c,newNode,null);
            }
            return newNode;
        }

    },
    refreshProjectData:function (projectID) {
        //projTreeObj.tree.findNode(4578)
        //获取当前节点的建设项目ID
        let project = projectID?projTreeObj.tree.findNode(projectID):projTreeObj.tree.selected;
        while (project.data.projType !== projectType.project && project.parent){
            project = project.parent;
        }
        if(project && project.data.ID){
            $.bootstrapLoading.start();
            CommonAjax.post('/pm/api/getSummaryInfo', {user_id: userID, projectIDs: [project.data.ID]}, function (summaryInfo) {//11-06 zhang 这个接口返回值增加了项目需重新计算标记，项目图标刷新
                refreshProjSummary(project, summaryInfo);
                $.bootstrapLoading.end();
            }, function () {
                $.bootstrapLoading.start();
            });
        }
    },
    refreshProjectIcon:function (projectID) {
        let node = projTreeObj.tree.findNode(projectID);
        if(node && node.data.changeMark && node.data.changeMark!="") this.refreshProjectData(projectID);
    },
    refreshWhenFileDateChange:function(projectID){//当单价文件、费率文件被修改后，刷新页面，共用的项目提示刷新图标
        //在一次的修改中，同一个建设下，单价文件、费率文件才有共用的情况，而refreshProjectData是传入单位工程ID,刷新整个建设项目，所以，只要传入修改的单位工程ID，刷新建设项目即可
        this.refreshProjectData(projectID);
    },
    exportProject:async function(projectID,projectName){
        $.bootstrapLoading.progressStart();
        let spString = "|----|";
        try {
            let sumString = "";
            $("#progress_modal_bar").css('width','5%');
            let result = await getProjectInfo({projectID:projectID,type:"main",user_id: userID});
            $("#progress_modal_bar").css('width','10%');
            let result_arr = result.split(spString);
            sumString = result_arr[0];
            if(result_arr.length == 2){
                let tenders = JSON.parse(result_arr[1]);
                let each = 100;
                let width = 10;
                if(tenders.length > 0) each = 90/tenders.length;
                for(let t of tenders){
                    let tenderString = await getProjectInfo({projectID:t,rootProjectID:projectID,type:"sub",user_id: userID});
                    width += each;
                    $("#progress_modal_bar").css('width',width+'%');
                    await  setTimeoutSync(null,500);//设置间隔
                    sumString = sumString + spString +tenderString;
                }

            }
            //  console.log(JSON.parse(sumString));

            saveProjectFile(sumString);

        }catch (e){
            alert("导出失败！请查看log.");
            console.log(e)
        }finally {
            await  setTimeoutSync(null,500);//设置间隔
            $.bootstrapLoading.progressEnd();
        }


        async function getProjectInfo(data) {
            let result = await ajaxPost("/pm/api/exportProject",data);
            return result;
        }

        function saveProjectFile(data) {
            let blob = new Blob([data], {type: 'text/plain;charset=utf-8'});
            saveAs(blob, projectName+'.ybp');
        }
    },
    getImportProjectDate:function () {//导入建设项目时，需要在现有的树节点中插入新的节点，这里是取插入所需的项目数据
        let selectNode = projTreeObj.tree.selected;
        let parent = null,next=null;
        let updateData = {};
        if(selectNode && selectNode.data.projType == projectType.folder){
            parent = selectNode;
            next = selectNode.firstChild();
        }else if(selectNode){
            let projectNode = null;
            if(selectNode.data.projType == projectType.project) projectNode = selectNode;
            if(selectNode.data.projType == projectType.engineering) projectNode = selectNode.parent;
            if(selectNode.data.projType == projectType.tender)projectNode = selectNode.parent.parent;
            parent = projectNode.parent;
            next = projectNode.nextSibling;
            updateData["update"] = {query:{ID:projectNode.id()}}
        } else if (!selectNode) { // 默认在第一位
            parent = selectNode ? selectNode.parent : projTreeObj.tree._root;
            next = selectNode ? selectNode.nextSibling : projTreeObj.tree.firstNode();
        }
        updateData["self"] ={ParentID:parent.id(),NextSiblingID:next?next.id():-1};
        return updateData;
    },
    //创建建设项目的时候，根据选中位置获取所要创建建设项目的父ID、上兄弟节点ID、后兄弟节点ID
    getRelProjectID: function (selected) {
        let parent, pre, next;
        if(!selected || selected.data.projType === projectType.project){
            parent = selected ? selected.parent : projTreeObj.tree._root;
            pre = selected;
            next = selected ? selected.nextSibling : projTreeObj.tree.firstNode();
        } else if(selected.data.projType === projectType.folder){
            parent = selected ? selected : projTreeObj.tree._root;
            pre = selected ? selected.lastChild() : projTreeObj.tree.firstNode();
            next = null;
        } else if(selected.data.projType === projectType.engineering || selected.data.projType === projectType.tender){
            let selectedProj = selected.parent.data.projType === projectType.project ? selected.parent : selected.parent.parent;
            parent = selectedProj ? selectedProj.parent : projTreeObj.tree._root;
            pre = selectedProj;
            next = selectedProj ? selectedProj.nextSibling : projTreeObj.tree.firstNode();
        }
        return {parentProjectID: parent && parent.data ? parent.data.ID : -1,
                preProjectID: pre && pre.data ? pre.data.ID : -1,
                nextProjectID: next && next.data ? next.data.ID : -1};
    },
    getUploadToken:async function () {
        let result =await ajaxGet("/pm/api/getUploadToken");
        $("#confirm-import").show();
        projTreeObj.uptoken=result.uptoken;
    },
    // 树数据发生变化，触发推送
    emitTreeChange: function () {
        const compilationID = compilationData._id;
        // 获取当前树节点展开状态和焦点行
        const isActive = $('#tab_pm_all').hasClass('active');
        const expandState = isActive ? this.tree.getExpState(this.tree.items) : null;
        const selection = isActive && this.tree.selected ? { row: this.tree.selected.serialNo(), rowCount: 1 } : null;
        socket.emit('pmTreeChange', { userID, compilationID, expandState, selection });
    },
    initTree: function (refresh = false, callback, expandCallback) {
        if(gcTreeObj.workBook){
            gcTreeObj.workBook.destroy();
            gcTreeObj.workBook = null;
        }
        gcTreeObj.tree = null;
        init(refresh, callback, expandCallback);
    },
    handleNotifyClick: function(expandState, selection) {
        $('#empty-modal').modal('hide');
        $('#notify').hide();
        const callback = () => {
            const sheet = this.workBook.getSheet(0);
            if (selection && this.tree.items[selection.row]) {
                this.initSelection(selection, { row : 0, rowCount: 1 }, sheet);
                const col = sheet.getActiveColumnIndex();
                sheet.setSelection(selection.row, col, 1, 1);
            }
        };
        const expandCallback = () => {
            if (expandState) {
                this.tree.setExpandedByState(this.tree.items, expandState);
            }
        }
        this.initTree(true, callback, expandCallback);
    },
    importExampleProjects:async function(isChongqing=false){
        if (STATE.importing) {
            return;
        }
        let textBody = '正在导入例题，请稍候……'
        let url = 'importExampleProject';
        STATE.importing = true;
        if(isChongqing){
            $('#welcomePage').modal('hide');
            textBody = "正在导入测评项目，请稍候……";
            url = 'importChongqingProject';
        } 
        try {
            let key = uuid.v1();
            $.bootstrapLoading.progressStart("欢迎使用大司空云计价",true);
            $("#progress_modal_body").text(textBody);
            let result = await ajaxPost(`/pm/api/${url}`,{user_id: userID,key:key});
            importProcessChecking(key, null, (projectData) => handleProjectAfterChecking(projectData));
        }catch (error){
            alert(error);
        }finally {
            STATE.importing = false;
        }
    }
};
// 新建项目必填项提示框设置“ 比如：注：为响应重庆地区指标采集标准数据要求，以上工程信息及特征必填项为必填项，请正确填写。”
function setupRequiredWarn(compilation) {
    let map = {
            '重庆定额(2018)': '<i class="fa fa-warning text-warning"></i> 注：为响应重庆地区指标采集标准数据要求，以上工程信息及特征为必填项，请正确填写。'
        },
        $warns = [
            $('#project-required-warn'),
            $('#tender-required-warn')
        ];
    for (let $warn of $warns) {
        map[compilation.name] ? $warn.html(map[compilation.name]) : $warn.html('');
    }
}

$(document).ready(function() {
    // 分享给的一些事件监听
    SHARE_TO.handleEventListener();

    // 单位工程超限提示后，弹出客服列表
    $('#hintBox_form').on('hide.bs.modal', function () {
        const text = $('#hintBox_caption').text();
        if (text === '您创建的项目个数超限，请联系我们的客服人员，或者导出建设项目保存到本地备份，删除云上数据。') {
            $('#customerService').click();
        } 
    });
    setupRequiredWarn(compilationData);
    $('#add-project-dialog').find('.modal-body').append();
    //绑定项目管理的升降级、上下移按钮事件
    projTreeObj.loadBtn();
    $('#sideTab').find('li').click(function () {
       //消除tooltip
        $('[data-toggle="tooltip"]').tooltip('hide');
    });
    //列宽随着屏幕改变
    $(window).resize(function () {
        sheetCommonObj.setColumnWidthByRate(getWorkBookWidth(), gcTreeObj.workBook, gcTreeObj.setting.header);

    });

    projTreeObj.initTree();
    $('#tab_pm_all').on('show.bs.tab', () => projTreeObj.initTree(true));

    //单价、费率文件删除确认
    $('#fileDelConfirm').click(function () {
        if(fileDelObj && fileDelObj.id){
            let updateObj = Object.create(null);
            updateObj.updateType = 'delete';
            updateObj.updateData = Object.create(null);
            if(fileDelObj.fileType === fileType.unitPriceFile){
                updateObj.updateData.id = fileDelObj.id;
            }
            else if(fileDelObj.fileType === fileType.feeRateFile){
                updateObj.updateData.ID = fileDelObj.id;
            }
            updateObj.fileType = fileDelObj.fileType;
            a_updateFiles([updateObj], function () {
                fileDelObj = null;
                $('#fileDelCancel').click();
                setDataToSideBar();
                //refresh front?
            });
        }
    });

    //绑定新建建设项目、新建单项工程、新建文件夹、重命名Enter键事件
    bindInputs($('#project-name'), $('#engineering-name'), $('#folder-name'), $('#rename-name'));
    //绑定新建窗口显示事件
    bindModalShown($('#add-folder-dialog'), $('#add-project-dialog'), $('#add-engineering-dialog'), $('#add-tender-dialog'));
    //绑定新建建设项目、新建单项工程、新建文件夹、重命名弹窗隐藏事件
    bindModalsHidden($('#add-project-dialog'), $('#add-engineering-dialog'), $('#add-folder-dialog'), $('#rename-dialog'));

    // 新建子菜单有效性刷新
    $('#addMenuBtn').click(function () {
        const menuDisplay = !$('#addMenu').is(':visible');
        if (!menuDisplay) {
            return;
        }
        projTreeObj.refreshAddMenuItems();
    });

    // 新增建设项目操作
    $('#addProjOk').click(function () {
        if (!validRequiredData($('#projInfoStep'))) {
            return;
        }
        if (STATE.addingProject) {
            return;
        }
        STATE.addingProject = true;
        if (needfulInfoData && Array.isArray(needfulInfoData)) {
            updateRequiredData($('#projInfoStep'), needfulInfoData);
        }
        let suc = AddProject();
        if (suc === false) {
            STATE.addingProject = false;
        }
    });
    //新建建设项目-下一步
    $('#add-proj-next').click(function () {
        let name = $('#project-name').val().trim();
        if (!name) {
            setDangerInfo($('#project-name-info'), '请填写建设项目名称');
            return false;
        }
        if (!validProjectName(name)) {
            setDangerInfo($('#project-name-info'), `已存在“${name}”`);
            return false;
        }
        //建设项目基本信息
        showProjInfoStep();
    });
    //新建建设项目-上一步
    $('#add-proj-prev').click(function () {
        setDangerInfo($('#project-name-info'), '', false);
        showProjFirstStep();
    });
    //显示新建建设项目第一步内容
    async function showProjFirstStep() {
        $('#add-project-dialog').find('.modal-title').html('<i class="fa fa-cubes"></i> 新建建设项目');
        $('#projInfoStep').hide();
        $('#addProjOk').hide();
        $('#project-required-warn').hide();
        $('#add-proj-prev').hide();
        $('#projFirstStep').show();
        let requiredData = null;
        if (!infoData) {
            try {
                let fileKind = $('input[name="fileKind"]:checked').val();
                infoData = await ajaxPost('/pm/api/getBasicInfo', {user_id: userID});
                //第一次默认是投标
                needfulInfoData = getNeedfulBasicInfo(infoData, fileKind);
            } catch (err) {
                $('#add-project-dialog').modal('hide');
            }
        }
        requiredData = getRequired([], needfulInfoData);
        if (requiredData.length > 0) {
            $('#add-proj-next').show();
        } else {
            $('#addProjOk').show();
        }
    }
    //显示新建建设项目-建设项目基本信息内容
    async function showProjInfoStep() {
        $('#add-project-dialog').find('.modal-title').html('建设项目基本信息');
        $('#projFirstStep').hide();
        $('#add-proj-next').hide();
        $('#add-proj-prev').show();
        $('#addProjOk').show();
        $('#projInfoStep').show();
        $('#project-required-warn').show();
        showRequiredInfo($('#projInfoStep'), needfulInfoData);
    }
    //新建建设项目-文件类型选择 (影响到基本信息数据)
    $('input[name="fileKind"]').click(function () {
        if (infoData && infoData.length) {
            let fileKind = $(this).val();
            needfulInfoData = getNeedfulBasicInfo(infoData, fileKind);
        }
        let requiredData = getRequired([], needfulInfoData);
        if (requiredData.length > 0) {
            $('#addProjOk').hide();
            $('#add-proj-next').show();
        } else {
            $('#projInfoStep').empty();
            $('#add-proj-next').hide();
            $('#addProjOk').show();
        }
    });

    function bindModalShown(folderDialog, projDialog, engDialog, tenderDialog) {
        folderDialog.on('shown.bs.modal', function () {
            $('#folder-name').focus();
        });
        projDialog.on('show.bs.modal', function () {
            // 内蒙古费用定额，新建建设项目页面隐藏“文件类型：投标、招标”
            const filterCompilationNames = ['内蒙古定额(2017)'];
            if (filterCompilationNames.includes(compilationData.name)) {
                $('#project-dialog-fileKind').hide();
            }
        });
        projDialog.on('shown.bs.modal', function () {
            $('#project-name').focus();
        });
        engDialog.on('shown.bs.modal', function () {
            $('#engineering-name').focus();
        });
        tenderDialog.on('show.bs.modal', function () {
            $('#tender-name').focus();
            const filterCompilationNames = ['内蒙古定额(2017)'];
            if (filterCompilationNames.includes(compilationData.name)) {
                $('#tender-dialog-fileKind').hide();
            }
        });
        tenderDialog.on('shown.bs.modal', function () {
            $('#tender-name').focus();
        });
    }

    //新建建设项目、新建单项工程、新建文件夹、重命名弹窗隐藏事件
    function bindModalsHidden(projDialog, engDialog, folderDialog, renameDialog){
        projDialog.on('hidden.bs.modal', function () {
            setDangerInfo($('#project-name-info'), '', false);
            $('#project-name').val('');
            //文件类型、计税方法恢复默认选项
            $('input[name="fileKind"]:eq(0)').prop('checked', true);
            $('input[name="taxType"]:eq(0)').prop('checked', true);
        });
        projDialog.on('show.bs.modal', function () {
            // 计价规则恢复默认选项
            setValuationSels($('#proj-valuation'), billValuation);
            infoData = null;
            needfulInfoData = null;
            $('#add-proj-prev').hide();
            $('#add-proj-next').hide();
            showProjFirstStep();
        });
        engDialog.on('hidden.bs.modal', function () {
            setDangerInfo($('#engineering-name-info'), '', false);
            $('#engineering-name').val('');
        });
        folderDialog.on('hidden.bs.modal', function () {
            setDangerInfo($('#folder-name-info'), '', false);
            $('#folder-name').val('');
        });
        renameDialog.on('hidden.bs.modal', function () {
            setDangerInfo($('#rename-name-info'), '', false);
            $('#rename-name').val('');
        });
    }

    //绑定新建建设项目、新建单项工程、新建文件夹、重命名回车键功能
    function bindInputs(projInput, engInput, foldInput, renameInput){
        projInput.bind('keypress', function (event) {
            if(event.keyCode === 13){
                $('#add-proj-next').is(':visible')
                    ? $('#add-proj-next').click()
                    : $('#addProjOk').click();
                return false;
            }
        });
        engInput.bind('keypress', function (event) {
            if(event.keyCode === 13){
                $('#add-engineering-confirm').click();
                return false;
            }
        });
        foldInput.bind('keypress', function (event) {
            if(event.keyCode === 13){
                $('#add-folder-confirm').click();
                return false;
            }
        });
        renameInput.bind('keypress', function (event) {
            if(event.keyCode === 13){
                $('#rename-confirm').click();
                return false;
            }
        });
    }
    //单位工程-新建建设项目-选择计税方法
    $('input[name="taxType-tender"]').click(function () {
        curTaxType = parseInt($(this).val());
        getStdCalcProgramFiles();
    });
    // 选择计价方式
    $("input[name='valuation_type']").click(function() {
        let type = $(this).val();
        let targetData = type === 'bill' ? billValuation : rationValuation;
        let html = '';
        for(let i = targetData.length - 1; i >=0; i--){
            let valuation = targetData[i];
            if (valuation === null) {
                continue;
            }
            html += `<option ${i === targetData.length -1 ? 'selected' : ''} value="${valuation.id}">${valuation.name}</option>`;
        }
        $("#valuation").html(html);
        let engineeringList = getEngineeringList();
        let engineeringHtml = getEngineeringHtml(engineeringList);
        $("#tender-engineering").html(engineeringHtml);
        changeEngineering();
    });

    //选择计价规则
    $("#valuation").change(function () {
        curValuation = $(this).val();
        curValuationName = $(this).text();
        let engineeringList = getEngineeringList();
        let engineeringHtml = getEngineeringHtml(engineeringList);
        $("#tender-engineering").html(engineeringHtml);
        $('#valuation-info').hide();
        changeEngineering();
    });

    //选择计税方式
    $("#taxType").change(function () {
        $('#valuation-info').hide();
        getStdCalcProgramFiles();
    });


    // 新增单项工程操作
    $("#add-engineering-confirm").click(function() {
        if (STATE.addingEng) {
            return;
        }
        STATE.addingEng = true;
        let suc = AddEngineering();
        if (suc === false) {
            STATE.addingEng = false;
        }
    });

    //新建单位工程-建设项目提示
    $('#poj-name').keyup(function () {
        let pojName = $('#poj-name').val().trim();
        let nameList = getNameList($('#poj-name-list').children());
        let isExist = hasListName(nameList, pojName);
        if(!isExist){
            if(pojName !== ''){
                console.log(curValuation);
                //新建建设项目，显示计价规则、文件类型、计税方法选项
                $('#newProjectSet').show();
                $('input[name="fileKind-tender"]:eq(0)').prop('checked', true);
                $('input[name="taxType-tender"]:eq(0)').prop('checked', true);
                curTaxType = 1;
                getStdCalcProgramFiles();
                replaceClass($('#poj-name-info'), 'text-danger', 'text-info');
                setDangerInfo($('#poj-name-info'), `新建“${pojName}”`);
            }
            else {
                $('#newProjectSet').hide();//隐藏文件类型、计税方法选项
                $('#poj-name-info').hide();
            }
            //清空单项工程下拉和文件下拉
            setEngOptions(null);
            setFileOptions(null);
        }
        else {
            //触发选项
            let curName = $(this).val().trim();
            function getProjOpt(opts){
                for(let opt of opts){
                    if($(opt).text().trim() === curName){
                        return $(opt);
                    }
                }
                return null;
            }
            let matchOpt = getProjOpt($('#poj-name-list').find('a'));
            if(matchOpt){
                matchOpt.click();
            }
            $('#poj-name-info').hide();
        }
    });

    //新建单位工程-单项工程提示
    $('#eng-name').keyup(function () {
        let engName = $('#eng-name').val().trim();
        let nameList = getNameList($('#eng-name-list').children());
        let isExist = hasListName(nameList, engName);
        if(!isExist && engName !== ''){
            replaceClass($('#eng-name-info'), 'text-danger', 'text-info');
            setDangerInfo($('#eng-name-info'), `新建“${engName}”`);
        }
        else {
            $('#eng-name-info').hide();
        }
    });

    //新建单位工程-单位工程提示
    $('#tender-name').keyup(function () {
        let selected = projTreeObj.tree.selected;
        let pojName = $('#poj-name').val().trim();
        let engName = $('#eng-name').val().trim();
        let tenderName = $('#tender-name').val().trim();
        let isExist = hasTender(selected, pojName, engName, tenderName);
        $('#unit-price').find('option:first-child').text(tenderName);
        $('#tender-fee-rate').find('option:first-child').text(tenderName);
        if(isExist){
            if(tenderName !== '')
                setDangerInfo($('#tender-name-info'), `已存在“${tenderName}”`);
        }
        else {
            $('#tender-name-info').hide();
        }
    });

    //下拉是否含有输入的名字
    function hasListName(nameList, name){
        for(let i = 0, len = nameList.length; i < len; i++){
            if(nameList[i] === name){
                return true;
            }
        }
        return false;
    }

    function getNameList(list){
        let rst = [];
        for(let i = 0, len = list.length; i < len; i++){
            rst.push($(list[i]).text());
        }
        return rst;
    }

    //设置地区选项
    function setRegionOpts (regions) {
        $('#regionDiv').find('select').empty();
        for(let region of regions){
            let $opt = $(`<option value = "${region}">${region}</option>`);
            $('#regionDiv').find('select').append($opt);
        }
    }
    // 新增单位工程弹层改变
    $('#add-tender-dialog').on('show.bs.modal', function() {
        // 恢复计价规则
        setValuationSels($('#valuation'), billValuation);
        //clear info
        curStep = 1; //当前在第几步
        infoData = null; //建设项目基本信息数据
        needfulInfoData = null;
        featureData = null; //工程特征数据
        $('#poj-name-info').hide();
        $('#eng-name-info').hide();
        $('#tender-name-info').hide();
        $('#tender-name').val('');
        $('#valuation-info').hide();
        $('#engineering-info').hide();
        $('#unit-price').find('option:first-child').text('新建单价文件');
        $('#tender-fee-rate').find('option:first-child').text('新建费率文件');
        $('#newProjectSet').hide(); //隐藏文件类型、计税方法选项
        $('input[name="fileKind-tender"]:eq(0)').prop('checked', true);
        $('input[name="taxType-tender"]:eq(0)').prop('checked', true);
        curTaxType = 1;
        //获取建设项目
        let selected = projTreeObj.tree.selected;
        let projs = getProjs(selected);
        setProjOptions(projs, selected);
        //$($("input[name='valuation_type']")[0]).click();
        initEngineering();
        //设置地区选项
        if(regions.length > 0){
            setRegionOpts(regions);
            $('#regionDiv').show();
        }
        //恢复到第一步状态
        if (!$('#firstStep').is(':visible')) {
            showFirstStep();
        }
    });
    //新建单位工程-文件类型选择变换（影响到基本信息数据）
    $('input[name="fileKind-tender"]').click(function () {
        if (infoData && infoData.length) {
            let fileKind = $(this).val();
            needfulInfoData = getNeedfulBasicInfo(infoData, fileKind);
            $('#infoStep').empty(); //清空设置的基本信息必填数据
        }
    });
    //新建单位工程-下一步
    $('#add-tender-next').click(async function() {
        if (curStep === 1) {
            let projName = $("#poj-name").val().trim();
            if(projName === ''){
                replaceClass($('#poj-name-info'), 'text-info', 'text-danger');
                setDangerInfo($('#poj-name-info'), '请填写建设项目名称');
                return false;
            }
            let engName = $("#eng-name").val().trim();
            if(engName === ''){
                replaceClass($('#eng-name-info'), 'text-info', 'text-danger');
                setDangerInfo($('#eng-name-info'), '请填写单项工程名称');
                return false;
            }

            let tenderName = $('#tender-name').val();
            if (tenderName === '') {
                setDangerInfo($('#tender-name-info'), '请填写单位工程名称');
                return false;
            }
            let selected = projTreeObj.tree.selected;
            let isExist = hasTender(selected, projName, engName, tenderName);
            if (isExist) {
                return false;
            }
            showSecondStep();
        } else if (curStep === 2) {
            let valuation = $("#valuation").val();
            if(!valuation || valuation === ''){
                setDangerInfo($('#valuation-info'), '请选择计价规则');
                return false;
            }

            let engineeringName = $("#tender-engineering").val();
            if (!engineeringName || engineeringName === '') {
                setDangerInfo($('#engineering-info'), '请选择工程专业');
                return false;
            }
            let feeName = $('#tender-feeStandard').val();
            if(!feeName || feeName === ''){
                setDangerInfo($('#feeStandard-info'), '请选择费用标准');
                return false;
            }

            let taxType = $("#taxType").val();
            let IDGroup = $("#tender-calcProgram").val();
            if (!IDGroup || IDGroup === '') {
                setDangerInfo($('#calcProgram-info'), '请选择计算程序');
                return false;
            }
            let path = getAddPath();
            let infoRequired = getRequired([], needfulInfoData);
            let featureRequired = getRequired([], featureData);
            if (path === addPath.p_e_t && infoRequired.length > 0) {
                showInfoStep();
            } else if (featureRequired.length > 0) {
                showFeatureStep();
            }
        } else if (curStep === 3) {
            if (!validRequiredData($('#infoStep'))) {
                return;
            }
            showFeatureStep();
        }
        curStep++;
    });
    //新建单位工程-上一步
    $('#add-tender-prev').click(function () {
        if (curStep === 2) {
            showFirstStep();
        } else if (curStep === 3) { //建设项目基本信息或工程特征
            showSecondStep();
        } else if (curStep === 4) { //工程特征
            $('#featureStep').hide();
            $('#add-tender-confirm').hide();
            $('#add-tender-next').show();
            $('#infoStep').show();
        }
        curStep--;
    });
    //显示第一步的内容
    function showFirstStep() {
        $('#add-tender-title').html(`<i class="fa fa-sticky-note-o"></i>新建单位工程`);
        $('#featureStep').hide();
        $('#infoStep').hide();
        $('#secondStep').hide();
        $('#tender-required-warn').hide();
        $('#firstStep').show();
        $('#add-tender-prev').hide();
        $('#add-tender-next').show();
        $('#add-tender-confirm').hide();
        $('#add-tender-cancel').hide();
    }
    //显示第二步内容
    async function showSecondStep() {
        $('#add-tender-title').html(`<i class="fa fa-sticky-note-o"></i>新建单位工程`);
        $('#add-tender-confirm').hide();
        $('#featureStep').hide();
        $('#infoStep').hide();
        $('#firstStep').hide();
        $('#tender-required-warn').hide();
        $('#secondStep').show();
        $('#add-tender-prev').show();
        $('#add-tender-next').hide();
        $('#add-tender-confirm').hide();
        $('#add-tender-cancel').show();
        if (!infoData) {
            try {
                let fileKind = $('input[name="fileKind-tender"]:checked').val();
                infoData = await ajaxPost('/pm/api/getBasicInfo', {user_id: userID});
                needfulInfoData = getNeedfulBasicInfo(infoData, fileKind);
            } catch (err) {
                $('#add-tender-dialog').modal('hide');
            }
        }
        if (!featureData) {
            try{
                let valuation = curValuation;
                let engineeringName = $("#tender-engineering").val();
                let feeName = $('#tender-feeStandard').val();
                featureData = await ajaxPost('/pm/api/getProjectFeature',
                    {user_id: userID, valuationID: valuation, engineeringName: engineeringName, feeName: feeName});
            } catch (err) {
                $('#add-tender-dialog').modal('hide');
            }
        }
        let infoRequired = getRequired([], needfulInfoData),
            featureRequired = getRequired([], featureData),
            path = getAddPath();
        if (path === addPath.p_e_t && infoRequired.length > 0 || featureRequired.length > 0) {
            $('#add-tender-next').show();
        } else {
            $('#add-tender-confirm').show();
        }
    }
    //显示新建单位工程-建设项目基本信息内容
    function showInfoStep() {
        $('#add-tender-title').html('建设项目基本信息');
        $('#secondStep').hide();
        $('#infoStep').show();
        $('#tender-required-warn').show();
        let featureRequired = getRequired([], featureData);
        if (featureRequired.length > 0) {
            $('#add-tender-next').show();
            $('#add-tender-confirm').hide();
        } else {
            $('#add-tender-next').hide();
            $('#add-tender-confirm').show();
        }
        showRequiredInfo($('#infoStep'), needfulInfoData);
    }
    //显示新建单位工程-工厂特征内容
    function showFeatureStep() {
        $('#add-tender-next').hide();
        $('#add-tender-confirm').show();
        $('#add-tender-title').html('工程特征');
        $('#secondStep').hide();
        $('#infoStep').hide();
        $('#featureStep').show();
        $('#tender-required-warn').show();
        showRequiredInfo($('#featureStep'), featureData);
    }
    //显示必填信息(建设项目基本信息、单位工程工程特征)
    //必填信息：标记了必填required且不只读!readOnly
    function showRequiredInfo($form, datas) {
        $form.empty();
        let requiredDatas = getRequired([], datas);
        for (let data of requiredDatas) {
            $form.append(getFormRow(data));
        }
    }
    //根据基本信息、工程特征数据获取对应节点
    function getFormRow(data) {
        let dateReg = /([0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]{1}|[0-9]{1}[1-9][0-9]{2}|[1-9][0-9]{3})-(((0[13578]|1[02])-(0[1-9]|[12][0-9]|3[01]))|((0[469]|11)-(0[1-9]|[12][0-9]|30))|(02-(0[1-9]|[1][0-9]|2[0-8])))/;
        let cellType = data.cellType ? data.cellType : 'text';
        let $label = $(`<label for="staticEmail" class="col-3 col-form-label col-form-label-sm">${data.dispName}</label>`),
            $cell;
        if (cellType === 'comboBox') {
            let opts = data.options.split('@');
            $cell = $(`<select name="${data.key}" class="form-control form-control-sm"><option>请选择</option></select>`);
            for (let opt of opts) {
                $cell.append($(`<option ${data.value === opt ? 'selected' : ''} value="${opt}">${opt}</option>`));
            }
        } else if (cellType === 'date') {   //不用原生的日期控件
            $cell = $(`<input type="pm-${cellType}" name="${data.key}"
                       value="${data.value}" class="form-control form-control-sm" placeholder="请输入">`);
            $cell.datepicker({dateFormat: 'yy-mm-dd'});
            $cell.change(function () {
                if (!dateReg.test($($cell).val())) {
                    $($cell).val('');
                }
            });
        } else {
            $cell = $(`<input type="${cellType}" ${cellType === 'number' ? 'min="0"' : ''} name="${data.key}"
                       value="${data.value}" class="form-control form-control-sm" placeholder="请输入">`);
        }
        let $row = $(`<div class="form-group row"></div>`),
            $col = $(`<div class="col"></div>`);
        $col.append($cell);
        $row.append($label);
        $row.append($col);
        return $row;
    }

    //验证必填信息.
    function validRequiredData($form) {
        let eles = $form.find('input, select');
        for (let ele of eles) {
            $(ele).removeClass('shake-input');
            let v = $(ele).val().trim();
            if (!v || v === '请选择') {
                $(ele).focus();
                $(ele).addClass('shake-input');
                return false;
            }
        }
        return true;
    }

    //根据用户填的值，更新基本信息、工程特征数据
    function updateRequiredData($form, fullData) {
        let eles = $form.find('input, select');
        for (let ele of eles) {
            let key = $(ele).attr('name');
            if (!key) {
                continue;
            }
            let data = findRequiredByKey(key, fullData);
            if (data) {
                data.value = $(ele).val();
                if (data.cellType === 'date') {
                    data.value = data.value.replace('/\//g', '-');
                }
            }
        }
    }
    //根据key获取基本信息/工程特征数据
    function findRequiredByKey(key, data) {
        function findItem(k, data) {
            for (let d of data) {
                if (d.key === k) {
                    return d;
                }
                if (d.items && d.items.length > 0) {
                    let target = findItem(k, d.items);
                    if (target) {
                        return target;
                    }
                }
            }
            return null;
        }
        return findItem(key, data);
    }

    // 新增单位工程
    $("#add-tender-confirm").click(function() {
        if (STATE.addingTender) {
            return;
        }
        if (getAddPath() === addPath.p_e_t && !validRequiredData($('#infoStep'))) {
            return;
        }
        if (!validRequiredData($('#featureStep'))) {
            return false;
        }
        STATE.addingTender = true;
        if (needfulInfoData && Array.isArray(needfulInfoData)) {
            updateRequiredData($('#infoStep'), needfulInfoData);
        }
        if (featureData && Array.isArray(featureData)) {
            updateRequiredData($('#featureStep'), featureData);
        }
        let suc = AddTender();
        if(suc === false){
            STATE.addingTender = false;
        }
    });

    // 新增文件夹操作
    $("#add-folder-confirm").click(function() {
        if (STATE.addingFolder) {
            return;
        }
        STATE.addingFolder = true;
        let suc = AddFolder();
        if (suc === false) {
            STATE.addingFolder = false;
        }
    });

    // 删除时文字替换
    $('#del').on('show.bs.modal', function() {
        let hasTenderChild = function (children) {
            for (let i = 0; i < children.length; i++) {
                if (children[i].children.length === 0) {
                    if (children[i].data.projType === 'Tender') {
                        return true;
                    }
                } else if (hasTenderChild(children[i].children)) {
                    return true;
                }
            }
            return false;
        };
        // 显示内容
        let tenderHintElement = $('#tenderHint');
        let folderHintElement = $('#folderHint');
        if (projTreeObj.tree.selected.children.length === 0) {
            tenderHintElement.show();
            tenderHintElement.text('删除 "' + projTreeObj.tree.selected.data.name +'" ？');
            folderHintElement.hide();
        } else {
            tenderHintElement.hide();
            folderHintElement.show();
            folderHintElement.text('删除 "'+ projTreeObj.tree.selected.data.name +'" 以及它包含的子项？');
        }
        // 显示是否可以找回
        if (hasTenderChild([projTreeObj.tree.selected])) {
            $('#restoreHint').show();
        } else {
            $('#restoreHint').hide();
        }
    });

    // 删除操作
    $('#delete-confirm').click(function () {
        if (STATE.deleting) {
            return;
        }
        STATE.deleting = true;
        let updateData = null;
        let dialog = $('#del');
        if (projTreeObj.tree && projTreeObj.tree.selected) {
            $.bootstrapLoading.start();
            updateData = GetDeleteUpdateData(projTreeObj.tree.selected);
            UpdateProjectData(updateData, function () {
                dialog.modal('hide');
                let selected = projTreeObj.tree.selected;
                //删除行号
                let rIdx = projTreeObj.tree.items.indexOf(selected);
                //删除行数
                let rCout = selected.posterityCount() + 1;
                projTreeObj.tree.removeNode(selected);
                let refreshNodes = projTreeObj.calEngineeringCost(selected);
                //delete view
                let sheet = projTreeObj.workBook.getActiveSheet();
                projTreeObj.remove(sheet, rIdx, rCout);
                if(selected.data.projType == projectType.tender||selected.data.projType == projectType.engineering){
                    projTreeObj.refreshNodeData(refreshNodes);//刷新工程造价信息
                }
                $.bootstrapLoading.end();
                //快速点击时，第一个项目删除成功了，可能会删除多项目
                setTimeout(function () {
                    STATE.deleting = false;
                }, 500);
                projTreeObj.emitTreeChange();
            }, function () {
                $.bootstrapLoading.end();
                setTimeout(function () {
                    STATE.deleting = false;
                }, 500);
            });
        }
    });

    // 重命名按钮点击
    /*$('#rename-btn').click(function() {
        if (!projTreeObj.tree) {
            return false;
        }
        if (!projTreeObj.tree.selected) {
            alert('请选择需要重命名的数据');
            return false;
        }
        $('#rename-name').val(projTreeObj.tree.selected.data.name ? projTreeObj.tree.selected.data.name : '');
        $('#rename-dialog').modal('show');
        setTimeout(function () {
            $('#rename-name')[0].focus();
        }, 300);
    });*/

    // 重命名操作
    $("#rename-confirm").click(function() {
        let select = projTreeObj.tree.selected;
        let parent = select ? select.parent : Tree._root;
        let newName = $('#rename-name').val().trim();
        let dialog = $('#rename-dialog');
        if (newName === '') {
            setDangerInfo($('#rename-name-info'), '请输入重命名');
            return false;
        }

        if (newName === select.data.name) {
            dialog.modal('hide');
            return false;
        }
        if(existName(newName, parent.children, select.data.projType)){
            setDangerInfo($('#rename-name-info'), `已存在“${newName}”`);
            return;
        }
        newName = whiteSpaceCollapse(newName);
        RenameProject(select.id(), newName, select.data.ParentID, function () {
            setDangerInfo($('#rename-name-info'), '', false);
            dialog.modal('hide');
            select.data.name = newName;
            let sheet = projTreeObj.workBook.getActiveSheet();
            projTreeObj.setCellValue({ row: sheet.getActiveRowIndex(), col: 0 }, select, sheet, projTreeObj.setting);
            projTreeObj.emitTreeChange();
        });
    });


    // 复制到按钮点击
    /*$('#copy-to-btn').click(function () {
        let selectedItem = projTreeObj.tree.selected;
        try {
            let selectedType = selectedItem !== null && selectedItem.data !== undefined ?
                selectedItem.data.projType : '';
            if (selectedType !== projectType.tender) {
                throw '请选择单位工程进行复制';
            }
        } catch (error) {
            alert(error);
            return false;
        }
        $('#copy-to-dialog').modal('show');
    });*/
    // 复制到弹层替换
  /*  $('#copy-to-dialog').on('show.bs.modal', function () {
        copytoZTree = ConvertTreeToZtree(projTreeObj.tree, $('#treeDemo2'), null);
    });*/

    $('#copy-to-dialog').on('shown.bs.modal', function () {
        projTreeObj.initCopyToSpread();
       // copytoZTree = ConvertTreeToZtree(projTreeObj.tree, $('#treeDemo2'), null);
    });

    $('#m_replace_file').on('shown.bs.modal', function () {
        // projTreeObj.tree.selected
        projTreeObj.initReplaceSpread();
    });
    $("input[name='select_from']").each(function(){
        $(this).click(function(){
            projTreeObj.initHtmlByFromRadio();
        });
    });
    // 复制到操作
    $("#copy-to-confirm").click(async function() {
        try {
            let originalNode = projTreeObj.tree.selected;
            let toNode = projTreeObj.copySelected;
            let projectNode;    //建设项目节点
        let parent = null,next = null,projectMap={};
            if(toNode.data.projType == projectType.engineering){//复制为目标的子节点
                projectNode = toNode.parent;
                parent = toNode;
                next = toNode.firstChild();
            }else if(toNode.data.projType == projectType.tender){//复制为目标的后兄弟
                projectNode = toNode.parent.parent;
                parent = toNode.parent;
                next = toNode.nextSibling;
                projectMap['update'] = {query:{ID:toNode.id()}};//前一节点的下一个节点更新;
            }
            //目标建设项目的计税方法与单位工程的一致时，才可复制到，否则提示“当前单位工程计税方法与目标建设项目不一致，不可复制。 确定”。
            if (projectNode.data.property.taxType != originalNode.data.property.taxType) {
                alert('当前单位工程计税方法与目标建设项目不一致，不可复制。');
                return false;
            }
            let nextID = next?next.id():-1;
            let projectData = _.cloneDeep(originalNode.data);
            projectData['ParentID'] = parent.id();
            projectData['NextSiblingID'] = nextID;
            projectData['property'] ={};
            projectData['property']['rootProjectID'] = parent.pid();
            projectData['shareInfo'] = [];
            let rename = projTreeObj.projectNameChecking(parent,originalNode,"复制");//重名检查
            rename? projectData['name'] = rename:'';
            projectMap['copy'] = {document:projectData};
            $("#copy-to-dialog").modal('hide');
            const copyRst = await ajaxPost('/pm/api/copyProjects', {projectMap:projectMap,user_id: userID, tenderCount: 1});
            if (!copyRst.error) {
                $.bootstrapLoading.progressStart('拷贝项目', true);
                $("#progress_modal_body").text('正在拷贝项目，请稍候……');
                await importProcessChecking(null, null, (newProjectData) => handleTenderAfterChecking(newProjectData, projectData));
            }
        } catch (err) {
            alert(err);
        }

    });
    $('#selectSameTypeProject').click(function(){
        let value = $(this).prop('checked') == true?1:0;
            projTreeObj.selectSameTypeProject(value);
    });

    $('#changeFileConfirm').click(function(){
        projTreeObj.confirmFileChange();
    });

    // 选择工程专业后动态更改费率文件等数据
    $("#tender-engineering").change(function() {
        changeEngineering()
    });
    $('#tender-feeStandard').change(function () {
       changeFeeStandard();
    });
    //导入相关
    importView.eventListen();
});

//初始化工程专业库
function initEngineering() {
    let engineeringList = getEngineeringList();
    let engineeringHtml = getEngineeringHtml(engineeringList);
    $("#tender-engineering").html(engineeringHtml);
    changeEngineering();
}

async function changeEngineering(){
    $('#engineering-info').hide();
    initFeeStandardSel();
}

function changeFeeRate(engLib) {
    if(engLib){
        /*
         if (engLib.fee_lib !== undefined && engLib.fee_lib.length > 0) {
         $("#tender-fee-rate").children("option").first().val("newFeeRate-"+engLib.fee_lib[0].id);
         }*/
        //2018-08-29  费率改为和计税方式绑定在一起 所以在这里还不能确定标准费率库ID
        $("#tender-fee-rate").children("option").first().val("newFeeRate@@");
        $("#tender-engineering").parent().siblings('.hidden-area').slideDown('fast');
    }
    else {
        $("#tender-fee-rate").children("option").first().val($('#tender-name').val());
    }
}

//根据文件类型筛选新的基本信息数据
function getNeedfulBasicInfo(info, fileKind) {
    /* let strMap = {
        1: 'tender',    //投标
        2: 'bid',       //招标
        3: 'control'    //控制价
    }; */
    const strMap = {
        1: '投标',    //投标
        2: '招标',       //招标
        3: '控制价'    //控制价
    };
    return filterItems(info);

    // 递归过滤
    function filterItems(items) {
        const filterdItems = items.filter(item => !item.fileKind || item.fileKind === strMap[fileKind]);
        filterdItems.forEach(item => {
            if (item.items && item.items.length) {
                item.items = filterItems(item.items);
            }
        });
        return filterdItems;
    }

    /* let needfulData = info.filter(data => !data.fileKind || data.fileKind === strMap[fileKind]);
    needfulData.forEach(nData => {
        let needfulSub = nData.items.filter(sData => !sData.fileKind || sData.fileKind === strMap[fileKind]);
        nData.items = needfulSub;
    });
    return needfulData; */
}

function getRequired(rst, datas) {
    // 暂时不填必填项了
    return [];
    if (!datas) {
        return rst;
    }
    for (let data of datas) {
        let required = typeof data.required === 'string' ? JSON.parse(data.required) : data.required,
            readOnly = typeof data.readOnly === 'string' ? JSON.parse(data.readOnly) : data.readOnly;
        if (required && !readOnly) {
            rst.push(data);
        }
        if (data.items && data.items.length > 0) {
            getRequired(rst, data.items);
        }
    }
    return rst;
}
//变换专业工程、变换费用标准，重新获取工程库数据...
async function changeFeature() {
    let valuation = curValuation;
    let engineeringName = $("#tender-engineering").val();
    let feeName = $('#tender-feeStandard').val();
    featureData = await ajaxPost('/pm/api/getProjectFeature',
        {user_id: userID, valuationID: valuation, engineeringName: engineeringName, feeName: feeName});
    updateAddState(needfulInfoData, featureData);
}

//更新当前新建单位工程是否需要下一步
function updateAddState(needfulInfoData, featureData) {
    let infoRequired = getRequired([], needfulInfoData),
        featureRequired = getRequired([], featureData),
        path = getAddPath();
    if (path === addPath.p_e_t && infoRequired.length > 0 || featureRequired.length > 0) {
        $('#add-tender-next').show();
        $('#add-tender-confirm').hide();
    } else {
        $('#add-tender-next').hide();
        $('#add-tender-confirm').show();
    }
}

async function initFeeStandardSel() {
    $('#tender-feeStandard').empty();
    let feeStandards = [];
    let engineeringList = getEngineeringList();
    let currentEngName = $('#tender-engineering').val();
    for(let eng of engineeringList){
        if(eng.lib.name && eng.lib.name === currentEngName && eng.lib.feeName && eng.lib.feeName !== ''){
            feeStandards.push(eng.lib.feeName);
        }
    }
    for(let feeName of feeStandards){
        let $opt = $(`<option value="${feeName}">${feeName}</option>`);
        $('#tender-feeStandard').append($opt);
    }
    if(feeStandards.length > 0){
        if($('#feeStandard-info').is(':visible')){
            $('#feeStandard-info').hide();
        }
    }
    //变换专业工程、变换费用标准，重新获取工程库数据...
    if (curStep === 2) {
        await changeFeature();
    }
    let currentEngLib = getEngineeringLib(currentEngName + $('#tender-feeStandard').val(), engineeringList);
    changeFeeRate(currentEngLib);
    //setTaxGroupHtml();
    getStdCalcProgramFiles();
}

async function changeFeeStandard() {
    //变换专业工程、变换费用标准，重新获取工程库数据...
    if (curStep === 2) {
        await changeFeature();
    }
    let currentEngLib = getEngineeringLib($('#tender-engineering').val() + $('#tender-feeStandard').val(), getEngineeringList());
    changeFeeRate(currentEngLib);
    //setTaxGroupHtml();
    getStdCalcProgramFiles();
}

function setTaxGroupHtml() {
    let groups = getTaxGroupList();
    let taxTypeArray = [];
    let htmlString = "";
    if(groups && groups.length > 0){
        taxTypeArray = _.uniq(_.map(groups,'taxType'));
    }
    for(let t of taxTypeArray){
        htmlString += "<option value='"+t+"'>"+taxTypeMap[t]+"</option>"
    }
    $('#taxType').html(htmlString);
    if(taxTypeArray.length <2){
        $('#taxType_div').hide();
    }else {
        $('#taxType_div').show();
    }
}

function getStdCalcProgramFiles(){
    function getStdCPFilesHtml(taxGroups) {
        let result = '';
        if (taxGroups.length <= 0) {
            return result;
        };

        for (let group of taxGroups){
            let groupString = ""; //把计算程序、清单模板、列设置的ID生成一个组合的值
            let p_id = group.program_lib?group.program_lib.id:"";
            let t_id = group.template_lib?group.template_lib.id:"";
            let c_id = group.col_lib?group.col_lib.id:"";
            let f_id = group.fee_lib?group.fee_lib.id:"";
            groupString = p_id + "|-|" +t_id+"|-|"+c_id+"|-|"+f_id;
            result += '<option value='+ groupString +'>'+ group.program_lib.name +'</option>';
        };
        return result;
    };
    let taxType = curTaxType; //计税方法取建设项目的
    let stdCPHtml = getStdCPFilesHtml(getTaxGroupList(taxType));
    $("#tender-calcProgram").html(stdCPHtml);
    if ($("#tender-calcProgram")[0].options.length > 1)
        $("#tender-calcProgram")[0].selectedIndex = 0;
}
//获取工作表总宽度
function getWorkBookWidth(){
    return workBookWidth = $(window).width() - $('.pm-side').width() - 90;
}

// 初始化节点可见性，默认收起至建设项目层
function initNodesVisibility(nodes, visible) {
    function recurSetVisible(nodes, visible) {
        nodes.forEach(node => {
            node.visible = visible;
            if (node.children) {
                recurSetVisible(node.children, visible);
            }
        });
    }
    nodes.forEach(node => {
        const isProject = node.data.projType === projectType.project;
        if (isProject) {
            node.expanded = visible;
            recurSetVisible(node.children, visible);
        }
    });
}

function initProjects(callback, expandCallback) {
    GetAllProjectData(function (datas) {
        //设置工程专业
        for (let data of datas) {
            if (data.projType === projectType.tender) {
                data.feeStandardName = data.property.feeStandardName || '';
            }
        }
        CommonAjax.post('/options/getOptions', [], function (rstData) {
            projTreeObj.setting.style.selectedColor = rstData.COLOROPTS.SELECTED.backColor;
            projTreeObj.tree = pmTree.createNew(projTreeObj.setting, datas);
            projTreeObj.tree.selected = projTreeObj.tree.items[0];
            projTreeObj.workBook = projTreeObj.buildSheet(projTreeObj.workBook,'projSpread',projTreeObj.setting);
            const sheet = projTreeObj.workBook.getSheet(0);
            sheet.options.frozenlineColor = '#ababab';
            sheet.frozenColumnCount(2);
            sheet.name('projectSheet');
            sheetCommonObj.spreadDefaultStyle(projTreeObj.workBook);
            projTreeObj.sumEngineeringCost();
            if (expandCallback) {
                expandCallback();
            } else {
                initNodesVisibility(projTreeObj.tree.items, false);
            }
            projTreeObj.showTreeData(projTreeObj.tree.items, projTreeObj.setting, sheet);
            //初始选择
            const initSel = sheet.getSelections()[0] ? sheet.getSelections()[0] : { row: 0, rowCount: 1 };
            projTreeObj.initSelection(initSel, null, sheet);
            autoFlashHeight();
            projTreeObj.workBook.refresh();
            if (callback) {
                callback();
            }
        }, function () {
            $.bootstrapLoading.end();
        });
    });
}

/**
 * 初始化数据
 */
async function init(refresh = false, callback, expandCallback) {
    console.log('init');
    //init spread and pmTree
    try {
        if(refresh == false) socketObject.connect('pm');//socket 连接;
        if (isFirst) {
            isFirst = false;
            $.bootstrapLoading.progressStart('欢迎使用大司空计价', true);
            $("#progress_modal_body").text('首次加载例题，请稍候……');
            await ajaxPost('/pm/api/prepareInitialData', {user_id: userID});
            await importProcessChecking(null, null, () => {
                initProjects(() => {
                    $.bootstrapLoading.progressEnd();
                    if (callback) {
                        callback();
                    }
                }, expandCallback);
            }, true);
        } else {
            await importProcessChecking(null, ({ content }) => {
                $.bootstrapLoading.progressStart('欢迎使用大司空计价', true);
                $("#progress_modal_body").text(content);
            }, () => {
                $.bootstrapLoading.start();
                initProjects(() => {
                    $.bootstrapLoading.end();
                    if (callback) {
                        callback();
                    }
                }, expandCallback);
            }, true);
        }
        engineering = engineeringList !== null && engineeringList !== undefined ? JSON.parse(engineeringList) : [];
    } catch (error) {
        alert(error)
    }
}

function refreshAllPage(){
    if(gcTreeObj.workBook){
        gcTreeObj.workBook.destroy();
        gcTreeObj.workBook = null;
    }
    gcTreeObj.tree = null;
    init(true);
}


function whiteSpaceCollapse(v) {
    v = v.replace(/[\r\n\t]/g, ' ');
    v = v.trim();
    return v.replace(/\s{1,}/g, ' ');
}

/**
 * 新增建设项目
 *
 * @return {boolean}
 */
function AddProject() {
    let name = $('#project-name').val().trim();
    if (name === '') {
        setDangerInfo($('#project-name-info'), '请填写建设项目名称');
        return false;
    }
    name = whiteSpaceCollapse(name);
    let fileKind = $('input[name="fileKind"]:checked').val();
    if (!fileKind) {
        setDangerInfo($('#fileKind-info'));
        return false;
    }
    let valuation = $('#proj-valuation').val();
    if (!valuation) {
        setDangerInfo($('#proj-valuation-info'));
        return false;
    }
    let valuationName = $('#proj-valuation').text().trim();
    let taxType = $('input[name="taxType"]:checked').val();
    if (!taxType) {
        setDangerInfo($('#taxType-info'));
        return false;
    }
    $.bootstrapLoading.start();
    let existCallback = function () {
        setDangerInfo($('#project-name-info'), `已存在“${$("#project-name").val()}”`);
        STATE.addingProject = false;
        $.bootstrapLoading.end();
    };
    let sucCallback = function () {
        $('#addProjOk').removeClass('disabled');
        $('#add-project-dialog').modal('hide');
        $('#project-name').val('');
        setDangerInfo($('#project-name-info'), '', false);
        $.bootstrapLoading.end();
        setTimeout(function () {
            STATE.addingProject = false;
        }, 500);
        projTreeObj.emitTreeChange();
    };
    let errCB = function () {
        $.bootstrapLoading.end();
        setTimeout(function () {
            STATE.addingProject = false;
        }, 500);
    };
    let selectedItem = projTreeObj.tree.selected;

    /*
     * （1）、当前没有焦点行，新建建设项目为第一个节点。
     （2）、当前定位在文件夹，新建建设项目为文件夹的最后一个子节点。
     （3）、当前定位在建设项目，新建建设项目为其后兄弟。
     （4）、当前定位在单项工程或单位工程，新建项目为当前所属建设项目的后兄弟。
     * */
    let property = {basicInformation: needfulInfoData ? needfulInfoData : [],
        fileKind: fileKind,
        taxType: taxType,
        valuation: valuation,
        valuationName: valuationName,
        valuationType: curValutionType
    };
    if(!selectedItem){
        AddSiblingsItem(selectedItem, name, property, projectType.project, existCallback, sucCallback, errCB);
    }
    else {
        if(selectedItem.data.projType === projectType.project){
            AddSiblingsItem(selectedItem, name, property, projectType.project, existCallback, sucCallback, errCB);
        }
        else if(selectedItem.data.projType === projectType.engineering || selectedItem.data.projType === projectType.tender){
            let proj = selectedItem.parent.data.projType === projectType.project ? selectedItem.parent : selectedItem.parent.parent;
            AddSiblingsItem(proj, name, property, projectType.project, existCallback, sucCallback, errCB);
        }
        else if(selectedItem.data.projType === projectType.folder){
            AddChildrenItem(selectedItem, name, property, projectType.project, existCallback, sucCallback, errCB);
        }
    }
}

//新建建设项目、单项工程、文件夹、重命名提示(文本改变，暂时不需要)
function getChangedFunc(input, nameInfo){
    return function () {
        let selected = Tree.selected();
        let parent = selected ? selected.parent : Tree._root;
        let name = input.val();
        if(existName(name, parent.children)){
            nameInfo.text(`已存在“${name}”`);
            nameInfo.show();
        }
        else {
            nameInfo.text('');
            nameInfo.hide();
        }
    }
}

//新增节点，初始化汇总数值
function setInitSummaryData(data) {
    if(data.projType === projectType.folder){
        return;
    }
    //just for View
    data.engineeringCost = 0;
    data.subEngineering = 0;
    data.measure = 0;
    data.safetyConstruction = 0;
    data.other = 0;
    data.charge = 0;
    data.tax = 0;
    data.rate = data.projType === projectType.project ? 100 : 0;
    data.buildingArea = '';
    data.perCost = '';
}

function getAddPath() {
    let projName = $("#poj-name").val().trim(),
        engName = $("#eng-name").val().trim(),
        selected = projTreeObj.tree.selected;
    let tempProjs = getProjs(selected);
    let tempProj = getNodeByName(projName, tempProjs);
    let tempEng;
    if(tempProj){
        tempEng = getNodeByName(engName, tempProj.children);
        if(tempEng){
           return addPath.t;
        } else {
            return addPath.e_t
        }
    } else {
        return addPath.p_e_t;
    }
}

function AddTenderItems(selected, projName, engName, tenderName, property, callback, errCB){
    let path, updateDatas = [];
    let tempProjs = getProjs(selected);
    let tempProj = getNodeByName(projName, tempProjs);
    let tempEng;
    if(tempProj){
        tempEng = getNodeByName(engName, tempProj.children);
        if(tempEng){
            path = addPath.t;
        }
        else {
            path = addPath.e_t
        }
    }
    else {
        path = addPath.p_e_t;
    }
    if(path === addPath.p_e_t){
        let parent, pre, next;
        GetNewProjectId(3, function (IDs) {
            let projID = IDs.lowID, engID = IDs.lowID + 1, tenderID = IDs.lowID + 2;
            if(!selected || selected.data.projType === projectType.project){
                parent = selected ? selected.parent : projTreeObj.tree._root;
                pre = selected;
                next = selected ? selected.nextSibling : projTreeObj.tree.firstNode();
            }
            else if(selected.data.projType === projectType.folder){
                parent = selected ? selected : projTreeObj.tree._root;
                pre = selected ? selected.lastChild() : projTreeObj.tree.firstNode();
                next = null;
            }
            else if(selected.data.projType === projectType.engineering || selected.data.projType === projectType.tender){
                let selectedProj = selected.parent.data.projType === projectType.project ? selected.parent : selected.parent.parent;
                parent = selectedProj ? selectedProj.parent : projTreeObj.tree._root;
                pre = selectedProj;
                next = selectedProj ? selectedProj.nextSibling : projTreeObj.tree.firstNode();
            }
            let fileKind = $('input[name="fileKind-tender"]:checked').val();
            let updateProjs = GetUpdateData(pre, parent, next, projName, {
                basicInformation: needfulInfoData ? needfulInfoData : [],
                fileKind: parseInt(fileKind), taxType: curTaxType, valuationType: curValutionType, valuation: curValuation, valuationName: curValuationName},
                projID, {updateType: 'new', projectType: projectType.project});
            let updateEng = {updateType: 'new', updateData: {ID: engID, ParentID: projID, NextSiblingID: -1, name: engName, projType: projectType.engineering}};
            property.rootProjectID = projID;
            let updateTender = {updateType: 'new', updateData: {ID: tenderID, ParentID: engID, NextSiblingID: -1, name: tenderName, projType: projectType.tender, property: property}};
            updateDatas = updateDatas.concat(updateProjs);
            updateDatas.push(updateEng);
            updateDatas.push(updateTender);
            UpdateProjectData(updateDatas, function(datas){
                let projData, engData, tenderData;
                datas.forEach(function (data) {
                    if (data.updateType === 'new') {
                        data.updateData.shareInfo = [];
                        setInitSummaryData(data.updateData);
                        if(data.updateData.projType === projectType.project){
                            projData = data.updateData;
                        }
                        else if(data.updateData.projType === projectType.engineering){
                            engData = data.updateData;
                        }
                        else if(data.updateData.projType === projectType.tender){
                            tenderData = data.updateData;
                            tenderData.feeStandardName = tenderData.property.feeStandardName || '';
                        }
                    }
                });
                let pojNode = projTreeObj.insert(projData, parent, next);
                let engNode = projTreeObj.insert(engData, pojNode, null);
                let tenderNode = projTreeObj.insert(tenderData, engNode, null);
                const rows = [pojNode.serialNo(), engNode.serialNo(), tenderNode.serialNo()];
                sheetCommonObj.setRowsAutoFit(projTreeObj.workBook.getSheet(0), rows, 0, true)
                callback();           
            }, errCB);
        }, errCB);
    }
    else if(path === addPath.e_t){
        GetNewProjectId(2, function (IDs) {
            let engID = IDs.lowID, tenderID = IDs.lowID + 1;
            let pre = tempProj.lastChild();
            let next = null;
            let updateEng = {updateType: 'new', updateData: {ID: engID, ParentID: tempProj.data.ID, NextSiblingID: -1, name: engName, projType: projectType.engineering}};
            property.rootProjectID = tempProj.data.ID;
            let updateTender = {updateType: 'new', updateData: {ID: tenderID, ParentID: engID, NextSiblingID: -1, name: tenderName, projType: projectType.tender, property: property}};
            if(selected && selected.data.projType === projectType.engineering && selected.parent === tempProj){
                pre = selected;
                next = selected.nextSibling;
                updateEng.updateData.NextSiblingID = pre.data.NextSiblingID;
            }
            updateDatas.push(updateEng);
            updateDatas.push(updateTender);
            if(pre){
                updateDatas.push({updateType: 'update', updateData: {ID: pre.id(), NextSiblingID: engID}});
            }
            UpdateProjectData(updateDatas, function (datas) {
                let engData, tenderData;
                datas.forEach(function (data) {
                    if (data.updateType === 'new') {
                        data.updateData.shareInfo = [];
                        setInitSummaryData(data.updateData);
                        if(data.updateData.projType === projectType.engineering){
                            engData = data.updateData;
                        }
                        else if(data.updateData.projType === projectType.tender){
                            tenderData = data.updateData;
                            tenderData.feeStandardName = tenderData.property.feeStandardName || '';
                        }
                    }
                });
                let engNode = projTreeObj.insert(engData, tempProj, next);
                let tenderNode = projTreeObj.insert(tenderData, engNode, null);
                const rows = [engNode.serialNo(), tenderNode.serialNo()];
                sheetCommonObj.setRowsAutoFit(projTreeObj.workBook.getSheet(0), rows, 0, true);
                callback();
            }, errCB);
        }, errCB);
    }
    else if(path === addPath.t){
        GetNewProjectId(1, function (IDs) {
            let tenderID = IDs.lowID;
            let pre = tempEng.lastChild();
            property.rootProjectID = tempProj.data.ID;
            let updateTender = {updateType: 'new', updateData: {ID: tenderID, ParentID: tempEng.id(), NextSiblingID: -1, name: tenderName, projType: projectType.tender, property: property}};
            updateDatas.push(updateTender);
            if(pre){
                updateDatas.push({updateType: 'update', updateData: {ID: pre.id(), NextSiblingID: tenderID}});
            }
            UpdateProjectData(updateDatas, function (datas) {
                let tenderNode = null;
                datas.forEach(function (data) {
                    if(data.updateType === 'new') {
                        data.updateData.shareInfo = [];
                        setInitSummaryData(data.updateData);
                        data.updateData.feeStandardName = data.updateData.property.feeStandardName || '';
                        tenderNode = projTreeObj.insert(data.updateData, tempEng, null);
                        const rows = [tenderNode.serialNo()];
                        sheetCommonObj.setRowsAutoFit(projTreeObj.workBook.getSheet(0), rows, 0, true);
                    }
                });
                callback();
                //自动打开新建的单位工程
                //projTreeObj.openTender(tenderNode.data.ID, tenderNode.parent, 500);
            }, errCB);
        }, errCB);
    }
}

/**
 * 新增子元素
 *
 * @param {String} name
 * @param {String} type
 * @param {function} callback
 * @return {void}
 */
function AddChildrenItem(selected, name, property, type, existCallback, sucCallback, errCB) {
    if(!selected){
        selected = projTreeObj.tree.selected;
    }
    let parent = selected ? selected : projTreeObj.tree._root;
    let pre = selected ? selected.lastChild() : projTreeObj.tree.firstNode();
    if(existName(name, parent.children)){
        //alert('同级目录已存在相同名称数据.');
        existCallback();
    }
    else {
        GetNewProjectId(1, function(IDs) {
            let typeInfo = {
                updateType: 'new',
                projectType: type
            };
            let updateData = GetUpdateData(pre, parent, null, name, property, IDs.lowID, typeInfo);
            projTreeObj.tree.maxNodeId(IDs.lowID - 1);
            UpdateProjectData(updateData, function(datas){
                datas.forEach(function (data) {
                    if (data.updateType === 'new') {
                        data.updateData.shareInfo = [];
                        setInitSummaryData(data.updateData);
                        let node = projTreeObj.insert(data.updateData, parent, null);
                        sheetCommonObj.setRowsAutoFit(projTreeObj.workBook.getSheet(0), [node.serialNo()], 0, true);
                    }
                });
                sucCallback();
            }, errCB);
        }, errCB);
    }
}

/**
 * 新增同级元素
 *
 * @param {String} name
 * @param {String} type
 * @param {function} callback
 * @return {void}
 */
function AddSiblingsItem(selected, name, property, type, existCallback, sucCallback, errCB) {
    if(!selected){
        selected = projTreeObj.tree.selected;
    }
    let parent = selected ? selected.parent : projTreeObj.tree._root;
    let next = selected ? selected.nextSibling : projTreeObj.tree.firstNode();
    if(existName(name, parent.children, type)){
        existCallback();
    }
    else {
        GetNewProjectId(1, function(IDs) {
            let typeInfo = {
                updateType: 'new',
                projectType: type
            };
            let updateData = GetUpdateData(selected, parent, next, name, property, IDs.lowID, typeInfo);
            projTreeObj.tree.maxNodeId(IDs.lowID - 1);
            UpdateProjectData(updateData, function(datas){
                datas.forEach(function (data) {
                    if (data.updateType === 'new') {
                        data.updateData.shareInfo = [];
                        setInitSummaryData(data.updateData);
                        const node = projTreeObj.insert(data.updateData, parent, next);
                        sheetCommonObj.setRowsAutoFit(projTreeObj.workBook.getSheet(0), [node.serialNo()], 0, true)
                    }
                });
                sucCallback();
            }, errCB);
        }, errCB);
    }
}

// 设置计价规则下拉
function setValuationSels($sel, valuationData) {
    let reducer = (acc, cur) => acc + `<option value="${cur.id}">${cur.name}</option>`;
    let html = valuationData.reduce(reducer, '');
    $sel.html(html);
    curValuation = valuationData[0].id;
    curValuationName = valuationData[0].name;
}

//根据工程专业名称+费用标准名称获取工程专业库
function getEngineeringLib(cascadeName, engineeringList) {
    for(let eng of engineeringList){
        let engName = eng.lib.name ? eng.lib.name : '';
        let engFeeName = eng.lib.feeName ? eng.lib.feeName : '';
        if(cascadeName === engName + engFeeName){
            return eng.lib;
        }
    }
    return null;
}

function getEngineeringList(){
    let valuation = curValuation;
    let valuationType = curValutionType;
    let valuationData = valuationType === 'bill' ? billValuation : rationValuation;
    let engineeringList = [];
    for(let tmp of valuationData) {
        if (tmp.id === valuation) {
            engineeringList = tmp.engineering_list;
            break;
        }
    }
    return engineeringList;
}



function getTaxGroupList(type){//getcalcProgramList
    let egrs = getEngineeringList();
    let groupList = [];
    //let egrID = $("#tender-engineering").val();
    let engLib = getEngineeringLib($('#tender-engineering').val() + $('#tender-feeStandard').val(), egrs);
    if(engLib){
        if(type){//是否要过滤，如果这个参数不传，则返回整个数组;
            for(let group of engLib.tax_group){
                if(group.taxType == type && group.program_lib){
                    groupList.push(group);
                }
            }
        }else {
            groupList = engLib.tax_group;
        }
    }
    /*for(let egr of egrs) {
        if (egr.engineering_id == egrID && egr.lib) {
            if(type){//是否要过滤，如果这个参数不传，则返回整个数组;
                for(let group of egr.lib.tax_group){
                    if(group.taxType == type && group.program_lib){
                        groupList.push(group);
                    }
                }
            }else {
                groupList = egr.lib.tax_group;
            }
        }
    }*/
    return groupList;
}

function getNodeByName(name, nodes){
    for(let i = 0, len = nodes.length; i < len; i++){
        if(name === nodes[i].data.name){
            return nodes[i];
        }
    }
    return null;
}

//建设项目名称是否有效的
function validProjectName(name) {
    let selected = projTreeObj.tree.selected,
        parent = null;
    if (selected && selected.data.projType === projectType.folder) {
        parent = selected ? selected : projTreeObj.tree._root;
    } else {
        if (selected && [projectType.tender, projectType.engineering].includes(selected.data.projType)) {
            selected = selected.parent.data.projType === projectType.project ? selected.parent : selected.parent.parent;
        }
        parent = selected ? selected.parent : projTreeObj.tree._root;
    }
    return !existName(name, parent.children);
}

//同级是否重名,文件夹与建设项目可以同名
function existName(name , nodes, projType = null){
    for(let i = 0, len = nodes.length; i < len; i++){
        if(name === nodes[i].data.name){
            if(projType && projType === projectType.folder && nodes[i].data.projType === projectType.project){
                continue;
            }
            return true;
        }
    }
    return false;
}

//获取新建单位工程时的建设项目数据
function getProjs(selected){
    let rst = [];
    let temp;
    let firstNode;
    if(!selected){
        temp = projTreeObj.tree._root;
        firstNode = temp.children[0];
    }
    else if(selected.data.projType === projectType.folder){
        temp = selected;
        firstNode = temp.children[0];
    }
    else if(selected.data.projType === projectType.project){
        temp = selected.parent;
        firstNode = temp.children[0];
    }
    else if(selected.data.projType === projectType.engineering || selected.data.projType === projectType.tender){
        let proj = selected.parent.data.projType === projectType.project ? selected.parent : selected.parent.parent;
        temp = proj.parent;
        firstNode = proj;
    }
    for(let childNode of temp.children){
        if(childNode.data.projType === projectType.project){
            rst.push(childNode);
        }
    }
    if(firstNode){
        //firstNode to first place
        let index = null;
        for(let i = 0, len = rst.length; i < len; i++){
            if(rst[i].data.ID === firstNode.data.ID){
                index = i;
                break;
            }
        }
        if(index){
            rst.splice(index, 1);
            rst.splice(0, 0, firstNode);
        }
    }
    return rst;
}

function setFileOptions(projID){
    // 获取单价文件数据
    if(!projID){
        $("#unit-price").children("option:not(':first')").remove();
        let first = $("#tender-fee-rate").children("option").first();
        $("#tender-fee-rate").empty();
        $("#tender-fee-rate").append(first);

    }
    else {
        getUnitFile(projID, function (response) {
            $("#unit-price").children("option:not(':first')").remove();
            if (response.data.length <= 0) {
                return false;
            }
            let unitFileHtml = '';
            response.data.forEach((uf, index) => {
                unitFileHtml += `<option value=${uf.id} ${index === 0 ? 'selected' : ''}>${uf.name}</option>`
            });
            /* for(let tmp of response.data) {
                unitFileHtml += '<option value="'+ tmp.id +'">'+ tmp.name +'</option>';
            } */
            $("#unit-price").children("option").first().after(unitFileHtml);
        });
        // 获取费率文件数据
        getFeeRateFile(projID, function (response) {
            let first = $("#tender-fee-rate").children("option").first();
            $("#tender-fee-rate").empty();
            $("#tender-fee-rate").append(first);
            if (response.data.length <= 0) {
                return false;
            }
            /* for(let tmp of response.data) {
                let option =  $("<option>").val(tmp.ID).text(tmp.name);
                $("#tender-fee-rate").append(option);
            } */
            let feeRateFileHtml = '';
            response.data.forEach((ff, index) => {
                feeRateFileHtml += `<option value=${ff.ID} ${index === 0 ? 'selected' : ''}>${ff.name}</option>`
            });
            $("#tender-fee-rate").children("option").first().after(feeRateFileHtml);
        });
    }
}

//建设项目下拉框
function setProjOptions(projs, selected){
    $("#poj-name-list").empty();
    $("#poj-name").val("");
    if(projs.length > 0){
        let firstProj = selected && selected.data.projType === projectType.project ? selected: projs[0];
        curTaxType = firstProj.data.property.taxType || 1;
        if (firstProj.data.property.valuationType) {
            curValutionType = firstProj.data.property.valuationType;
        }
        if (firstProj.data.property.valuation) {
            curValuation = firstProj.data.property.valuation;
        }
        if (firstProj.data.property.valuationName) {
            curValuationName = firstProj.data.property.valuationName;
        }
        if (firstProj.data.property.valuation)
        getStdCalcProgramFiles();
        $("#poj-name").val(firstProj.data.name);
        setFileOptions(firstProj.data.ID);
        setEngOptions(firstProj.data.ID);
        for(let i = 0, len = projs.length; i < len; i++){
            let $proj = $(`<a class='text-ellipsis' title="${projs[i].data.name}">`).val(projs[i].data.ID).text(projs[i].data.name);
            $proj.addClass("dropdown-item");
            $proj.attr("href", "javascript:void(0);");
            $proj.click(function () {
                curTaxType = projs[i].data.property.taxType || 1;
                if (projs[i].data.property.valuationType) {
                    curValutionType = projs[i].data.property.valuationType;
                }
                if (projs[i].data.property.valuation) {
                    curValuation = projs[i].data.property.valuation;
                }
                if (projs[i].data.property.valuationName) {
                    curValuationName = projs[i].data.property.valuationName;
                }
                getStdCalcProgramFiles();
                $('#newProjectSet').hide();//隐藏文件类型、计税方法选项
                $("#poj-name").val(projs[i].data.name);
                setFileOptions(projs[i].data.ID);
                setEngOptions(projs[i].data.ID);
                $('#poj-name-info').hide();
            });
            $("#poj-name-list").append($proj);
        }
    }
    else {
        setFileOptions(null);
        setEngOptions(null);
    }
}
//单项工程下拉框
function setEngOptions(projID){
    let proj = projTreeObj.tree.findNode(projID) || null;
    $("#eng-name-list").empty();
    $("#eng-name").val("");
    if(proj){
        let engineerings = [].concat(proj.children);
        //set selected engineering to first place
        let selected = projTreeObj.tree.selected;
        let firstNode = null;
        if(selected && (selected.data.projType === projectType.engineering || selected.data.projType === projectType.tender)){
            firstNode = selected.data.projType === projectType.engineering ? selected : selected.parent;
        }
        if(firstNode){
            let index = null;
            for(let i = 0, len = engineerings.length; i < len; i++){
                if(firstNode.data.ID === engineerings[i].data.ID){
                    index = i;
                }
            }
            if(index){
                engineerings.splice(index, 1);
                engineerings.splice(0, 0, firstNode);
            }
        }
        if(engineerings.length > 0){
            $("#eng-name").val(engineerings[0].data.name);
            for(let i = 0, len = engineerings.length; i < len; i++){
                //let eng = $("<button>").val(engineerings[i].data.ID).text(engineerings[i].data.name);
                let $eng = $('<a>').val(engineerings[i].data.ID).text(engineerings[i].data.name);
                $eng.prop('href', 'javascript:void(0);');
                $eng.addClass("dropdown-item");
                //eng.attr("type", "button");
                $eng.click(function () {
                    $("#eng-name").val(engineerings[i].data.name);
                    $('#eng-name-info').hide();
                });
                $("#eng-name-list").append($eng);
            }
        }
        /*if(engineerings.length > 0){
            $("#eng-name").val(engineerings[0].data.name);
            for(let i = 0, len = engineerings.length; i < len; i++){
                let eng = $("<button>").val(engineerings[i].data.ID).text(engineerings[i].data.name);
                eng.addClass("dropdown-item");
                eng.attr("type", "button");
                eng.click(function () {
                    $("#eng-name").val(engineerings[i].data.name);
                    $('#eng-name-info').hide();
                });
                $("#eng-name-list").append(eng);
            }
        }*/
    }
}

function hasTender(selected, pojName, engName, tenderName){
    let isExist = false;
    let tempProjs = getProjs(selected);
    if(pojName !== ''){
        let tempProj = getNodeByName(pojName, tempProjs);
        if(tempProj){
            if(engName !== ''){
                let tempEng = getNodeByName(engName, tempProj.children);
                if(tempEng){
                    let tempTender = getNodeByName(tenderName, tempEng.children);
                    if(tempTender){
                        isExist = true;
                    }
                }
            }
        }
    }
    return isExist;
}

//替换class
function replaceClass(selector, orgClass, newClass){
    selector.removeClass(orgClass);
    selector.addClass(newClass);
}
//设置提示信息
function setDangerInfo(area, info, show = true){
    if (info) {
        area.text(info);
    }
    if(show)
        area.show();
    else
        area.hide();
}

/**
 * 新增单项工程
 *
 * @return {boolean}
 */
function AddEngineering() {
    let name = $('#engineering-name').val().trim();
    if (name === '') {
        setDangerInfo($('#engineering-name-info'), '请填写单项工程名称');
        return false;
    }
    name = whiteSpaceCollapse(name);
    $.bootstrapLoading.start();
    let existCallback = function () {
        setDangerInfo($('#engineering-name-info'), `已存在“${$("#engineering-name").val()}”`);
        STATE.addingEng = false;
        $.bootstrapLoading.end();
    };
    let sucCallback = function () {
        $('#add-engineering-dialog').modal('hide');
        $('#engineering-name').val('');
        setDangerInfo($('#engineering-name-info'), '', false);
        $.bootstrapLoading.end();
        setTimeout(function () {
            STATE.addingEng = false;
        }, 500);
        projTreeObj.emitTreeChange();
    };
    let errCB = function () {
        $.bootstrapLoading.end();
        setTimeout(function () {
            STATE.addingEng = false;
        }, 500);
    };
    let selectedItem = projTreeObj.tree.selected;
    // 如果选择的是单项工程则新增同级数据
    if(selectedItem){
        if(selectedItem.data.projType === projectType.project){
            AddChildrenItem(selectedItem, name, null, projectType.engineering, existCallback, sucCallback, errCB);
        }
        else if(selectedItem.data.projType === projectType.engineering){
            AddSiblingsItem(selectedItem, name, null, projectType.engineering, existCallback, sucCallback, errCB);
        }
        else if(selectedItem.data.projType === projectType.tender){
            let proj = selectedItem.parent;
            AddSiblingsItem(proj, name, null, projectType.engineering, existCallback, sucCallback, errCB);
        }
    }
}

/**
 * 新增单位工程
 *
 * @return {boolean}
 */
function AddTender() {
    try {
        let projName = $("#poj-name").val().trim();
        if(projName === ''){
            replaceClass($('#poj-name-info'), 'text-info', 'text-danger');
            setDangerInfo($('#poj-name-info'), '请填写建设项目名称');
            return false;
        }
        projName = whiteSpaceCollapse(projName);
        let engName = $("#eng-name").val().trim();
        if(engName === ''){
            replaceClass($('#eng-name-info'), 'text-info', 'text-danger');
            setDangerInfo($('#eng-name-info'), '请填写单项工程名称');
            return false;
        }
        engName = whiteSpaceCollapse(engName);
        let tenderName = $('#tender-name').val();
        if (tenderName === '') {
            setDangerInfo($('#tender-name-info'), '请填写单位工程名称');
            return false;
        }
        tenderName = whiteSpaceCollapse(tenderName);
        if(hasTender(projTreeObj.tree.selected, projName, engName, tenderName)){
            return false;
        }

        let unitPriceFileObj = getAddTenderFile(tenderName, $('#unit-price'), $("#unit-price").children());
        let feeFileObj = getAddTenderFile(tenderName, $('#tender-fee-rate'), $("#tender-fee-rate").children());

        //let valuation = $("#valuation").val();
        let valuation = curValuation;   //跟建设项目一样的计价规则

        let engineeringName = $("#tender-engineering").val();
        if (!engineeringName || engineeringName === '') {
            setDangerInfo($('#engineering-info'), '请选择工程专业');
            return false;
        }
        let feeName = $('#tender-feeStandard').val();
        if(!feeName || feeName === ''){
            setDangerInfo($('#feeStandard-info'), '请选择费用标准');
            return false;
        }
        //
        //计税方法由原本的跟单位工程绑定，改成跟建设项目绑定，为了减少项目出错几率，新建时保留单位工程的计税方法，值为建设项目的计税方法值
        let taxTypeTender = curTaxType;
        let IDGroup = $("#tender-calcProgram").val();
        if (!IDGroup || IDGroup === '') {
            setDangerInfo($('#calcProgram-info'), '请选择计算程序');
            return false;
        }
        IDGroup = IDGroup.split("|-|");

        let calcProgram = isNaN(parseInt(IDGroup[0]))?IDGroup[0]:parseInt(IDGroup[0]);//转换成整数
        let templateLibID = IDGroup[1];
        let colLibID = IDGroup[2];
        let feeLibID = IDGroup[3];
        if(templateLibID == ''|| colLibID ==''||feeLibID==''){
            alert("工程专业配置有误！");
            return false;
        }
        //如果是新建费率的情况
        if(feeFileObj.id.indexOf("newFeeRate")!=-1) feeFileObj.id +=feeLibID;
        let valuationName = curValuationName;   //跟建设项目一样的计价方式
        let valuationType = curValutionType;    //跟建设项目一样的计价方式

        let engineering = undefined;
        let valuationData = valuationType === 'bill' ? billValuation : rationValuation;
        let engineeringList = [];
        for(let tmp of valuationData) {
            if (tmp.id === valuation) {
                engineeringList = tmp.engineering_list;
                break;
            }
        }
        let libs = getEngineeringLib(engineeringName + feeName, engineeringList);
        if(!libs){
            alert('数据错误，无法确定工程专业库!');
            return false;
        }
        // 一个项目里面，这两个文件必须得有，而界面又没有像费率、单价文件那样给出可选项。所以这里给出提示。
        if (!libs.artificial_lib)  throw '编办没有绑定人工系数标准文件';

        let featureLibID = "",
            progressiveLibID = "";
        if(libs.feature_lib && libs.feature_lib.length > 0) featureLibID = libs.feature_lib[0].id;
        if(libs.progressive_lib && libs.progressive_lib.length > 0) {
            progressiveLibID = libs.progressive_lib[0].id;
        }

        let calcProgramName = $('#tender-calcProgram').children("option:selected").text();
        $.bootstrapLoading.start();
        let callback = function() {
                $("#add-tender-dialog").modal("hide");
                $('#tender-name').val('');
                $("#tender-fee-rate").children("option").removeAttr("selected");
                $("#tender-engineering").children("option").removeAttr("selected");
                $("#tender-calcProgram").children("option").removeAttr("selected");
                $("#poj-name").val('');
                $("#poj-name-info").hide();
                $("#eng-name").val('');
                $("#eng-name-info").hide();
                $.bootstrapLoading.end();
                setTimeout(function () {
                    STATE.addingTender = false;
                }, 500);
                projTreeObj.emitTreeChange();
            },
            errCB = function () {
                $.bootstrapLoading.end();
                setTimeout(function () {
                    STATE.addingTender = false;
                }, 500);
            };
        let selectedItem = projTreeObj.tree.selected;
        //地区
        let region = $('#regionDiv').find('select').val() || commonConstants.DEFAULT_REGION;
        let tenderInfo = {
            gljAdjustType: 'priceInfo', //默认为造价信息差额调整法
            valuation: valuation,
            valuationType: valuationType,
            valuationName: valuationName,
            isInstall: libs.isInstall !== undefined ? libs.isInstall : false,
            isItemIncrease: !!libs.isItemIncrease,
            isAreaIncrease: !!libs.isAreaIncrease,
            engineering: libs.engineering,//定额默认取费专业
            projectEngineering:libs.projectEngineering,//单位工程默认取费专业（造价书中插入量价、工料机时用）
            engineering_id: libs._id,
            engineeringName: engineeringName,
            feeStandardName: feeName,
            unitPriceFile: {name: unitPriceFileObj.name, id: unitPriceFileObj.id},
            feeFile: {name: feeFileObj.name, id: feeFileObj.id},
            calcProgram: {name: calcProgramName, id: calcProgram},
            taxType:taxTypeTender,
            templateLibID:templateLibID,
            colLibID:colLibID,
            featureLibID:featureLibID,
            progressiveLibID:progressiveLibID,
            region: region,
            projectFeature: featureData ? featureData : []
        };
        //导出指标信息
        if(libs.indexName) tenderInfo.indexName = libs.indexName;
        if(libs.engineer_info_lib && libs.engineer_info_lib.length > 0) tenderInfo.engineerInfoLibID = libs.engineer_info_lib[0].id;
        if(libs.engineer_feature_lib && libs.engineer_feature_lib.length > 0) tenderInfo.engineerFeatureLibID = libs.engineer_feature_lib[0].id;
        if(libs.economic_lib && libs.economic_lib.length > 0) tenderInfo.economicLibID = libs.economic_lib[0].id;
        if(libs.main_quantity_lib && libs.main_quantity_lib.length > 0) tenderInfo.mainQuantityLibID = libs.main_quantity_lib[0].id;
        if(libs.material_lib && libs.material_lib.length > 0) tenderInfo.materialLibID = libs.material_lib[0].id;

        AddTenderItems(selectedItem, projName, engName, tenderName, tenderInfo, callback, errCB);

    } catch (error) {
        $('#add-tender-confirm').removeClass('disabled');
        alert(error);
    }
}
/*
* 新增单位工程时选择的文件
* @tenderName {String}
* @selValue {String}
* @options {Array}
* */
function getAddTenderFile(tenderName, selected, options){
    let rst = {name: '', id: ''};
    let selValue = selected.val();
    //选择的是新建单价/费率文件
    if(selValue === ''){
        //若新建的单位工程名称与建设项目下文件重名，则引用该文件
        for(let i = 0; i < options.length; i++){
            if(i === 0){
                continue;
            }
            let option = options[i];
            if($(option).text() === tenderName){
                rst.id = $(option).val();
                break;
            }
        }
        rst.name = tenderName;
    }
    //非新建
    else{
        rst.id = selected.val();
        rst.name =  selected.children("option:selected").text();
    }
    return rst;
}


/**
 * 新增文件夹
 *
 * @return {boolean}
 */
function AddFolder() {
    let name = $('#folder-name').val().trim();
    if (name === '') {
        setDangerInfo($('#folder-name-info'), '请填写文件夹名称');
        return false;
    }

    let selectedItem = projTreeObj.tree.selected;
    let existCallback = function () {
        setDangerInfo($('#folder-name-info'), `已存在“${$("#folder-name").val()}”`);
        STATE.addingFolder = false;
        $.bootstrapLoading.end();
    };
    $.bootstrapLoading.start();
    let sucCallback = function () {
        $('#add-folder-dialog').modal('hide');
        $('#folder-name').val('');
        setDangerInfo($('#folder-name-info'), '', false);
        $.bootstrapLoading.end();
        setTimeout(function () {
            STATE.addingFolder = false;
        }, 500);
        projTreeObj.emitTreeChange();
    };
    let errCB = function () {
        $.bootstrapLoading.end();
        setTimeout(function () {
            STATE.addingFolder = false;
        }, 500);
    };
    if (selectedItem) {
        // 判断是否超过3层
        if(!withinTreble(selectedItem)){
            alert("文件夹不能超过3层");
            return false;
        }
        if(selectedItem.data.projType === projectType.folder || selectedItem.data.projType === projectType.project){
            AddSiblingsItem(null, name, null, projectType.folder, existCallback, sucCallback, errCB);
        }
        else if(selectedItem.data.projType === projectType.engineering || selectedItem.data.projType === projectType.tender){
            let proj = selectedItem.parent.data.projType === projectType.project ? selectedItem.parent : selectedItem.parent.parent;
            AddSiblingsItem(proj, name, null, projectType.folder, existCallback, sucCallback, errCB);
        }
    } else {
        AddSiblingsItem(null, name, null, projectType.folder, existCallback, sucCallback, errCB);
    }
}

function getFolderLevel(selected) {
    let level = 0;
    while(selected && selected.data) {
        if (selected.data.projType === projectType.folder) {
            level++;
        }
        selected = selected.parent;
    }
    return level;
}

// 选中节点及其子项最大文件夹层数
function getMaxFolderLevel(selected) {
    const nodes = [selected, ...selected.getAllChildren()];
    const levels = nodes.map(node => getFolderLevel(node));
    return Math.max(...levels);
}

//判断是否是三层文件夹以内
function withinTreble(selectedItem){
    let rst;
    if(selectedItem.data.projType === projectType.engineering || selectedItem.data.projType === projectType.tender){
        selectedItem = selectedItem.parent.data.projType === projectType.project ? selectedItem.parent : selectedItem.parent.parent;
    }
    if(selectedItem.parent.parent && hasFolder(selectedItem.parent.parent.children) && selectedItem.parent.parent.parent && hasFolder(selectedItem.parent.parent.parent.children)
        && selectedItem.parent.parent.parent.parent && hasFolder(selectedItem.parent.parent.parent.parent.children)){
        return false;
    }
    return true;
    function hasFolder(items){
        for(let i = 0, len = items.length; i < len; i++){
            if(items[i].data.projType === projectType.folder){
                return true;
            }
        }
        return false;
    }
}

/**
 * 组织更新数据
 *
 * @param {Object} parent
 * @param {Object} next
 * @param {String} name
 * @param {Object} type
 * @return {Object}
 */
function GetUpdateData(pre, parent, next, name, property, newId, type) {
    let data = [];
    let updateData = {};

    let rootProjectID = -1;
    if(type.projectType === projectType.tender){
        let rootProject = parent ? parent.parent : projTreeObj.tree._root;
        rootProjectID = rootProject ? rootProject.id() : -1;
        if(property){
            property.rootProjectID=rootProjectID;
        }
    }

    updateData['updateType'] = type.updateType === undefined ? 'new' : type.updateType;
    updateData['updateData'] = {};
    if (newId !== '') {
        updateData['updateData'][projTreeObj.tree.setting.tree.id] = newId;
    }
    updateData['updateData'][projTreeObj.tree.setting.tree.pid] = parent ? parent.id() : -1;
    updateData['updateData'][projTreeObj.tree.setting.tree.nid] = next ? next.id() : -1;
    if (name !== '') {
        updateData['updateData']['name'] = name;
    }
    if (property !== null && property !== undefined) {
        updateData['updateData']['property'] = property;
    }
    if (type !== null && type.projectType !== null) {
        updateData['updateData']['projType'] = type.projectType !== undefined ? type.projectType : 'Tender';
    }
    if(pre){//维护preNode
        let updateObj = Object.create(null);
        updateObj.updateData = Object.create(null);
        updateObj.updateType = 'update';
        updateObj.updateData.ID = pre.id();
        updateObj.updateData.NextSiblingID = newId;
        data.push(updateObj);
    }
    data.push(updateData);
    return data;
}

/**
 * 获取删除数据
 *
 * @return {Object} node
 * @return {Object}
 */
function GetDeleteUpdateData(node) {
    let datas = [], updateData,
        pre = node.preSibling(),
        deleteNodeData = function (node) {
            var data = Object.create(null);
            data['updateType'] = 'delete';
            //data['NextSiblingID'] = node.data.NextSiblingID;
            data['updateData'] = Object.create(null);
            data['updateData'][projTreeObj.tree.setting.tree.id] = node.id();
            data['updateData']['projType'] = node.data.projType;
            if (node.data.projType === 'Tender') {
                data['updateData']['FullFolder'] = GetFullFolder(node.parent);
            }
            return data;
        },
        addDeleteChildren = function (children) {
            children.forEach(function(child){
                datas.push(deleteNodeData(child));
                addDeleteChildren(child.children);
            });
        };
    if (pre && pre.id() !== -1) {
        updateData = {};
        updateData['updateType'] = 'update';
        updateData['updateData'] = {};
        updateData['updateData'][projTreeObj.tree.setting.tree.id] = pre.id();
        updateData['updateData'][projTreeObj.tree.setting.tree.nid] = node ? node.nid() : -1;
        datas.push(updateData);
    }
    datas.push(deleteNodeData(node));
    addDeleteChildren(node.children);
    return datas;
};

/**
 * 获取父级所有名称
 *
 * @return {Array}
 */
function GetFullFolder (node) {
    let fullFolder = [];
    let cur = node;
    while (cur && cur.data) {
        fullFolder.unshift(cur.data.name);
        cur = cur.parent;
    }
    return fullFolder;
}

/**
 * 获取需要更新的前节点
 *
 * @param {Object} parent
 * @param {Object} next
 * @return {Object}
 */
function GetNeedUpdatePreNode(parent, next) {
    if (next) {
        return next.preSibling();
    } else if (parent) {
        return parent.firstChild();
    } else {
        return null;
    }
}

/**
 * 获取最新id
 *
 * @param {function} callback
 * @return {void}
 */
function GetNewProjectId(count, callback, errCB) {
    CommonAjax.post('/pm/api/getNewProjectID', {count: count}, function(data) {
        callback(data);
    }, errCB);
}

/**
 * 重命名项目
 *
 * @param {Number} projectId
 * @param {String} newName
 * @param {Number} parentID
 * @param {function} callback
 * @return {void}
 */
function RenameProject(projectId, newName, parentID, callback) {
    $.ajax({
        type: "POST",
        url: '/pm/api/renameProject',
        data: {'data': JSON.stringify({"user_id": userID, "id": projectId, "newName": newName, "parentID": parentID})},
        dataType: 'json',
        cache: false,
        timeout: 5000,
        success: function(result){
            if (result.error === 0) {
                callback();
            } else {
                if(result.message === '同级目录已存在相同名称数据'){
                    setDangerInfo($('#rename-name-info'), `已存在“${newName}”`);
                }
            }
        },
        error: function(iqXHR, textStatus, errorThrown){
            alert('error ' + textStatus + " " + errorThrown)
        }
    });
}

/**
 * 转换当前树结构为zTree结构
 *
 * @param {Object} Tree
 * @param {Object} zTreeObj
 * @param {Object} filterNode
 * @return {Mixed}
 */
function ConvertTreeToZtree(Tree, zTreeObj, filterNode) {
    let setting = {
        data: {
            simpleData: {
                enable:true,
                idKey: "id",
                pIdKey: "pId",
                rootPId: "-1"
            }
        }};
    let zTreeData = [],
        exportNodesData = function (nodes) {
            nodes.forEach(function (node) {
                if (node !== filterNode) {
                    var data = {};
                    data['id'] = node.data[Tree.setting.tree.id];
                    data['pId'] = node.pid();
                    data['name'] = node.data['name'];
                    data['isParent'] = node.data.projType === 'Folder';//(node.data.projType === 'Folder' && node.children.length === 0);
                    data['open'] = node.data.projType === 'Folder';//node.children.length !== 0;
                    zTreeData.push(data);
                    exportNodesData(node.children);
                }
            })
        };
    exportNodesData(Tree._root.children);
    return $.fn.zTree.init(zTreeObj, setting, zTreeData);
}

/**
 * 获取指定zTree节点
 *
 * @param {Object} zTreeObj
 * @return {object}
 */
function GetTargetTreeNode(zTreeObj) {
    if (!zTreeObj || !projTreeObj.tree) {
        return null;
    }

    let ztree_selected = zTreeObj.getSelectedNodes().length === 0 ? null : zTreeObj.getSelectedNodes()[0];
    return ztree_selected ? projTreeObj.tree.findNode(ztree_selected.id) : null;
}

/**
 * 根据指定id获取对应的工程专业
 *
 * @param {Array} engineeringList
 * @return {String}
 */
function getEngineeringHtml(engineeringList) {
    let result = '';
    if (engineeringList.length <= 0) {
        return result;
    }
    let engLibNames = [];
    for(let i = 0; i < engineeringList.length; i++){
        let tmp = engineeringList[i];
        if(engLibNames.includes(tmp.lib.name)){
           continue;
        }
        result += `<option ${i === 0 ? 'selected' : ''} value="${tmp.lib.name}">${tmp.lib.name}</option>`;
        engLibNames.push(tmp.lib.name);
    }
    return result;
}

/**
 * 远程获取项目属性数据
 *
 * @param {Object} projectInfo
 * @return {void}
 */
function getProperty(projectInfo) {
    if (projectInfo.property === undefined) {
        return;
    }
    projectProperty = projectInfo.property;
    // 写入专业工程相关
    let engineeringHtml = getEngineeringHtml(projectProperty.engineeringList);
    $("#tender-engineering").html(engineeringHtml);

    // 填入计价规则
    let valuationHtml = '<option value="'+ projectProperty.valuation +'">'+ projectProperty.valuationName +'</option>';
    $("#tender-valuation").html(valuationHtml);

    // 选中计价方式
    $("input[name='tender_valuation_type']").attr('disabled', 'disabled').removeAttr('checked', 'checked');
    $("input[name='tender_valuation_type'][value='"+ projectProperty.valuationType +"']")
        .attr("checked", "checked").removeAttr('disabled', 'disabled');
}

/**
 * 获取单价文件
 *
 * @param {Number} parentID
 * @return {void}
 */
function getUnitFile(parentID, callback) {
    parentID = parseInt(parentID);
    if (isNaN(parentID) && parentID <= 0) {
        return;
    }

    $.ajax({
        url: '/pm/api/getUnitFile',
        type: 'post',
        data: {'data': JSON.stringify({"user_id": userID, "parentID": parentID})},
        dataType: 'json',
        error: function() {
            alert('数据传输错误!');
        },
        beforeSend: function() {

        },
        success: function(response) {
            if (response.error === 1) {
                alert('获取失败!');
            } else {
                if(callback){
                    callback(response);
                }
            }
        }
    });

}
/**
 * 获取费率文件
 *
 * @param {Number} parentID
 * @return {void}
 */
function getFeeRateFile(parentID, callback) {
    parentID = parseInt(parentID);
    if (isNaN(parentID) && parentID <= 0) {
        return;
    }

    $.ajax({
        url: '/pm/api/getFeeRateFile',
        type: 'post',
        data: {'data': JSON.stringify({"user_id": userID, "parentID": parentID})},
        dataType: 'json',
        error: function() {
            alert('数据传输错误!');
        },
        beforeSend: function() {

        },
        success: function(response) {
            if (response.error === 1) {
                alert('获取失败!');
            } else {
                if(callback){
                    callback(response);
                }
            }
        }
    });

}


/**
 * 加载数据到侧边栏
 *
 * @return {void}
 */
function setDataToSideBar() {
    // 获取当前点击的数据
    let that = projTreeObj;
    let selectedItem = that.tree.selected;
    while ([projectType.tender, projectType.engineering].includes(selectedItem.data.projType) && selectedItem.parent){
        selectedItem = selectedItem.parent;
    }
    let name = selectedItem.data.name;
    let target = selectedItem.data.projType === projectType.project ? '#summary-project' : '#summary-engineering';
    $(".side-content .p-3").hide();
    $(target).show();

    // 加载单价文件与费率文件
    if (selectedItem.data.projType === projectType.project) {
        let engineeringData = selectedItem.children !== null && selectedItem.children.children !== null ?
            selectedItem.children : [];
        /*if (engineeringData.length <= 0) {
         return;
         }*/
        let unitPriceFileList = [];
        let feeFileList = [];
        let poj_tenders = getProjTenders(selectedItem);
        getUnitFile(selectedItem.data.ID, function (response) {
            unitPriceFileList = unitPriceFileList.concat(response.data);
            $(target + '-unit-price-table tbody').empty();
            set_file_table(target, poj_tenders, unitPriceFileList, fileType.unitPriceFile);
        });
        getFeeRateFile(selectedItem.data.ID, function (response) {
            feeFileList = feeFileList.concat(response.data);
            $(target + '-fee-table tbody').empty();
            set_file_table(target, poj_tenders, feeFileList, fileType.feeRateFile);
        });
    }
}

//获取建设项目的全部单位工程
function getProjTenders(proj) {
    if(proj.data.projType === projectType.tender){
        proj = proj.parent.parent;
    }
    else if(proj.data.projType === projectType.engineering){
        proj = proj.parent;
    }
    let rst = [];
    let engineerings = proj.children || null;
    if (engineerings) {
        for (let i = 0, len = engineerings.length; i < len; i++) {
            let e_tenders = engineerings[i].children || null;
            if (e_tenders && e_tenders.length > 0) {
                rst = rst.concat(e_tenders);
            }
        }
    }
    return rst;
}
//单价、费率文件汇总信息的使用次数、使用该文件的单位工程
function getUsedObj(tenders, fileId, type){
    let rst = Object.create(null), usedCount = 0, usedInfo = '';
    rst.usedCount = 0;
    rst.usedInfo = null;
    for(let i = 0, len = tenders.length; i < len; i++){
        if(tenders[i].data.property){
            let theFile = type === fileType.unitPriceFile ? tenders[i].data.property.unitPriceFile || null : tenders[i].data.property.feeFile || null;
            if(theFile && theFile.id == fileId){
                usedCount ++;
                usedInfo += tenders[i].data.name + '<br>';
            }
        }
    }
    if(usedCount > 0){
        usedInfo = usedInfo.slice(0, usedInfo.length - 4);
        rst.usedCount = usedCount;
        rst.usedInfo = usedInfo;
    }
    return rst;
}

//单价、费率文件汇总界面交互
function bindEvents_file_table(jqS, usedObj, targetBody, type){
    //悬浮显示删除和重命名按钮
    $(jqS).hover(function(){
        $('p',this).show();
    },function(){
        $('p', this).hide();
    });
    //删除
    if(usedObj.usedCount > 0){//不可删除
        $(jqS + ' p a:eq(0)').addClass('disabled');
        $(jqS + ' p a:eq(0)').removeAttr('data-target');
    }
    else {
        $(jqS + ' p a:eq(0)').on('click', function () {
            let dispName = $(jqS + ' div:eq(0)')[0].childNodes[0].textContent;
            //刷新删除弹出框内容
            let delData = '删除"' + dispName + '"？';
            $('#del-wj .modal-body h5').text(delData);
            let attrId = $(jqS).attr('id');
            let id = attrId.slice(5, attrId.length);
            if(type === fileType.unitPriceFile){
                id = parseInt(id);
            }
            let obj = Object.create(null);
            obj.fileType = type;
            obj.id = id;
            fileDelObj = obj;
        });
    }
    //重命名
    let fileObjs = getFileObj(targetBody, type),
        fileDiv = $(jqS + ' div:eq(0)'),
        renameDiv = $(jqS + ' div:eq(1)'),
        hintText = $(jqS).find('span'),
        postFix = '';
    $(jqS + ' p a:eq(1)').on('click', function () {
        let orgDispName = $(jqS + ' div:eq(0)')[0].childNodes[0].textContent;
        let orgName = orgDispName;
        $(jqS + ' input').val(orgName);
        fileDiv.hide();
        renameDiv.show();
        $(jqS).find('input:eq(0)').focus();
        $(jqS).find('input:eq(0)').blur(function () {
            fileDiv.show();
            renameDiv.hide();
            hintText.hide();
        });
    });
    //回车键确认重命名
    $(jqS).find('input:eq(0)').keypress(function (e) {
        if(e.keyCode === 13){
            let orgName = $(jqS + ' div:eq(0)')[0].childNodes[0].textContent;
            let attrId = $(jqS).attr('id');
            let id = attrId.slice(5, attrId.length);
            let newName = $(jqS + ' input').val().trim();
            if(newName !== orgName){
                if(hasThisFileName(fileObjs, newName)){
                    hintText.show();
                    return;
                }
                if(newName.trim().length === 0){
                    alert('文件名不可为空！');
                    $(jqS + ' input').val(orgName);
                    return;
                }
                //ajax
                let updateObj = Object.create(null);
                updateObj.fileType = type;
                updateObj.updateType = 'update';
                updateObj.updateData = Object.create(null);
                if(type === fileType.unitPriceFile){
                    updateObj.updateData.id = parseInt(id);
                }
                else if(type === fileType.feeRateFile){
                    updateObj.updateData.ID = id;
                }
                updateObj.updateData.name = newName;
                a_updateFiles([updateObj], function () {
                    let newDispName = newName + postFix;
                    fileDiv[0].childNodes[0].textContent = newDispName;
                    fileDiv.show();
                    renameDiv.hide();
                    //refresh tender
                    refreshTenderFile(getTendersByFile(type, id, projTreeObj.tree.selected), type, newName);
                });
            }
            let newDispName = newName + postFix;
            fileDiv[0].childNodes[0].textContent = newDispName;
            fileDiv.show();
            renameDiv.hide();
            hintText.hide();
        }
    });
    //悬浮框显示使用该文件的单位工程
    $($(jqS)[0].nextSibling).popover({
            placement:"bottom",
            html:true,
            trigger:"hover", //| focus.
            content: usedObj.usedInfo ? usedObj.usedInfo : ''
        }
    );
}

//更新单价、费率文件（删除、重命名）
function a_updateFiles(updateDatas, callback){
    $.ajax({
        type: 'post',
        url: '/pm/api/updateFiles',
        data: {data: JSON.stringify({user_id: userID, updateDatas: updateDatas})},
        dataType: 'json',
        success: function (result){
            if(!result.error && callback){
                callback();
            }
        }
    })
}

function set_file_table(target, poj_tenders, fileList, type){
    let fileCounter = 1;
    for(let i = 0, len = fileList.length; i < len; i++){
        let fileId = type === fileType.unitPriceFile ? fileList[i].id : fileList[i].ID;
        let usedObj = getUsedObj(poj_tenders, fileId, type);
        let usedHtml = usedObj.usedCount > 0 ?  '<td class="text-center"><a href="javascript:void(0);">' + usedObj.usedCount + '</a></td>' : '<td class="text-center">' + usedObj.usedCount + '</td>';
        let unitPriceEditHtml = type === fileType.unitPriceFile? `<a class="btn btn-sm" href="/unitPrice/index/${fileId}" target="_">编辑</a>`:"";
        let hoverHtml = `<p style="display: none; height: 14px;"><a class="btn btn-sm" href="javascript:void(0);" data-toggle="modal" data-target="#del-wj">删除</a><a class="btn btn-sm" href="javascript:void(0);">重命名</a>${unitPriceEditHtml}</p></div>`;
        let renHtml = '<div class="input-group" style="display: none;">'
            + '<input class="form-control form-control-sm" value="">'

            + '</div>'
            + '<span class="form-text text-danger" style="display: none">本建设项目已存在该文件名，请重新输入！' +
            '</span></td>';
        let fileTypeStr = type === fileType.unitPriceFile ? '单价文件' : '费率文件';
        let fileHtml = '<tr><td class="text-center">' + fileCounter + '</td><td id="file_' + fileId + '"><div>' + fileList[i].name + hoverHtml + renHtml + usedHtml + '</tr>';
        fileCounter++;
        let targetBody = type === fileType.unitPriceFile ? target + '-unit-price-table tbody' : target + '-fee-table tbody';
        $(targetBody).append(fileHtml);
        let jqS = '#file_' + fileId;
        bindEvents_file_table(jqS, usedObj, targetBody, type);
    }
}

function getFileObj(jqS, type){
    let rst = [];
    let trs = $('tr', jqS);
    for(let i = 0, len = trs.length; i < len; i++){
        let td = $('td:eq(1)', trs[i])[0];
        let name = td.childNodes[0].childNodes[0].textContent;
        let attrId = $(td).attr('id');
        let id = attrId.slice(5, attrId.length);
        if(type === fileType.unitPriceFile){
            id = parseInt(id);
        }
        let obj = Object.create(null);
        obj.id = id;
        obj.name = name;
        rst.push(obj);
    }
    return rst;
    //let orgDispName = $(jqS + ' div:eq(0)')[0].childNodes[0].textContent;
}

function hasThisFileName(fileObjs, name){
    for(let i = 0, len = fileObjs.length; i < len; i++){
        if(fileObjs[i].name === name){
            return true;
        }
    }
    return false;
}

//获得使用此单价、费率文件的项目节点
function getTendersByFile(type, fileId, project){
    let rst = [];
    let tenders = getProjTenders(project);
    for(let tender of tenders){
        if(type === fileType.unitPriceFile && tender.data.property && tender.data.property.unitPriceFile){
            if(fileId == tender.data.property.unitPriceFile.id){
                rst.push(tender);
            }
        }
        else if(type === fileType.feeRateFile && tender.data.property && tender.data.property.feeFile){
            if(fileId == tender.data.property.feeFile.id){
                rst.push(tender);
            }
        }
    }
    return rst;
}

//重命名单价、费率文件后，刷新使用此文件的节点
function refreshTenderFile(tenders, type, newName){
   projTreeObj.renderSheetFuc(projTreeObj.workBook.getActiveSheet(), function () {
       for(let tender of tenders){
           if(type === fileType.unitPriceFile){
               tender.data.property.unitPriceFile.name = newName;
           }
           else if(type === fileType.feeRateFile){
               tender.data.property.feeFile.name = newName;
           }
           projTreeObj.refreshNodeData(tender);
       }
   });
}

//批量替换文件，切换建设项目
$('#otherProject').change(function(){
    let optionList = [],idField = 'ID';
    var newVal = $(this).val();
    var projects = projTreeObj.changeInfo.others;
    var selected = _.find(projects,{ID:parseInt(newVal)});
    if($("#mr_from").val() =="unitPriceFile"){
        idField = 'id';
        optionList = selected.unitPriceList;
    }else {
        optionList =  selected.optionList;
    }
    $('#otherFileOptions').empty();
    for(let f of optionList){
        let option =  $("<option>").val(f[idField]).text(f.name);
        $('#otherFileOptions').append(option);
    }
});

$("#confirm-import").click(function() {
    //$.bootstrapLoading.start();
    if (STATE.importing) {
        return;
    }
    STATE.importing = true;

    let input = $("input[name='import_project_data']")[0];
    if (input.files.length <= 0) {
        throw '请选择文件!';
    }
    let token = projTreeObj.uptoken;
    $('#import').modal("hide");
    $.bootstrapLoading.progressStart("上传文件中",true);
    let file = input.files[0];
    let key = uuid.v1() + ".ybp"; //file.name;
    if (file) {
        const callback = () => {
            $("#progress_modal_body").text("正在导入建设项目");
            startImportProject(key);
            projTreeObj.uptoken = null;
        };
        UPLOAD_CDN.upload(file, key, token, callback);
    }

    async function  startImportProject(key) {
        try {
            let result = await ajaxPost("/pm/api/importProject",{key:key,updateData:projTreeObj.getImportProjectDate()});
            importProcessChecking(key, null, (projectData) => handleProjectAfterChecking(projectData));
        }catch (error){
            alert(error);
        }finally {
            STATE.importing = false;
        }
    }
});

$("#import_project_data").change(function(){
    let file = $(this)[0];
    let projectFile = file.files[0];
    if(projectFile) {
        let ybpReg = /ybp$/g;
        if(projectFile.name && ybpReg.test(projectFile.name)){
            $('#import_project_label').text(`${projectFile.name}`);
            $('#confirm-import').removeAttr("disabled");
        }else {
            alert("请选择ybp项目文件");
            $(this).val('');
            $('#confirm-import').attr("disabled","disabled");
        }
    }
});

//清空导入清单选择文件
$('#import').on('show.bs.modal', function(){
    $('#import_project_data').val('');
    $('.custom-file-label').text(`请选择建设项目文件`);
});


//刷新建设项目汇总金额信息
function refreshProjSummary(project, summaryInfo) {
    let refreshNodes = [];
    refreshNodes.push(project);
    getNodes(project);
    function getNodes(node) {
        if(node.children.length > 0){
            refreshNodes = refreshNodes.concat(node.children);
            for(let cNode of node.children){
                getNodes(cNode);
            }
        }
    }
    for(let node of refreshNodes){
        let nodeInfo = summaryInfo[node.data.ID];
        if(nodeInfo){
            node.data.engineeringCost = nodeInfo.engineeringCost;
            node.data.subEngineering = nodeInfo.subEngineering;
            node.data.measure = nodeInfo.measure;
            node.data.safetyConstruction = nodeInfo.safetyConstruction;
            node.data.other = nodeInfo.other;
            node.data.charge = nodeInfo.charge;
            node.data.tax = nodeInfo.tax;
            node.data.rate = nodeInfo.rate;
            node.data.buildingArea = nodeInfo.buildingArea;
            node.data.perCost = nodeInfo.perCost;
            node.data.changeMark = nodeInfo.changeMark;
            if(nodeInfo.property) node.data.property = nodeInfo.property;
        }
    }
    projTreeObj.refreshNodeData(refreshNodes);
}



$(function () {
    if(isShow)  $('#welcomePage').modal('show');//是否显示欢迎页
    $('#importChongqing').click(async function () {
      await  projTreeObj.importExampleProjects(true);
    })
});

// 导入检查完成时，对新增建设项目的处理
function handleProjectAfterChecking(projectData) {
    if (!projectData) {
        return;
    }
    const rootData = projectData.find(item => item.projType === projectType.project);
    const sorted = commonUtil.getSortedTreeData(rootData.ParentID, projectData);
    importView.doAfterImport(sorted);
    projTreeObj.emitTreeChange();
}
// 导入检查完成时，对新增单位工程的处理
function handleTenderAfterChecking(projectData, orgTender) {
    if (!projectData) {
        return;
    }
    const tenderData = {...orgTender, ...projectData[0]};
    const parent = projTreeObj.tree.findNode(tenderData.ParentID);
    const next = projTreeObj.tree.findNode(tenderData.NextSiblingID);
    const newNode = projTreeObj.insert(tenderData, parent, next);
    const refreshNodes = projTreeObj.calEngineeringCost(newNode);
    projTreeObj.refreshNodeData(refreshNodes);
    projTreeObj.emitTreeChange();
}

async function importProcessChecking(key, processingFunc = null, completeFunc = null, immediately = false) {
    let count = 0;
    immediately ? checking() : setTimeout(checking, 2000);
    async function checking() {
        let result = await ajaxPost("/pm/api/importProcessChecking", { key: key, user_id: userID });
        if (result.error == 1) {
            let message = result.msg ? result.msg : result.message;
            setTimeout(function () {
                $.bootstrapLoading.progressEnd();//不做这个的话太快，页面不会自动关闭
            }, 500);
            alert(message);
            if (completeFunc) {
                completeFunc(result.data);
            }
        } else if (result.error == 0) {
            if (result.status == "processing") {
                // 只调用一次
                if (processingFunc && count === 0) {
                    processingFunc(result);
                }
                count++;
                setTimeout(checking, 2000);
            } else if (result.status == "complete") {
                if (completeFunc) {
                    completeFunc(result.data);
                }
                $.bootstrapLoading.progressEnd();
                //refreshAllPage();
            }
        }
    }
}