/**
 * 台账相关js
 *
 * @author Mai
 * @date 2018/02/05
 * @version
 */
const ckBillsSpread = window.location.pathname + '-billsSelect';
function checkTzMeasureType () {
    return tender.measure_type === measureType.tz.value;
}

function getTenderId() {
    return window.location.pathname.split('/')[2];
}

const copyBlockTag = 'zh.calc.copyBlock';

$(document).ready(function() {
    autoFlashHeight();
    // 初始化台账
    const ledgerSpread = SpreadJsObj.createNewSpread($('#ledger-spread')[0]);
    SpreadJsObj.addDeleteBind(ledgerSpread);
    const treeSetting = {
        id: 'ledger_id',
        pid: 'ledger_pid',
        order: 'order',
        level: 'level',
        rootId: -1,
        keys: ['id', 'tender_id', 'ledger_id'],
        preUrl: '/tender/' + getTenderId() + '/ledger',
    };
    if (checkTzMeasureType()) {
        treeSetting.calcFields = ['sgfh_tp', 'sjcl_tp', 'qtcl_tp', 'total_price'];
    } else {
        treeSetting.calcFields = ['deal_tp', 'sgfh_tp', 'sjcl_tp', 'qtcl_tp', 'total_price'];
    }
    treeSetting.calcFun = function (node) {
        node.dgn_price = ZhCalc.round(ZhCalc.div(node.total_price, node.dgn_qty1), 2);
    };
    const ledgerTree = createNewPathTree('ledger', treeSetting);
    ledgerTree.loadDatas(ledger);
    treeCalc.calculateAll(ledgerTree);
    ledgerTreeCol.initSpreadSetting(ledgerSpreadSetting);
    SpreadJsObj.initSheet(ledgerSpread.getActiveSheet(), ledgerSpreadSetting);
    // 加载台账数据到界面
    SpreadJsObj.loadSheetData(ledgerSpread.getActiveSheet(), 'tree', ledgerTree);
    SpreadJsObj.loadTopAndSelect(ledgerSpread.getActiveSheet(), ckBillsSpread);
    // 初始化 部位明细
    const pos = new PosData({
        id: 'id', ledgerId: 'lid',
    });
    const posSpread = SpreadJsObj.createNewSpread($('#pos-spread')[0]);

    // 定义事件
    const treeOperationObj = {
        getSelectNode: function (sheet) {
            if (!sheet || !sheet.zh_tree) {
                return null;
            } else {
                const sel = sheet.getSelections()[0];
                return sheet.zh_tree.nodes[sel.row];
            }
        },
        /**
         * 刷新顶部按钮是否可用
         * @param sheet
         * @param selections
         */
        refreshOperationValid: function (sheet, selection) {
            const setObjEnable = function (obj, enable) {
                if (enable) {
                    obj.removeClass('disabled');
                } else {
                    obj.addClass('disabled');
                }
            };

            const sel = selection ? selection[0] : sheet.getSelections()[0];
            const row = sel ? sel.row : -1;
            const tree = sheet.zh_tree;
            if (!tree) { return; }
            const node = sheet.zh_tree.nodes[row];
            const preNode = tree.getPreSiblingNode(node);
            const valid = !sheet.zh_setting.readOnly;

            setObjEnable($('#insert'), valid && node && node.level > 1);
            setObjEnable($('#delete'), valid && node && node.level > 1);
            setObjEnable($('#up-move'), valid && node && node.level > 1 && preNode);
            setObjEnable($('#down-move'), valid && node && node.level > 1 && !tree.isLastSibling(node));
            if (checkTzMeasureType()) {
                const posRange = node ? pos.getLedgerPos(node.id) : [];
                setObjEnable($('#up-level'), valid && node && tree.getParent(node) && node.level > 2 && (!posRange || posRange.length === 0));
                const preNodePosRange = preNode ? pos.getLedgerPos(preNode.id) : [];
                setObjEnable($('#down-level'), valid && node && node.level > 1 && preNode && (!preNodePosRange || preNodePosRange.length === 0));
            } else {
                setObjEnable($('#up-level'), valid && node && node.level > 2 && tree.getParent(node));
                setObjEnable($('#down-level'), valid && node && node.level > 1 && preNode);
            }
            setObjEnable($('#cut'), valid);
            setObjEnable($('#paste'), valid);
        },
        refreshTree: function (sheet, data) {
            SpreadJsObj.massOperationSheet(sheet, function () {
                const tree = sheet.zh_tree;
                // 处理删除
                if (data.delete) {
                    for (const d of data.delete) {
                        sheet.deleteRows(tree.nodes.indexOf(d), 1);
                    }
                }
                // 处理新增
                if (data.create) {
                    const newNodes = data.create;
                    if (newNodes) {
                        newNodes.sort(function (a, b) {
                            return a.index - b.index;
                        });

                        for (const node of newNodes) {
                            sheet.addRows(node.index, 1);
                            SpreadJsObj.reLoadRowData(sheet, tree.nodes.indexOf(node), 1);
                        }
                    }
                }
                // 处理更新
                if (data.update) {
                    const rows = [];
                    for (const u of data.update) {
                        rows.push(tree.nodes.indexOf(u));
                    }
                    SpreadJsObj.reLoadRowsData(sheet, rows);
                }
                // 处理展开
                if (data.expand) {
                    const expanded = [];
                    for (const e of data.expand) {
                        if (expanded.indexOf(e) === -1) {
                            const posterity = tree.getPosterity(e);
                            for (const p of posterity) {
                                sheet.setRowVisible(tree.nodes.indexOf(p), p.visible);
                                expanded.push(p);
                            }
                        }
                    }
                }
            });
        },
        /**
         * 新增节点
         * @param spread
         */
        addNode: function (spread) {
            const self = this;
            const sheet = spread.getActiveSheet();
            const row = sheet.getSelections()[0].row;

            const tree = sheet.zh_tree;
            if (!tree) { return; }

            const node = sheet.zh_tree.nodes[row];
            if (!node) { return; }

            SpreadJsObj.massOperationSheet(sheet, function () {
                tree.baseOperation('/tender/' + getTenderId() + '/ledger/base-operation', node, 'add', function (result) {
                    self.refreshTree(sheet, result);
                    self.refreshOperationValid(sheet);
                });
            });
        },
        /**
         * 删除选中节点
         * @param spread
         */
        deleteNode: function (spread) {
            const self = this;
            const sheet = spread.getActiveSheet();
            const row = sheet.getSelections()[0].row;

            const tree = sheet.zh_tree;
            if (!tree) { return; }

            const node = sheet.zh_tree.nodes[row];
            if (!node) { return; }

            const count = ledgerTree.getPosterity(node).length;
            tree.baseOperation('/tender/' + getTenderId() + '/ledger/base-operation', node, 'delete', function (result) {
                //treeOperationObj.refreshTree(sheet, result);
                sheet.deleteRows(row, count + 1);
                for (const data of result.update) {
                    SpreadJsObj.reLoadRowData(sheet, tree.nodes.indexOf(data), tree.getPosterity(data).length + 1);
                }
                self.refreshOperationValid(sheet);
                for (const data of result.delete) {
                    pos.removeDatasByMasterId(data.id);
                }
                posOperationObj.loadCurPosData();
            });
        },
        /**
         * 上移选中节点
         * @param spread
         */
        upMove: function (spread) {
            const self = this;
            const sheet = spread.getActiveSheet();
            const sel = sheet.getSelections()[0];
            const row = sel.row;

            const tree = sheet.zh_tree;
            if (!tree) { return; }

            const node = tree.nodes[row];
            if (!node) { return; }

            tree.baseOperation('/tender/' + getTenderId() + '/ledger/base-operation', node, 'up-move', function (result) {
                self.refreshTree(sheet, result);
                sheet.setSelection(tree.nodes.indexOf(node), sel.col, sel.rowCount, sel.colCount);
                self.refreshOperationValid(sheet);
            });

        },
        /**
         * 下移选中节点
         * @param spread
         */
        downMove: function (spread) {
            const self = this;
            const sheet = spread.getActiveSheet();
            const sel = sheet.getSelections()[0];
            const row = sel.row;

            const tree = sheet.zh_tree;
            if (!tree) { return; }

            const node = tree.nodes[row];
            if (!node) { return; }

            tree.baseOperation('/tender/' + getTenderId() + '/ledger/base-operation', node, 'down-move', function (result) {
                self.refreshTree(sheet, result);
                sheet.setSelection(tree.nodes.indexOf(node), sel.col, sel.rowCount, sel.colCount);
                self.refreshOperationValid(sheet);
            });

        },
        /**
         * 升级选中节点
         * @param spread
         */
        upLevel: function (spread) {
            const self = this;
            const sheet = spread.getActiveSheet();
            const row = sheet.getSelections()[0].row;

            const tree = sheet.zh_tree;
            if (!tree) { return; }

            const node = tree.nodes[row];
            if (!node) { return; }

            tree.baseOperation('/tender/' + getTenderId() + '/ledger/base-operation', node, 'up-level', function (result) {
                self.refreshTree(sheet, result);
                self.refreshOperationValid(sheet);
            });

        },
        /**
         * 降级选中节点
         * @param spread
         */
        downLevel: function (spread) {
            const self = this;
            const sheet = spread.getActiveSheet();
            const row = sheet.getSelections()[0].row;

            const tree = sheet.zh_tree;
            if (!tree) { return; }

            const node = tree.nodes[row];
            if (!node) { return; }

            tree.baseOperation('/tender/' + getTenderId() + '/ledger/base-operation', node, 'down-level', function (result) {
                self.refreshTree(sheet, result);
                self.refreshOperationValid(sheet);
            });
        },
        /**
         * 编辑单元格响应事件
         * @param {Object} e
         * @param {Object} info
         */
        editEnded: function (e, info) {
            if (info.sheet.zh_setting) {
                const col = info.sheet.zh_setting.cols[info.col];
                const sortData = info.sheet.zh_dataType === 'tree' ? info.sheet.zh_tree.nodes : info.sheet.zh_data;
                const node = sortData[info.row];
                const data = {
                    id: node.id,
                    tender_id: node.tender_id,
                    ledger_id: node.ledger_id
                };
                // 未改变值则不提交
                const orgValue = node[col.field];
                if (orgValue == info.editingText || ((!orgValue || orgValue === '') && (info.editingText === ''))) {
                    return;
                }
                // 台账模式，检查部位明细相关
                if (checkTzMeasureType()) {
                    if (col.field === 'sgfh_qty' || col.field === 'sgfh_tp' ||
                        col.field === 'sjcl_qty' || col.field === 'sjcl_tp' ||
                        col.field === 'qtcl_qty' || col.field === 'qtcl_tp') {
                        if (!node.children || node.children.length ===0) {
                            const lPos = pos.getLedgerPos(node.id);
                            if (lPos && lPos.length > 0) {
                                toast('清单含有部位明细，请在部位明细输入数量', 'error');
                                SpreadJsObj.reLoadRowData(info.sheet, info.row);
                                return;
                            }
                        }
                    }
                    if (col.field === 'b_code' && (info.editingText === '' || !info.editingText)) {
                        const lPos = pos.getLedgerPos(node.id);
                        if (lPos && lPos.length > 0) {
                            toast('清单含有部位明细，请先删除部位明细，再删除清单编号', 'error');
                            SpreadJsObj.reLoadRowData(info.sheet, info.row);
                            return;
                        }
                    }
                }
                // 获取更新数据
                if (info.editingText) {
                    data[col.field] = col.type === 'Number' ? parseFloat(info.editingText) : info.editingText.replace('\n', '');
                } else {
                    data[col.field] = null;
                }
                // 更新至服务器
                info.sheet.zh_tree.update('/tender/' + getTenderId() + '/ledger/update', data, function (result) {
                    treeOperationObj.refreshTree(info.sheet, result);
                });
            }
        },
        /**
         * 粘贴单元格响应事件
         * @param e
         * @param info
         */
        clipboardPasted: function (e, info) {
            if (info.sheet.zh_setting && info.sheet.zh_dataType === 'tree') {
                const tree = info.sheet.zh_tree;
                if (!tree) { return; }

                const sortData = info.sheet.zh_tree.nodes;
                const datas = [], filterNodes = [];
                let bHint = false, bPaste;

                for (let iRow = 0; iRow < info.cellRange.rowCount; iRow ++) {
                    bPaste = false;
                    const curRow = info.cellRange.row + iRow;
                    const node = sortData[curRow];
                    if (node) {
                        const data = info.sheet.zh_tree.getNodeKeyData(node);
                        for (let iCol = 0; iCol < info.cellRange.colCount; iCol++) {
                            const curCol = info.cellRange.col + iCol;
                            const colSetting = info.sheet.zh_setting.cols[curCol];
                            const value = info.sheet.getText(curRow, curCol).replace('\n', '');
                            const lPos = pos.getLedgerPos(node.id);
                            if (lPos && lPos.length > 0) {
                                if (value === '' && colSetting.field === 'b_code') {
                                    if (!bHint) {
                                        toast('清单含有部位明细，请先删除部位明细，再删除清单编号', 'warning');
                                        bHint = true;
                                    }
                                    continue;
                                }
                                if (colSetting.field === 'sgfh_qty' || colSetting.field === 'sgfh_tp' ||
                                    colSetting.field === 'sjcl_qty' || colSetting.field === 'sjcl_tp' ||
                                    colSetting.field === 'qtcl_qty' || colSetting.field === 'qtcl_tp') {
                                    if (!bHint) {
                                        toast('清单含有部位明细，数量金额根据部位明细汇总计算所得，不可编辑', 'warning');
                                        bHint = true;
                                    }
                                    continue;
                                }
                            }
                            data[colSetting.field] = value;
                            bPaste = true;
                        }
                        if (bPaste) {
                            datas.push(data);
                        } else {
                            filterNodes.push(node);
                        }
                    }
                }
                if (datas.length > 0) {
                    info.sheet.zh_tree.update('/tender/' + getTenderId() + '/ledger/update', datas, function (result) {
                        if (result.update) {
                            result.update = result.update.concat(filterNodes);
                        }
                        treeOperationObj.refreshTree(info.sheet, result);
                    }, function () {
                        SpreadJsObj.reLoadRowData(info.sheet, info.cellRange.row, info.cellRange.rowCount);
                    });
                } else {
                    SpreadJsObj.reLoadRowData(info.sheet, info.cellRange.row, info.cellRange.rowCount);
                }
            }
        },
        /**
         * 删除按钮响应事件
         * @param sheet
         */
        deletePress: function (sheet) {
            if (sheet.zh_setting && sheet.zh_dataType === 'tree') {
                const tree = sheet.zh_tree;
                if (!tree) { return; }

                const sortData = sheet.zh_tree.nodes;
                const datas = [], nodes = [];
                const sel = sheet.getSelections()[0];
                let bHint = false;
                for (let iRow = sel.row; iRow < sel.row + sel.rowCount; iRow++) {
                    const node = sortData[iRow];
                    if (node) {
                        let bDel = false;
                        const data = sheet.zh_tree.getNodeKeyData(node);
                        for (let iCol = sel.col; iCol < sel.col + sel.colCount; iCol++) {
                            const col = sheet.zh_setting.cols[iCol];
                            if (col.field === 'b_code' || col.field === 'sgfh_qty' || col.field === 'sgfh_tp' ||
                                col.field === 'sjcl_qty' || col.field === 'sjcl_tp' ||
                                col.field === 'qtcl_qty' || col.field === 'qtcl_tp') {
                                const lPos = pos.getLedgerPos(node.id);
                                if (lPos && lPos.length > 0) {
                                    if (!bHint) {
                                        if (col.field === 'code') {
                                            toast('清单含有部位明细，请先删除部位明细，再删除清单编号', 'warning');
                                        } else {
                                            toast('清单含有部位明细，数量金额根据部位明细汇总计算所得，不可删除', 'warning');
                                        }
                                        bHint = true;
                                    }
                                    continue;
                                }
                            }
                            const style = sheet.getStyle(iRow, iCol);
                            if (!style.locked) {
                                const colSetting = sheet.zh_setting.cols[iCol];
                                data[colSetting.field] = null;
                                bDel = true;
                            }
                        }
                        if (bDel) {
                            datas.push(data);
                            nodes.push(node);
                        }
                    }
                }
                if (datas.length > 0) {
                    sheet.zh_tree.update('/tender/' + getTenderId() + '/ledger/update', datas, function (result) {
                        treeOperationObj.refreshTree(sheet, result);
                    });
                }
            }
        },
        /**
         * 粘贴整块
         * @param spread
         * @param block
         */
        pasteBlock: function (spread, copyInfo) {
            const self = this;
            const sheet = spread.getActiveSheet();
            const row = sheet.getSelections()[0].row;

            const tree = sheet.zh_tree;
            if (!tree) { return; }

            const node = tree.nodes[row];
            if (!node) { return; }

            postData('/tender/' + getTenderId() + '/ledger/paste-block', {
                id: node[tree.setting.id],
                tid: copyInfo.tid,
                block: copyInfo.block,
            }, function (data) {
                pos.updateDatas(data.pos);
                const result = tree.loadPostData(data.ledger);
                self.refreshTree(sheet, result);
                self.refreshOperationValid(sheet);
                removeLocalCache(copyBlockTag);
            });
        },
        selectionChanged: function (e, info) {
            if (!info.oldSelections[0] || info.newSelections[0].row !== info.oldSelections[0].row) {
                posOperationObj.loadCurPosData();
                SpreadJsObj.resetTopAndSelect(posSpread.getActiveSheet());
                posSearch.search($('#pos-keyword').val());
            }
            SpreadJsObj.saveTopAndSelect(info.sheet, ckBillsSpread);
        },
        topRowChanged(e, info) {
            SpreadJsObj.saveTopAndSelect(info.sheet, ckBillsSpread);
        }
    };
    // 绑定事件
    ledgerSpread.bind(GC.Spread.Sheets.Events.SelectionChanged, treeOperationObj.selectionChanged);
    ledgerSpread.bind(spreadNS.Events.TopRowChanged, treeOperationObj.topRowChanged);
    if (!ledgerSpreadSetting.readOnly) {
        ledgerSpread.bind(GC.Spread.Sheets.Events.SelectionChanged, function (e, info) {
            treeOperationObj.refreshOperationValid(info.sheet, info.newSelections);
        });
        ledgerSpread.bind(GC.Spread.Sheets.Events.EditEnded, treeOperationObj.editEnded);
        ledgerSpread.bind(GC.Spread.Sheets.Events.ClipboardPasted, treeOperationObj.clipboardPasted);
        SpreadJsObj.addDeleteBind(ledgerSpread, treeOperationObj.deletePress);
        ledgerSpread.bind(GC.Spread.Sheets.Events.ClipboardChanging, function (e, info) {
            console.log(info);
            const copyText = SpreadJsObj.getFilterCopyText(info.sheet);
        });
        ledgerSpread.bind(GC.Spread.Sheets.Events.ClipboardChanged, function (e, info) {
            console.log(info.copyData.text);
        });
        ledgerSpread.bind(GC.Spread.Sheets.Events.ClipboardPasting, function (e, info) {
        });

        // 绑定 删除等 顶部按钮
        $('#insert').click(() => {
            treeOperationObj.addNode(ledgerSpread);
        });
        $('#delete').click(function () {
            treeOperationObj.deleteNode(ledgerSpread);
        });
        $('#up-move').click(function () {
            treeOperationObj.upMove(ledgerSpread);
        });
        $('#down-move').click(function () {
            treeOperationObj.downMove(ledgerSpread);
        });
        $('#up-level').click(function () {
            treeOperationObj.upLevel(ledgerSpread);
        });
        $('#down-level').click(function () {
            treeOperationObj.downLevel(ledgerSpread);
        });

        let batchInsertObj;
        // 右键菜单
        $.contextMenu({
            selector: '#ledger-spread',
            build: function ($trigger, e) {
                const target = SpreadJsObj.safeRightClickSelection($trigger, e, ledgerSpread);
                return target.hitTestType === GC.Spread.Sheets.SheetArea.viewport || target.hitTestType === GC.Spread.Sheets.SheetArea.rowHeader;
            },
            items: {
                'create': {
                    name: '新增',
                    icon: 'fa-sign-in',
                    callback: function (key, opt) {
                        treeOperationObj.addNode(ledgerSpread);
                    },
                    visible: function(key, opt){
                        const sheet = ledgerSpread.getActiveSheet();
                        const selection = sheet.getSelections();
                        const row = selection[0].row;
                        const select = ledgerTree.nodes[row];
                        return select;
                    }
                },
                'delete': {
                    name: '删除',
                    icon: 'fa-remove',
                    callback: function (key, opt) {
                        treeOperationObj.deleteNode(ledgerSpread);
                    },
                    visible: function (key, opt) {
                        const sheet = ledgerSpread.getActiveSheet();
                        const selection = sheet.getSelections();
                        const row = selection[0].row;
                        const select = ledgerTree.nodes[row];
                        return select;
                    }
                },
                'copyBlock': {
                    name: '复制整块',
                    icon: 'fa-files-o',
                    callback: function (key, opt) {
                        /*ledgerSpread.commandManager().execute({
                            cmd:"copy",
                            sheetName:ledgerSpread.getActiveSheet().name()
                        });*/
                        treeOperationObj.block = [];
                        const copyBlockList = [];
                        const sheet = ledgerSpread.getActiveSheet();
                        const sel = sheet.getSelections()[0];
                        let iRow = sel.row;
                        const pid = sheet.zh_tree.nodes[iRow].ledger_pid;
                        while (iRow < sel.row + sel.rowCount) {
                            const node = sheet.zh_tree.nodes[iRow];
                            if (node.ledger_pid !== pid) {
                                toast('error: 仅可同时选中同层节点', 'error', 'exclamation-circle');
                                return;
                            }
                            copyBlockList.push(node.ledger_id);
                            iRow += sheet.zh_tree.getPosterity(node).length + 1;
                        }
                        const tenderId = _.toInteger(getTenderId());
                        setLocalCache(copyBlockTag, JSON.stringify({tid: tenderId, block: copyBlockList}));
                        //treeOperationObj.block = copyBlockList;
                    },
                    visible: function (key, opt) {
                        const sheet = ledgerSpread.getActiveSheet();
                        const selection = sheet.getSelections();
                        const row = selection[0].row;
                        const select = ledgerTree.nodes[row];
                        return select;
                    }
                },
                'pasteBlock': {
                    name: '粘贴整块',
                    icon: 'fa-clipboard',
                    disabled: function (key, opt) {
                        //const block = treeOperationObj.block || [];
                        const copyInfo = JSON.parse(getLocalCache(copyBlockTag));
                        return !(copyInfo && copyInfo.tid && copyInfo.tid > 0 && copyInfo.block && copyInfo.block.length > 0);
                    },
                    callback: function (key, opt) {
                        //const block = treeOperationObj.block || [];
                        const copyInfo = JSON.parse(getLocalCache(copyBlockTag));
                        if (copyInfo.block.length > 0) {
                            treeOperationObj.pasteBlock(ledgerSpread, copyInfo);
                        } else {
                            document.execCommand('paste');
                        }
                    }
                },
                'batchInsertBillsPos': {
                    name: '批量插入清单-部位',
                    icon: 'fa-sign-in',
                    disabled: function (key, opt) {
                        const sheet = ledgerSpread.getActiveSheet();
                        const selection = sheet.getSelections();
                        const row = selection[0].row;
                        const select = ledgerTree.nodes[row];
                        if (select) {
                            if (select.code && select.code !== '') {
                                return !ledgerTree.isLeafXmj(select);
                            } else {
                                const parent = ledgerTree.getParent(select);
                                return !(parent && ledgerTree.isLeafXmj(parent));
                            }
                        } else {
                            return false;
                        }
                    },
                    callback: function (key, opt) {
                        if (!batchInsertObj) {
                            batchInsertObj = new BatchInsertBillsPosObj($('#batch'));
                        } else {
                            batchInsertObj.initView();
                        }
                        $('#batch').modal('show');
                    }
                },
                'importExcel': {
                    name: '导入分项清单Excel',
                    icon: 'file-excel-o',
                    disabled: function (key, opt) {
                        return tender.ledger_status !== 1;
                    },
                    callback: function (key, opt) {
                        $('#upload-ledger').modal('show');
                    }
                }
            }
        });
    } else {
        SpreadJsObj.forbiddenSpreadContextMenu('#ledger-spread', ledgerSpread);
    }

    treeOperationObj.refreshOperationValid(ledgerSpread.getActiveSheet());

    const posSearch = (function () {
        let resultArr = [];
        const search = function (keyword) {
            if (keyword && keyword !== '') {
                resultArr = [];
                const sortData = posSpread.getActiveSheet().zh_data;
                if (sortData) {
                    for (let i = 0, iLength = sortData.length; i < iLength; i++) {
                        const sd = sortData[i];
                        if (sd.name && sd.name.indexOf(keyword) > -1) {
                            resultArr.push({index: i, data: sd});
                        }
                    }
                }
                $('#pos-search-hint').html(' ' + resultArr.length + '个匹配').show();
            } else {
                resultArr = [];
                $('#pos-search-hint').hide();
            }
        };
        const locateNext = function () {
            if (resultArr.length > 0) {
                const sheet = posSpread.getActiveSheet();
                const sel = sheet.getSelections()[0];
                const curRow = sel ? sel.row : 0;
                let next = _.find(resultArr, function (d) {
                    return d.index > curRow;
                });
                if (!next) next = resultArr[0];
                if (next.index !== curRow) {
                    sheet.setSelection(next.index, sel ? sel.col : 0, 1, 1);
                    sheet.showRow(next.index, spreadNS.VerticalPosition.center);
                }
            }
        };
        const locatePre = function () {
            if (resultArr.length > 0) {
                const sheet = posSpread.getActiveSheet();
                const sel = sheet.getSelections()[0];
                const curRow = sel ? sel.row : 0;
                let next = _.findLast(resultArr, function (d) {
                    return d.index < curRow;
                });
                if (!next) next = resultArr[resultArr.length - 1];
                if (next.index !== curRow) {
                    sheet.setSelection(next.index, sel ? sel.col : 0, 1, 1);
                    sheet.showRow(next.index, spreadNS.VerticalPosition.center);
                }
            }
        };
        return {search, locateNext, locatePre};
    })();
    // 台账模式加载部位明细数据
    if (checkTzMeasureType()) {
        $.divResizer({
            select: '#main-resize',
            callback: function () {
                ledgerSpread.refresh();
                let bcontent = $(".bcontent-wrap") ? $(".bcontent-wrap").height() : 0;
                $(".sp-wrap").height(bcontent-40);
                posSpread.refresh();
            }
        });
        SpreadJsObj.initSheet(posSpread.getActiveSheet(), posSpreadSetting);
        postData('/tender/' + getTenderId() + '/pos', null, function (data) {
            pos.loadDatas(data);
            posOperationObj.loadCurPosData();
            SpreadJsObj.resetTopAndSelect(posSpread.getActiveSheet());
        });
        $('#pos-keyword').bind('input propertychange', function () {
            posSearch.search(this.value);
        });
        $('#search-pre-pos').click(function () {
            posSearch.locatePre();
        });
        $('#search-next-pos').click(function () {
            posSearch.locateNext();
        });
    }
    // 绑定部位明细编辑事件
    const posOperationObj = {
        editStarting: function (e, info) {
            posOperationObj.ledgerTreeNode = SpreadJsObj.getSelectObject(ledgerSpread.getActiveSheet());
        },
        /**
         * 加载部位明细 根据当前台账选择节点
         */
        loadCurPosData: function () {
            const node = treeOperationObj.getSelectNode(ledgerSpread.getActiveSheet());
            if (node) {
                const posData = pos.ledgerPos[itemsPre + node.id] || [];
                SpreadJsObj.loadSheetData(posSpread.getActiveSheet(), 'data', posData);
            } else {
                SpreadJsObj.loadSheetData(posSpread.getActiveSheet(), 'data', []);
            }
        },
        /**
         * 编辑单元格响应事件
         * @param {Object} e
         * @param {Object} info
         */
        editEnded: function (e, info) {
            if (info.sheet.zh_setting) {
                const posData = info.sheet.zh_data ? info.sheet.zh_data[info.row] : null;
                const col = info.sheet.zh_setting.cols[info.col];
                const orgText = posData ? posData[col.field] : null;
                const newText = info.sheet.getCell(info.row, info.col).text();
                if (orgText === newText || ((!orgText || orgText === '') && (newText === ''))) {
                    return;
                }

                //const node = treeOperationObj.getSelectNode(ledgerSpread.getActiveSheet());
                const node = posOperationObj.ledgerTreeNode;
                if (!node) {
                    toast('数据错误，请选择台账节点后再试', 'error');
                    SpreadJsObj.reLoadRowData(info.sheet, info.row);
                    return;
                } else if (newText && newText !== '' && node.children && node.children.length > 0) {
                    toast('父节点不可插入部位明细', 'error');
                    SpreadJsObj.reLoadRowData(info.sheet, info.row);
                    return;
                } else if (newText && newText !== '' && (!node.b_code || node.b_code === '')) {
                    toast('项目节不可插入部位明细', 'error');
                    SpreadJsObj.reLoadRowData(info.sheet, info.row);
                    return;
                }

                const data = {};
                if (col.field === 'name') {
                    if (newText === '' && posData) {
                        toast('部位名称不可为空', 'error', 'exclamation-circle');
                        SpreadJsObj.reLoadRowData(info.sheet, info.row);
                        return;
                    } else if (!posData) {
                        if (newText && newText !== '') {
                            data.updateType = 'add';
                            const sortData = info.sheet.zh_data;
                            const order = (!sortData || sortData.length === 0) ? 1 : Math.max(sortData[sortData.length - 1].porder + 1, sortData.length + 1);
                            data.updateData = { name: newText, lid: node.id, tid: tender.id, porder: order};
                        } else {
                            return;
                        }
                    } else {
                        data.updateType = 'update';
                        data.updateData = {id: posData.id, name: newText};
                    }
                } else if (!posData) {
                    toast('新增部位请先输入名称', 'warning');
                    SpreadJsObj.reLoadRowData(info.sheet, info.row);
                    return;
                } else {
                    data.updateType = 'update';
                    data.updateData = {id: posData.id};
                    data.updateData[col.field] = col.type === 'Number' ? parseFloat(newText) : newText;
                }
                postData('/tender/' + getTenderId() + '/pos/update', data, function (result) {
                    const updateRst = pos.updateDatas(result.pos);
                    // 刷新当前行, 不适用于新增（在非下一空白行新增）
                    if (updateRst.create.length > 0) {
                        // info.sheet.addRows(info.row, 1);
                        // if (info.sheet.zh_data.length === 0) {
                        //     info.sheet.zh_data = pos.ledgerPos[itemsPre + node.id] || [];
                        // }
                        // SpreadJsObj.reLoadRowData(info.sheet, info.sheet.zh_data.length - 1);
                        posOperationObj.loadCurPosData();
                    } else {
                        SpreadJsObj.reLoadRowData(info.sheet, info.row);
                    }
                    const loadResult = ledgerTree.loadPostData(result.ledger);
                    treeOperationObj.refreshTree(ledgerSpread.getActiveSheet(), loadResult);
                    treeOperationObj.refreshOperationValid(ledgerSpread.getActiveSheet());
                }, function () {
                    SpreadJsObj.reLoadRowData(info.sheet, info.row);
                });
            }
        },
        /**
         * 删除按钮响应事件
         * @param sheet
         */
        deletePress: function (sheet) {
            const self = this;
            if (sheet.zh_setting) {
                const sortData = sheet.zh_data;
                const datas = [], posSelects = [];
                const sel = sheet.getSelections()[0];
                for (let iRow = sel.row; iRow < sel.row + sel.rowCount; iRow++) {
                    let bDel = false;
                    const node = sortData[iRow];
                    if (node) {
                        const data = {id: node.id};
                        for (let iCol = sel.col; iCol < sel.col + sel.colCount; iCol++) {
                            const colSetting = sheet.zh_setting.cols[iCol];
                            if (colSetting.field === 'name') {
                                toast('部位名称不能为空', 'error');
                                return;
                            }
                            const style = sheet.getStyle(iRow, iCol);
                            if (!style.locked) {
                                const colSetting = sheet.zh_setting.cols[iCol];
                                data[colSetting.field] = null;
                                bDel = true;
                            }
                        }
                        if (bDel) {
                            datas.push(data);
                            posSelects.push(node);
                        }
                    }
                }
                if (datas.length > 0) {
                    postData('/tender/' + getTenderId() + '/pos/update', {updateType: 'update', updateData: datas}, function (result) {
                        pos.updateDatas(result.pos);
                        posOperationObj.loadCurPosData();
                        const loadResult = ledgerTree.loadPostData(result.ledger);
                        treeOperationObj.refreshTree(ledgerSpread.getActiveSheet(), loadResult);
                        treeOperationObj.refreshOperationValid(ledgerSpread.getActiveSheet());
                    }, function () {
                        posOperationObj.loadCurPosData();
                    });
                }
            }
        },
        /**
         * 删除 部位明细
         * @param sheet
         */
        deletePos: function (sheet) {
            const selection = sheet.getSelections();
            const data = {
                updateType: 'delete',
                updateData: [],
            };
            const row = selection[0].row, count = selection[0].rowCount;
            const sortData = sheet.zh_data;
            for (let iRow = 0; iRow < count; iRow++) {
                if (sortData[iRow + row]) {
                    data.updateData.push(sortData[iRow + row].id);
                }
            }
            if (data.updateData.length > 0) {
                postData('/tender/' + getTenderId() + '/pos/update', data, function (result) {
                    pos.removeDatas(result.pos);
                    sheet.deleteRows(row, count);
                    const loadResult = ledgerTree.loadPostData(result.ledger);
                    treeOperationObj.refreshTree(ledgerSpread.getActiveSheet(), loadResult);
                    treeOperationObj.refreshOperationValid(ledgerSpread.getActiveSheet());
                });
            }
        },
        /**
         * 粘贴单元格响应事件
         * @param e
         * @param info
         */
        clipboardPasted: function (e, info) {
            const node = treeOperationObj.getSelectNode(ledgerSpread.getActiveSheet());
            if (node.code && (node.code !== '')) {
                toast('项目节不可含有清单明细', 'error');
                posOperationObj.loadCurPosData();
                return;
            }
            if (node.children && (node.children.length > 0)) {
                toast('仅清单子项可以含有部位明细', 'error');
                posOperationObj.loadCurPosData();
                return;
            }

            if (info.sheet.zh_setting) {
                const data = [];
                const sortData = info.sheet.zh_data || [];
                if (sortData.length === 0 || info.cellRange.row + info.cellRange.rowCount > sortData.length) {
                    if (info.cellRange.col !== 0) {
                        toast('新增部位请先输入名称', 'warning');
                        posOperationObj.loadCurPosData();
                        return;
                    }
                }
                const lastOrder = sortData.length > 0 ? sortData[sortData.length - 1].porder + 1 : 1;
                for (let iRow = 0; iRow < info.cellRange.rowCount; iRow++) {
                    const curRow = info.cellRange.row + iRow;
                    const posData = curRow >= sortData.length ? {lid: node.id, porder: lastOrder + curRow - sortData.length} : {id: sortData[curRow].id, lid: node.id};
                    for (let iCol = 0; iCol < info.cellRange.colCount; iCol++) {
                        const curCol = info.cellRange.col + iCol;
                        const colSetting = info.sheet.zh_setting.cols[curCol];
                        posData[colSetting.field] = info.sheet.getText(curRow, curCol);
                        if (colSetting.type === 'Number') {
                            posData[colSetting.field] = _.toNumber(posData[colSetting.field]);
                        }
                    }
                    data.push(posData);
                }
                postData('/tender/' + getTenderId() + '/pos/paste', data, function (result) {
                    pos.updateDatas(result.pos);
                    posOperationObj.loadCurPosData();
                    const loadResult = ledgerTree.loadPostData(result.ledger);
                    treeOperationObj.refreshTree(ledgerSpread.getActiveSheet(), loadResult);
                    posOperationObj.loadCurPosData();
                    treeOperationObj.refreshOperationValid(ledgerSpread.getActiveSheet());
                }, function () {
                    SpreadJsObj.reLoadRowData(info.sheet, info.cellRange.row, info.cellRange.rowCount);
                });
            }
        },
    };
    if (!posSpreadSetting.readOnly) {
        SpreadJsObj.addDeleteBind(posSpread, posOperationObj.deletePress);
        posSpread.bind(spreadNS.Events.EditStarting, posOperationObj.editStarting);
        posSpread.bind(spreadNS.Events.EditEnded, posOperationObj.editEnded);
        posSpread.bind(spreadNS.Events.ClipboardPasted, posOperationObj.clipboardPasted);
        // 右键菜单
        $.contextMenu({
            selector: '#pos-spread',
            build: function ($trigger, e) {
                const target = SpreadJsObj.safeRightClickSelection($trigger, e, posSpread);
                return target.hitTestType === GC.Spread.Sheets.SheetArea.viewport || target.hitTestType === GC.Spread.Sheets.SheetArea.rowHeader;
            },
            items: {
                'delete': {
                    name: '删除',
                    icon: 'fa-remove',
                    disabled: function (key, opt) {
                        const sheet = posSpread.getActiveSheet();
                        if (sheet.zh_data) {
                            const selection = sheet.getSelections();
                            return sheet.zh_data.length < selection[0].row + selection[0].rowCount;
                        } else {
                            return true;
                        }
                    },
                    callback: function (key, opt) {
                        posOperationObj.deletePos(posSpread.getActiveSheet());
                    }
                },
            }
        });
    } else {
        SpreadJsObj.forbiddenSpreadContextMenu('#pos-spread', posSpread);
    }

    let stdChapter, stdBills, dealBills, searchLedger;

    $.divResizer({
        select: '#right-spr',
        callback: function () {
            ledgerSpread.refresh();
            if (posSpread) {
                posSpread.refresh();
            }
            if (stdChapter) {
                stdChapter.spread.refresh();
            }
            if (stdBills) {
                stdBills.spread.refresh();
            }
            if (dealBills) {
                dealBills.spread.refresh();
            }
            if (searchLedger) {
                searchLedger.spread.refresh();
            }
        }
    });
    // 展开收起标准清单
    $('a', '#side-menu').bind('click', function (e) {
        e.preventDefault();
        const tab = $(this), tabPanel = $(tab.attr('content'));
        const showSideTools = function (show) {
            const left = $('#left-view'), right = $('#right-view'), parent = left.parent();
            if (show) {
                right.show();
                autoFlashHeight();
                /**
                 * right.show()后, parent被撑开成2倍left.height, 导致parent.width减少了10px
                 * 第一次left.width调整后，parent的缩回left.height, 此时parent.width又增加了10px
                 * 故需要通过最终的parent.width再计算一次left.width
                 *
                 * Q: 为什么不通过先计算left.width的宽度，以避免计算两次left.width?
                 * A: 右侧工具栏不一定显示，当右侧工具栏显示过一次后，就必须使用parent和right来计算left.width
                 *
                 */
                //left.css('width', parent.width() - right.outerWidth());
                //left.css('width', parent.width() - right.outerWidth());
                const percent = 100 - right.outerWidth() /parent.width() * 100;
                left.css('width', percent + '%');
            } else {
                left.width(parent.width());
                right.hide();
            }
        };
        // 展开工具栏、切换标签
        if (!tab.hasClass('active')) {
            const close = $('.active', '#side-menu').length === 0;
            $('a', '#side-menu').removeClass('active');
            tab.addClass('active');
            $('.tab-content .tab-pane').removeClass('active');
            tabPanel.addClass('active');
            showSideTools(tab.hasClass('active'));
            if (tab.attr('content') === '#std-chapter') {
                if (!stdChapter) {
                    stdChapter = new stdLib('#std-chapter-spread', 'chapter', {
                        id: 'chapter_id',
                        pid: 'pid',
                        order: 'order',
                        level: 'level',
                        rootId: -1,
                        keys: ['id', 'list_id', 'chapter_id'],
                    }, {
                        cols: [
                            {title: '项目节编号', field: 'code', hAlign: 0, width: 120, formatter: '@', readOnly: true, cellType: 'tree'},
                            {title: '名称', field: 'name', hAlign: 0, width: 230, formatter: '@', readOnly: true},
                            {title: '单位', field: 'unit', hAlign: 1, width: 50, formatter: '@', readOnly: true}
                        ],
                        treeCol: 0,
                        emptyRows: 0,
                        headRows: 1,
                        headRowHeight: [40],
                        defaultRowHeight: 21,
                    });
                    stdChapter.loadLib(1);
                }
                stdChapter.spread.refresh();
            } else if (tab.attr('content') === '#std-bills') {
                if (!stdBills) {
                    stdBills = new stdLib('#std-bills-spread', 'bills', {
                        id: 'bill_id',
                        pid: 'pid',
                        order: 'order',
                        level: 'level',
                        rootId: -1,
                        keys: ['id', 'list_id', 'bill_id']
                    }, {
                        cols: [
                            {title: '清单编号', field: 'code', hAlign: 0, width: 120, formatter: '@', readOnly: true, cellType: 'tree'},
                            {title: '名称', field: 'name', hAlign: 0, width: 230, formatter: '@', readOnly: true},
                            {title: '单位', field: 'unit', hAlign: 1, width: 50, formatter: '@', readOnly: true}
                        ],
                        treeCol: 0,
                        emptyRows: 0,
                        headRows: 1,
                        headRowHeight: [40],
                        defaultRowHeight: 21,
                    });
                    stdBills.loadLib(1);
                }
                stdBills.spread.refresh();
            } else if (tab.attr('content') === '#deal-bills') {
                if (!dealBills) {
                    dealBills = new DealBills('#deal-bills-spread', {
                        cols: [
                            {title: '清单编号', field: 'code', hAlign: 0, width: 120, formatter: '@', readOnly: true},
                            {title: '名称', field: 'name', hAlign: 0, width: 230, formatter: '@', readOnly: true},
                            {title: '单位', field: 'unit', hAlign: 1, width: 50, formatter: '@', readOnly: true},
                            {title: '单价', field: 'unit_price', hAlign: 2, width: 50, readOnly: true},
                            {title: '数量', field: 'quantity', hAlign: 2, width: 50, readOnly: true},
                            {title: '金额', field: 'total_price', hAlign: 2, width: 50, readOnly: true},
                        ],
                        emptyRows: 0,
                        headRows: 1,
                        headRowHeight: [40],
                        defaultRowHeight: 21,
                    });
                    dealBills.loadData();
                }
                dealBills.spread.refresh();
            } else if (tab.attr('content') === '#search' && !searchLedger) {
                if (!searchLedger) {
                    searchLedger = new SearchLedger($('#search'), {
                        cols: [
                            {title: '项目节编号', field: 'code', hAlign: 0, width: 120, formatter: '@', readOnly: true},
                            {title: '清单编号', field: 'b_code', hAlign: 0, width: 120, formatter: '@', readOnly: true},
                            {title: '名称', field: 'name', width: 230, hAlign: 0, formatter: '@', readOnly: true},
                            {title: '单位', field: 'unit', width: 50, hAlign: 1, formatter: '@', readOnly: true},
                            {title: '单价', field: 'unit_price', hAlign: 2, width: 50, readOnly: true},
                            {title: '数量', field: 'quantity', hAlign: 2, width: 50, readOnly: true},
                        ],
                        emptyRows: 0,
                        headRows: 1,
                        headRowHeight: [40],
                        defaultRowHeight: 21,
                    });
                }
                searchLedger.spread.refresh();
            }
        } else { // 收起工具栏
            tab.removeClass('active');
            tabPanel.removeClass('active');
            showSideTools(tab.hasClass('active'));
        }
        ledgerSpread.refresh();
        if (posSpread) {
            posSpread.refresh();
        }
    });

    class stdLib {
        constructor(selector, stdType, treeSetting, spreadSetting) {
            this.obj = $(selector)[0];
            this.url = '/std/' + stdType;
            this.treeSetting = treeSetting;
            treeSetting.preUrl = this.url;
            this.spreadSetting = spreadSetting;
            this.spread = SpreadJsObj.createNewSpread(this.obj);
            SpreadJsObj.initSheet(this.spread.getActiveSheet(), this.spreadSetting);
            SpreadJsObj.forbiddenSpreadContextMenu(selector, this.spread);
            this.spread.getActiveSheet().bind(GC.Spread.Sheets.Events.CellDoubleClick, function (e, info) {
                const stdSheet = info.sheet;
                const mainSheet = ledgerSpread.getActiveSheet();
                if (!stdSheet.zh_setting || !stdSheet.zh_tree || !mainSheet.zh_tree) { return; }

                const stdTree = stdSheet.zh_tree;
                const stdNode = stdTree.nodes[info.row];

                const mainTree = mainSheet.zh_tree;
                const sel = mainSheet.getSelections()[0];
                const mainNode = mainTree.nodes[sel.row];
                if (!stdNode) { return; }
                if (stdType === 'bills') {
                    if (!(mainNode.b_code && mainNode.b_code !== '') && !mainTree.isLeafXmj(mainNode)) {
                        toast('非最底层项目下，不应添加清单', 'warning');
                        return;
                    }
                }

                mainTree.postData('/tender/' + getTenderId() + '/ledger/add-by-std', mainNode, {
                    tender_id: mainNode.tender_id,
                    stdType: stdType,
                    stdLibId: stdNode.list_id,
                    stdNode: stdTree.getNodeKey(stdNode)
                }, function (result) {
                    treeOperationObj.refreshTree(mainSheet, result);
                    treeOperationObj.refreshOperationValid(mainSheet);
                });
            });
            this.pathTree = createNewPathTree('base', this.treeSetting);
        }
        loadLib (listId) {
            const self = this;
            postData(this.url+'/get-data', {list_id: listId}, function (data) {
                self.pathTree.loadDatas(data);
                SpreadJsObj.loadSheetData(self.spread.getActiveSheet(), 'tree', self.pathTree);
            });
        }
    }
    class DealBills {
        constructor (selector, spreadSetting) {
            const self = this;
            this.obj = $(selector)[0];
            this.url = '/tender/' + getTenderId() + '/deal';
            this.spreadSetting = spreadSetting;
            this.spread = SpreadJsObj.createNewSpread(this.obj);
            SpreadJsObj.initSheet(this.spread.getActiveSheet(), this.spreadSetting);
            if (!readOnly) {
                this.spread.bind(spreadNS.Events.CellDoubleClick, function (e, info) {
                const dealSheet = info.sheet;
                const mainSheet = ledgerSpread.getActiveSheet();

                const dealBills = SpreadJsObj.getSelectObject(dealSheet);
                if (!dealBills) { return; }
                const mainTree = mainSheet.zh_tree;
                const mainNode = SpreadJsObj.getSelectObject(mainSheet);
                if (!mainNode || !mainTree) { return; }

                if (mainNode.code && mainNode.code !== '' && !mainTree.isLeafXmj(mainNode)) {
                    toast('非最底层项目下，不应添加清单', 'error');
                    return;
                }

                postData('/tender/' + getTenderId() + '/ledger/add-by-deal', {
                    id: mainNode.ledger_id,
                    type: mainNode.code ? 'child' : 'next',
                    dealBills: {
                        b_code: dealBills.code, name: dealBills.name, unit: dealBills.unit,
                        unit_price: dealBills.unit_price,
                    },
                }, function (result) {
                    const refreshData = mainTree.loadPostData(result);
                    treeOperationObj.refreshTree(mainSheet, refreshData);
                    treeOperationObj.refreshOperationValid(mainSheet);
                });
            });
            }
            SpreadJsObj.forbiddenSpreadContextMenu(selector, this.spread);
            $('#upload-deal-bills').click(function () {
                    const file = $('#deal-bills-file')[0];
                    const formData = new FormData();
                    formData.append('file', file.files[0]);
                    postDataWithFile(self.url+'/upload-excel', formData, function (data) {
                        self.data = data;
                        //self.calculateData();
                        SpreadJsObj.loadSheetData(self.spread.getActiveSheet(), 'data', data);
                        $('#upload-deal').modal('hide');
                    }, function () {
                        $('#upload-deal').modal('hide');
                    });
                });
        }
        loadData () {
            const self = this;
            postData(this.url+'/get-data', {}, function (data) {
                self.data = data;
                //self.calculateData();
                SpreadJsObj.loadSheetData(self.spread.getActiveSheet(), 'data', data);
            });
        }
        calculateData () {
            if (this.data) {
                for (const d of this.data) {
                    d.total_price = _.multiply(d.quantity, d.unit_price);
                }
            }
        }
    }
    class BatchInsertBillsPosObj {
        constructor (obj) {
            const self = this;
            this.obj = obj;
            this.billsCount = 6;
            this.posCount = 1000;
            // 初始化 清单编号窗口 参数
            this.qdSpreadSetting = {
                cols: [
                    {title: '编号', field: 'code', hAlign: 0, width: 80, formatter: '@'},
                    {title: '名称', field: 'name', hAlign: 0, width: 120, formatter: '@'},
                    {title: '单位', field: 'unit', hAlign: 1, width: 50, formatter: '@'},
                    {title: '单价', field: 'unit_price', hAlign: 2, width: 50},
                    {title: '图册号', field: 'name', hAlign: 0, width: 60, formatter: '@'},
                ],
                emptyRows: this.billsCount,
                headRows: 1,
                headRowHeight: [40],
            };
            this.qdSpread = SpreadJsObj.createNewSpread($('.batch-l-t', this.obj)[0]);
            // 初始化 部位数量复核表 参数
            this.posSpreadSetting = {
                cols: [
                    {title: '部位', field: 'bw', hAlign: 0, width: 80, formatter: '@'},
                    {title: '图册号', field: 'drawingCode', hAlign: 0, formatter: '@', width: 60},
                ],
                emptyRows: this.posCount,
                headRows: 1,
                headRowHeight: [40],
            };
            for (let iNum = 1; iNum <= this.billsCount; iNum++) {
                this.posSpreadSetting.cols.push(
                    {title: '清单' + iNum, field: 'bills' + iNum, hAlign: 2, width: 50}
                )
            }
            this.posSpread = SpreadJsObj.createNewSpread($('.batch-l-b', this.obj)[0]);
            // 初始化 签约清单 参数
            this.dealSpreadSetting = {
                cols: [
                    {title: '清单编号', field: 'code', width: 80, formatter: '@', readOnly: true},
                    {title: '名称', field: 'name', width: 120, formatter: '@', readOnly: true},
                    {title: '单位', field: 'unit', width: 50, formatter: '@', readOnly: true},
                    {title: '单价', field: 'unit_price', width: 50, readOnly: true},
                ],
                emptyRows: 0,
                headRows: 1,
                headRowHeight: [40],
            };
            this.dealSpread = SpreadJsObj.createNewSpread($('.batch-r', this.obj)[0]);
            // 初始化 清单编号、部位数量复核表 表格
            this.initView();
            SpreadJsObj.initSheet(this.dealSpread.getActiveSheet(), this.dealSpreadSetting);
            SpreadJsObj.refreshColumnAlign(this.dealSpread.getActiveSheet());
            $.contextMenu({
                selector: '.batch-l-t',
                build: function ($trigger, e) {
                    const target = SpreadJsObj.safeRightClickSelection($trigger, e, self.qdSpread);
                    return target.hitTestType === spreadNS.SheetArea.viewport || target.hitTestType === spreadNS.SheetArea.rowHeader;
                },
                items: {
                    'create': {
                        name: '新增行',
                        icon: 'fa-sign-in',
                        callback: function (key, opt) {
                            const qdSheet = self.qdSpread.getActiveSheet();
                            const posSheet = self.posSpread.getActiveSheet();
                            qdSheet.addRows(qdSheet.getRowCount(), 1);
                            const index = qdSheet.getRowCount();
                            qdSheet.getCell(qdSheet.getRowCount() - 1, 0, spreadNS.SheetArea.rowHeader).text('清单' + index);
                            posSheet.addColumns(posSheet.getColumnCount(), 1);
                            posSheet.getCell(0, index + 2, spreadNS.SheetArea.colHeader).text('清单' + index);
                        },
                    },
                    'delete': {
                        name: '删除行',
                        icon: 'fa-remove',
                        callback: function (key, opt) {
                            const qdSheet = self.qdSpread.getActiveSheet();
                            const posSheet = self.posSpread.getActiveSheet();
                            const sel = qdSheet.getSelections()[0];
                            qdSheet.deleteRows(sel.row, sel.rowCount);
                            posSheet.deleteColumns(sel.row + 2, sel.rowCount);
                            for (let iRow = 0, iLen = qdSheet.getRowCount(); iRow < iLen; iRow++) {
                                qdSheet.getCell(iRow, 0, spreadNS.SheetArea.rowHeader).text('清单' + (iRow+1));
                            }
                            for (let iCol = 0, iLen = posSheet.getColumnCount() - 2; iCol < iLen; iCol++) {
                                posSheet.getCell(0, iCol + 2, spreadNS.SheetArea.colHeader).text('清单' + (iCol+1));
                            }
                            qdSheet.setSelection(sel.row, sel.col, 1, 1);
                        },
                    },
                }
            });
            // 拉取签约清单数据
            if (dealBills) {
                SpreadJsObj.loadSheetData(this.dealSpread.getActiveSheet(), 'data', dealBills.data);
            } else {
                postData('/tender/' + getTenderId() + '/deal/get-data', {}, function (data) {
                    SpreadJsObj.loadSheetData(self.dealSpread.getActiveSheet(), 'data', data);
                });
            }
            // 双击签约清单，自动添加到清单编号窗口
            this.dealSpread.bind(GC.Spread.Sheets.Events.CellDoubleClick, function (e, info) {
                const deal = info.sheet.zh_data[info.row];
                const qdSheet = self.qdSpread.getActiveSheet(), posSheet = self.posSpread.getActiveSheet();
                const sel = qdSheet.getSelections()[0];
                qdSheet.getCell(sel.row, 0).value(deal.code);
                qdSheet.getCell(sel.row, 1).value(deal.name);
                qdSheet.getCell(sel.row, 2).value(deal.unit);
                qdSheet.getCell(sel.row, 3).value(deal.unit_price);
                if (sel.row + 1 === qdSheet.getRowCount()) {
                    const count = sel.row + 2;
                    qdSheet.setRowCount(count);
                    qdSheet.getCell(sel.row + 1, 0, GC.Spread.Sheets.SheetArea.rowHeader).text('清单' + count);

                    const colCount = posSheet.getColumnCount() + 1
                    posSheet.setColumnCount(colCount);
                    posSheet.getCell(0, colCount - 1, GC.Spread.Sheets.SheetArea.colHeader).text('数量' + count);
                }
                qdSheet.setSelection(sel.row + 1, sel.col, 1, 1);
            });

            this.obj.bind('shown.bs.modal', function () {
                self.qdSpread.refresh();
                self.posSpread.refresh();
                self.dealSpread.refresh();
            });

            $('#batch-ok').click(function () {
                const sheet = ledgerSpread.getActiveSheet();
                const selection = sheet.getSelections();
                const row = selection[0].row;
                const select = ledgerTree.nodes[row];
                if (select) {
                    const insertData = {};
                    insertData.batchType = (select.code && select.code !== '') ? 'child' : 'next';
                    insertData.id = select[ledgerTree.setting.id];
                    insertData.batchData = self.getBatchData();
                    postData('/tender/' + getTenderId() + '/ledger/batch-insert', insertData, function (data) {
                        pos.updateDatas(data.pos);
                        const result = ledgerTree.loadPostData(data.ledger);
                        treeOperationObj.refreshTree(sheet, result);
                        treeOperationObj.refreshOperationValid(sheet, selection);
                        self.obj.modal('hide');
                    });
                }
            });
        }
        // 初始化左侧表格
        initView () {
            // 初始化 清单编号
            const qdSheet = this.qdSpread.getActiveSheet();
            SpreadJsObj.initSheet(qdSheet, this.qdSpreadSetting);
            SpreadJsObj.refreshColumnAlign(qdSheet);
            // 清理原有数据
            SpreadJsObj.beginMassOperation(qdSheet);
            qdSheet.clear(0, 0, qdSheet.getRowCount(), qdSheet.getColumnCount(), GC.Spread.Sheets.SheetArea.viewport, GC.Spread.Sheets.StorageType.data);
            for (let iRow = 1; iRow <= this.billsCount; iRow++) {
                qdSheet.getCell(iRow - 1, 0, GC.Spread.Sheets.SheetArea.rowHeader).text('清单' + iRow);
            }
            qdSheet.setSelection(0, 0, 1 ,1);
            SpreadJsObj.endMassOperation(qdSheet);
            // 初始化 部位数量复核表
            const posSheet = this.posSpread.getActiveSheet();
            SpreadJsObj.initSheet(posSheet, this.posSpreadSetting);
            SpreadJsObj.refreshColumnAlign(posSheet);
            // 清理原有数据
            SpreadJsObj.beginMassOperation(posSheet);
            posSheet.setColumnWidth(0, 45, GC.Spread.Sheets.SheetArea.rowHeader);
            posSheet.clear(0, 0, posSheet.getRowCount(), posSheet.getColumnCount(), GC.Spread.Sheets.SheetArea.viewport, GC.Spread.Sheets.StorageType.data);
            posSheet.setSelection(0, 0, 1 ,1);
            SpreadJsObj.endMassOperation(posSheet);
            // 检查签约清单数据，以工具栏数据为准
            if (dealBills) {
                SpreadJsObj.loadSheetData(this.dealSpread.getActiveSheet(), 'data', dealBills.data);
            }
            this.dealSpread.getActiveSheet().setSelection(0, 0, 1, 1);
        }
        // 获取界面数据
        getBatchData () {
            const result = [];
            const qdSheet = this.qdSpread.getActiveSheet(), posSheet = this.posSpread.getActiveSheet();
            for (let iRow = 0; iRow < qdSheet.getRowCount(); iRow++) {
                if (qdSheet.getText(iRow, 0) === '') { continue; }
                const qd = {
                    b_code: qdSheet.getText(iRow, 0),
                    name: qdSheet.getText(iRow, 1),
                    unit: qdSheet.getText(iRow, 2),
                    price: _.toNumber(qdSheet.getText(iRow, 3)),
                    pos: [],
                };
                result.push(qd);
                for (let iPosRow = 0; iPosRow < posSheet.getRowCount(); iPosRow++) {
                    const value = _.toNumber(posSheet.getText(iPosRow, iRow + 2));
                    if (value !== 0 && !isNaN(value)) {
                        qd.pos.push({
                            name: posSheet.getText(iPosRow, 0),
                            drawing_code: posSheet.getText(iPosRow, 1),
                            quantity: value, porder: qd.pos.length + 1,
                        });
                    }
                }
            }
            return result;
        }
     }
    class SearchLedger {
        constructor(obj, spreadSetting) {
            const self = this;
            this.obj = obj;
            this.spreadSetting = spreadSetting;
            this.spread = SpreadJsObj.createNewSpread($('#search-result', this.obj)[0]);
            SpreadJsObj.initSheet(this.spread.getActiveSheet(), this.spreadSetting);
            SpreadJsObj.forbiddenSpreadContextMenu('#search-result', this.spread);
            $('#searchLedger', this.obj).bind('click', function () {
                const keyword = $('input', self.obj).val();
                this.searchResult = [];
                const sortData = SpreadJsObj.getSortData(ledgerSpread.getActiveSheet());
                for (const node of sortData) {
                    if ((node.code && node.code.indexOf(keyword) > -1) ||
                        node.b_code && node.b_code.indexOf(keyword) > -1 ||
                        node.name && node.name.indexOf(keyword) > -1) {
                        const data = JSON.parse(JSON.stringify(node));
                        data.visible = true;
                        this.searchResult.push(data);
                    }
                }
                SpreadJsObj.loadSheetData(self.spread.getActiveSheet(), 'data', this.searchResult);
            });
            this.spread.getActiveSheet().bind(GC.Spread.Sheets.Events.CellDoubleClick, function (e, info) {
                const sheet = info.sheet;
                const data = sheet.zh_data;
                if (!data) { return }

                const curBills = data[info.row];
                if (!curBills) { return }

                SpreadJsObj.locateTreeNode(ledgerSpread.getActiveSheet(), curBills.ledger_id, true);
            });
        }
    }

    $('#searchAccount').click(() => {
        const data = {
            keyword: $('#searchName').val(),
        };
        postData('/search/user', data, (data) => {
            const resultDiv = $('#searchResult');
            if (data) {
                $('h5>span', resultDiv).text(data.name);
                $('#addAuditor').attr('auditorId', data.id);
                $('h6', resultDiv).text(data.role);
                $('p', resultDiv).text(data.company);
                resultDiv.show();
            } else {
                toast('未查询到该审核人', 'info');
                resultDiv.hide();
            }
        }, () => {
            $('#searchResult').hide();
        });
    });
    // 审批人分组选择
    $('#account_group').change(function () {
        let account_html = '<option value="0">选择审批人</option>';
        for (const account of accountList) {
            if (parseInt($(this).val()) === 0 || parseInt($(this).val()) === account.account_group) {
                const role = account.role !== '' ? '（' + account.role + '）' : '';
                const company = account.company !== '' ? ' -' + account.company : '';
                account_html += '<option value="' + account.id + '">' + account.name + role + company + '</option>';
            }
        }
        $('#account_list').html(account_html);
    });
    // 添加到审批流程中
    $('body').on('change', '#account_list', function () {
        let id = $(this).val();
        id = parseInt(id);
        if (id !== 0) {
            const data = {
                auditorId: $(this).val(),
            };
            postData('/tender/' + getTenderId() + '/ledger/audit/add', data, (data) => {
                const html = [];
                html.push('<li class="list-group-item" auditorId="' + data.audit_id + '"><a href="javascript: void(0)" class="text-danger pull-right">移除</a>');
                html.push('<span>');
                html.push(data.audit_order + ' ');
                html.push(data.name + ' ');
                html.push('</span>');
                html.push('<small class="text-muted">');
                html.push(data.role);
                html.push('</small></li>');
                $('#auditors').append(html.join(''));

                // 如果是重新上报，添加到重新上报列表中
                const auditorshtml = [];
                // 重新上报时。令其它的审批人流程图标转换
                $('#auditors-list li i').removeClass('fa-stop-circle').addClass('fa-chevron-circle-down');
                // 添加新审批人
                auditorshtml.push('<li class="list-group-item" data-auditid="' + data.audit_id + '">');
                auditorshtml.push('<i class="fa fa-stop-circle"></i> ');
                auditorshtml.push(data.name + ' <small class="text-muted">' + data.role + '</small>');
                auditorshtml.push('</li>');
                $('#auditors-list').append(auditorshtml.join(''));

                const auditorshtml2 = [];
                // 重新上报时。令其它的审批人流程图标转换
                $('#auditors-list2 li i').removeClass('fa-stop-circle').addClass('fa-chevron-circle-down');
                // 添加新审批人
                auditorshtml2.push('<li class="list-group-item" data-auditid="' + data.audit_id + '">');
                auditorshtml2.push('<h5 class="card-title"><i class="fa fa-stop-circle"></i> ');
                auditorshtml2.push(data.name + ' <small class="text-muted">' + data.role + '</small></h5>');
                auditorshtml2.push('</li>');
                $('#auditors-list2').append(auditorshtml2.join(''));
            });
        }
    });
    // $('#addAuditor').click(() => {
    //     const data = {
    //         auditorId: $('#addAuditor').attr('auditorId'),
    //     };
    //     postData('/tender/' + getTenderId() + '/ledger/audit/add', data, (data) => {
    //         const html = [];
    //         html.push('<li class="list-group-item" auditorId="'+ data.audit_id +'"><a href="javascript: void(0)" class="text-danger pull-right">移除</a>');
    //         html.push('<span>');
    //         html.push(data.audit_order + ' ');
    //         html.push(data.name + ' ');
    //         html.push('</span>');
    //         html.push('<small class="text-muted">');
    //         html.push(data.role);
    //         html.push('</small></li>');
    //         $('#auditors').append(html.join(''));
    //     });
    // });
    $('body').on('click', '#auditors li>a', function () {
        const li = $(this).parent();
        const data = {
            auditorId: parseInt(li.attr('auditorId')),
        };
        postData('/tender/' + getTenderId() + '/ledger/audit/delete', data, (data2) => {
            li.remove();
            for (const a of data2) {
                const aLi = $('li[auditorId=' + a.audit_id + ']');
                $('span', aLi).text(a.audit_order + ' ' + a.name + ' ');
            }

            // 如果是重新上报
            // 令最后一个图标转换
            $('#auditors-list li[data-auditid="' + data.auditorId + '"]').remove();
            if ($('#auditors-list li').length !== 0 && !$('#auditors-list li i').hasClass('fa-stop-circle')) {
                $('#auditors-list li').eq($('#auditors-list li').length-1).children('i')
                    .removeClass('fa-chevron-circle-down').addClass('fa-stop-circle');
            }
            $('#auditors-list2 li[data-auditid="' + data.auditorId + '"]').remove();
            if ($('#auditors-list2 li').length !== 0 && !$('#auditors-list2 li i').hasClass('fa-stop-circle')) {
                $('#auditors-list2 li').eq($('#auditors-list2 li').length-1).children('i')
                    .removeClass('fa-chevron-circle-down').addClass('fa-stop-circle');
            }
        });
    });
    // 选择excel文件后，加载全部sheet
    $('#upload-ledger-file').change(function () {
        if (this.files.length === 0) {
            $('#upload-ledger-sheets').html('').hide();
            return;
        }$('#upload-ledger-sheets').hide();
        try {
            xlsxUtils.import(this.files[0], (excelData) => {
                if (excelData.SheetNames.length > 0) {
                    const html = [];
                    html.push('<hr></hr>');
                    html.push('<h6>选择导入的工作表</h6>');
                    for (const iName in excelData.SheetNames) {
                        const name = excelData.SheetNames[iName];
                        html.push('<div class="card p-2 mb-2">');
                        html.push('<div class="form-check">');
                        html.push('<input class="form-check-input" type="radio" name="sheetName" id="excel-sheet' + iName + '"', (iName == 0 ? ' checked=""' : ''), ' value="' + name + '"',  '>');
                        html.push('<label class="form-check-label" for="excel-sheet' + iName + '">', name, '</label>');
                        html.push('</div>');
                        html.push('</div>');
                    }
                    $('#upload-ledger-sheets').html(html.join('')).show();
                    $('.mb-2.p-2').mouseenter(function () {
                        $(this).addClass('border-primary');
                    });
                    $('.mb-2.p-2').mouseleave(function () {
                        $(this).removeClass('border-primary');
                    })
                } else {
                    toast('选择的Excel无有效数据，请重新选择', 'hint');
                    $('#upload-ledger-sheets').hide();
                }
            });
        } catch(err) {
            toast('加载excel异常，请刷新当前页面', 'error');
            $('#upload-ledger-sheets').hide();
        }
    });
    // 上传excel内容，并导入
    $('#upload-ledger-ok').click(function () {
        const sheetName = $('input[name=sheetName]:checked').val();
        if (sheetName) {
            const sheet = {
                rows: xlsxUtils.getSheetByName(sheetName, {header: 1}),
                merge: xlsxUtils._wb.Sheets[sheetName]["!merges"]
            };
            postDataCompress(window.location.pathname + '/upload-excel', sheet, function (result) {
                ledgerTree.loadDatas(result.bills);
                treeCalc.calculateAll(ledgerTree);
                SpreadJsObj.loadSheetData(ledgerSpread.getActiveSheet(), 'tree', ledgerTree);
                pos.loadDatas(result.pos);
                posOperationObj.loadCurPosData();
                $('#upload-ledger').modal('hide');
            });
        }
    });
    $('#upload-ledger').bind('hidden.bs.modal', function () {
        $('#upload-ledger-file').val('');
        $('#upload-ledger-sheets').html('');
    });

    $('#hideSp').click(function () {
        $('#sp-list2').modal('hide');
    });
    // 显示层次
    (function (select, sheet) {
        if (!sheet.zh_tree) return;
        $(select).click(function () {
            const tag = $(this).attr('tag');
            const tree = sheet.zh_tree;
            switch (tag) {
                case "1":
                case "2":
                case "3":
                case "4":
                case "5":
                    tree.expandByLevel(parseInt(tag));
                    SpreadJsObj.refreshTreeRowVisible(sheet);
                    break;
                case "last":
                    tree.expandByCustom(() => { return true; });
                    SpreadJsObj.refreshTreeRowVisible(sheet);
                    break;
                case "leafXmj":
                    tree.expandToLeafXmj();
                    SpreadJsObj.refreshTreeRowVisible(sheet);
                    break;
            }
        });
    })('a[name=showLevel]', ledgerSpread.getActiveSheet());
});



// 检查上报情况
function checkAuditorFrom () {
    if ($('#auditors li').length === 0) {
        toast('请先选择审批人，再上报数据', 'error', 'exclamation-circle');
        return false;
    }
}

