'use strict';
/**
 * 期计量 - 本期计量台账页面 js
 *
 * @author Mai
 * @date 2018/12/7
 * @version
 */
const ckBillsSpread = window.location.pathname + '-billsSelect';
function checkTzMeasureType () {
    return tender.measure_type === measureType.tz.value;
}
function transExpr(expr) {
    return $.trim(expr).replace('\t', '').replace('=', '').replace('%', '/100');
}
function getExprInfo (field) {
    const exprField = [
        {qty: 'sgfh_qty', expr: 'sgfh_expr'},
        {qty: 'sjcl_qty', expr: 'sjcl_expr'},
        {qty: 'qtcl_qty', expr: 'qtcl_expr'},
        {qty: 'contract_qty', expr: 'contract_expr'},
    ];
    return _.find(exprField, {qty: field});
}
/**
 * 从cookie中读取缓存的列显示设置,没有则取默认
 * @returns {*[]}
 */
function customColDisplay () {
    const defaultSetting = [
        { title: '签约合同', fields: ['deal_qty', 'deal_tp'], visible: true },
        { title: '本期计量合同', fields: ['contract_qty', 'contract_tp'], visible: true },
        { title: '本期数量变更', fields: ['qc_qty', 'qc_tp', 'qc_bgl'], visible: true },
        { title: '本期完成计量', fields: ['gather_qty', 'gather_tp'], visible: true },
        { title: '截止本期计量合同', fields: ['end_contract_qty', 'end_contract_tp'], visible: true },
        { title: '截止本期数量变更', fields: ['end_qc_qty', 'end_qc_tp', 'end_qc_bgl'], visible: true },
        { title: '截止本期完成计量', fields: ['end_gather_qty', 'end_gather_tp', 'end_gather_percent'], visible: true },
        { title: '本期批注', fields: ['postil'], visible: true },
        { title: '图册号', fields: ['drawing_code'], visible: true },
        { title: '备注', fields: ['memo'], visible: true },
        { title: '总额计量', fields: ['is_tp'], visible: true},
    ];
    if (checkTzMeasureType()) {
        defaultSetting.splice(0, 1);
    }
    const settingStr = Cookies.get(ckColSetting);
    return settingStr ? JSON.parse(settingStr) : defaultSetting;
}
/**
 * 根据列显示设置,调整setting中的列是否显示
 * @param setting
 * @param customDisplay
 */
function customizeStageTreeSetting(setting, customDisplay) {
    for (const cd of customDisplay) {
        for (const c of setting.cols) {
            if (cd.fields.indexOf(c.field) !== -1) {
                c.visible = cd.visible;
            }
        }
    }
}
/**
 * 初始化 树结构 列事件
 * @param setting
 */
function initTreeColSettingEvents(setting) {
    const Events = {
        readOnly: {
            measureData: function (node) {
                return node.children && node.children.length > 0;
            },
        },
    };
    const getEvent = function (eventName) {
        const names = eventName.split('.');
        let event = Events;
        for (let name of names) {
            if (event[name]) {
                event = event[name];
            } else {
                return null;
            }
        }
        if (event && Object.prototype.toString.apply(event) !== "[object Function]") {
            return null;
        } else {
            return event;
        }
    };
    for (const col of setting.cols) {
        if (col.readOnly && Object.prototype.toString.apply(col.readOnly) === "[object String]") {
            col.readOnly = getEvent(col.readOnly);
        }
    }
}
// 生成所有附件列表
function getAllList(currPageNum = 1) {
    // 每页最多几个附件
    const pageCount = 15;
    // 附件总数
    const total = attData.length;
    // 总页数
    const pageNum = Math.ceil(total/pageCount);
    $('#totalPage').text(pageNum);
    $('#currentPage').text(total === 0 ? 0 : currPageNum);
    // 当前页附件内容
    const currPageAttData = attData.slice((currPageNum-1)*pageCount, currPageNum*pageCount);
    let html = '';
    // '/tender/' + tender.id + '/measure/stage/' + stage.order + '/download/file/' + att.id
    for(const att of currPageAttData) {
        html += `
        
        
         ${att.username}  `
    }
    $('#alllist-table').html(html);
    $('#alllist-table').on('click', 'tr', function() {
        $('#alllist-table tr').removeClass('bg-light')
        $(this).addClass('bg-light')
    })
}
// 生成当前节点列表
function getNodeList(node) {
    let html = '';
    for(const att of attData) {
        if (node === att.lid) {
            // html += ''+ att.filename + att.fileext +' '+ att.username +' 
            
            
             ${att.username}  `
        }
    }
    $('#nodelist-table').html(html);
    $('#nodelist-table').on('click', 'tr', function() {
        $('#nodelist-table tr').removeClass('bg-light')
        $(this).addClass('bg-light')
    })
}
function getGxbyText(data) {
    const def = thirdParty.gxby.find(function (x) {
        return x.value === data.gxby_status;
    });
    return def ? def.name : '';
}
function getDaglText(data) {
    const def = thirdParty.dagl.find(function (x) {
        return x.value === data.dagl_status;
    });
    return def ? def.name : '';
}
$(document).ready(() => {
    let detail, searchLedger, checkedChanges;
    // 界面布局
    autoFlashHeight();
    // 初始化 台账树结构 数据结构
    const stageTreeSetting = {
        id: 'ledger_id',
        pid: 'ledger_pid',
        order: 'order',
        level: 'level',
        rootId: -1,
        keys: ['id', 'tender_id', 'ledger_id'],
        stageId: 'id',
        markFoldKey: 'bills-fold',
        markFoldSubKey: window.location.pathname.split('/')[2],
    };
    // 台账树结构计算相关设置
    stageTreeSetting.updateFields = ['contract_qty', 'contract_tp', 'qc_qty', 'qc_tp', 'postil', 'used', 'contract_expr'];
    stageTreeSetting.calcFields = ['deal_tp', 'total_price', 'contract_tp', 'qc_tp', 'gather_tp',
        'pre_contract_tp', 'pre_qc_tp', 'pre_gather_tp', 'end_contract_tp', 'end_qc_tp', 'end_gather_tp'];
    stageTreeSetting.calcFun = function (node) {
        if (node.children && node.children.length === 0) {
            node.pre_gather_qty = ZhCalc.add(node.pre_contract_qty, node.pre_qc_qty);
            node.gather_qty = ZhCalc.add(node.contract_qty, node.qc_qty);
            node.end_contract_qty = ZhCalc.add(node.pre_contract_qty, node.contract_qty);
            node.end_qc_qty = ZhCalc.add(node.pre_qc_qty, node.qc_qty);
            node.end_gather_qty = ZhCalc.add(node.pre_gather_qty, node.gather_qty);
        }
        node.pre_gather_tp = ZhCalc.add(node.pre_contract_tp, node.pre_qc_tp);
        node.gather_tp = ZhCalc.add(node.contract_tp, node.qc_tp);
        node.end_contract_tp = ZhCalc.add(node.pre_contract_tp, node.contract_tp);
        node.end_qc_tp = ZhCalc.add(node.pre_qc_tp, node.qc_tp);
        node.end_gather_tp = ZhCalc.add(node.pre_gather_tp, node.gather_tp);
        node.end_final_tp = ZhCalc.add(node.end_qc_tp, node.total_price);
        node.end_gather_percent = ZhCalc.mul(ZhCalc.div(node.end_gather_tp, node.end_final_tp), 100, 2);
        node.final_dgn_price = ZhCalc.round(ZhCalc.div(node.end_gather_tp, ZhCalc.add(node.deal_dgn_qty1, node.c_dgn_qty1)), tenderInfo.decimal.up);
    };
    const stageTree = createNewPathTree('stage', stageTreeSetting);
    // 初始化 计量单元 数据结构
    const stagePosSetting = {
        id: 'id', ledgerId: 'lid',
        updateFields: ['contract_qty', 'qc_qty', 'postil', 'contract_expr'],
    };
    stagePosSetting.calcFun = function (pos) {
        pos.pre_gather_qty = ZhCalc.add(pos.pre_contract_qty, pos.pre_qc_qty);
        pos.gather_qty = ZhCalc.add(pos.contract_qty, pos.qc_qty);
        pos.end_contract_qty = ZhCalc.add(pos.pre_contract_qty, pos.contract_qty);
        pos.end_qc_qty = ZhCalc.add(pos.pre_qc_qty, pos.qc_qty);
        pos.end_gather_qty = ZhCalc.add(pos.pre_gather_qty, pos.gather_qty);
        pos.sum = ZhCalc.add(pos.end_qc_qty, pos.quantity);
        pos.end_gather_percent = ZhCalc.mul(ZhCalc.div(pos.end_gather_qty, pos.sum), 100, 2);
        pos.estimate_qty = !checkZero(pos.real_qty)
            ? ZhCalc.sub(ZhCalc.sub(pos.real_qty, pos.quantity), pos.end_qc_qty)
            : null;
    };
    const stagePos = new StagePosData(stagePosSetting);
    class Changes {
        constructor(obj) {
            const self = this;
            this.obj = obj;
            // 初始化 清单编号窗口 参数
            this.spreadSetting = {
                cols: [
                    {title: '已用', field: '', width: 45, formatter: '@', cellType: 'image', readOnly: true, hAlign: 1, indent: 14, img: function (data) {
                        if (data.uamount && !checkZero(data.uamount)) {
                            return $('#icon-ok')[0];
                        } else {
                            return null;
                        }
                    }},
                    {title: '变更令号', field: 'p_code', width: 100, formatter: '@', readOnly: true, hAlign: 0, },
                    {title: '名称', field: 'name', width: 120, formatter: '@', readOnly: true, hAlign: 0,},
                    {title: '变更部位', field: 'b_bwmx', width: 100, formatter: '@', readOnly: true, hAlign: 0,},
                    //{title: '总数量', field: 'b_amount', width: 60, readOnly: true, hAlign: 2, },
                    {title: '可变更数量', field: 'vamount', width: 60, readOnly: true, hAlign: 2, type: 'Number', getValue: function (data) {return data.vamount ? data.vamount + '' : '0';}},
                    {title: '本期计量', field: 'uamount', width: 60, hAlign: 2, type: 'Number', },
                ],
                emptyRows: 0,
                headRows: 1,
                headRowHeight: [32],
                headerFont: '12px 微软雅黑',
                font: '12px 微软雅黑',
                getColor: function (sheet, data, row, col, defaultColor) {
                    if (col.field === 'uamount') {
                        if (data.bamount > 0) {
                            const usedAmount = ZhCalc.add(data.uamount, data.pre_amount);
                            return usedAmount < 0 || usedAmount > data.bamount ? '#ff6f5c' : defaultColor;
                        } else if (data.bamount < 0) {
                            const usedAmount = ZhCalc.add(data.uamount, data.pre_amount);
                            return usedAmount > 0 || usedAmount < data.bamount ? '#ff6f5c' : defaultColor;
                        } else {
                            return data.uamount ? '#ff6f5c' : defaultColor;
                        }
                    } else {
                        return defaultColor;
                    }
                }
            };
            this.curChangeId = '';
            this.spread = SpreadJsObj.createNewSpread($('#change-spread')[0]);
            this.firstView = true;
            SpreadJsObj.initSheet(this.spread.getActiveSheet(), this.spreadSetting);
            // 初次显示,需刷新spread界面,保证界面绘制正确
            this.obj.bind('shown.bs.modal', function () {
                if (self.firstView) {
                    self.firstView = false;
                    self.spread.refresh();
                }
            });
            // 切换变更令,加载右侧明细数据
            this.spread.bind(spreadNS.Events.SelectionChanged, function (e, info) {
                const change = SpreadJsObj.getSelectObject(info.sheet);
                self._loadChangeDetail(change);
            });
            // 填写本期计量
            this.spread.bind(spreadNS.Events.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];
                    node[col.field] = col.type === 'Number' ? parseFloat(info.editingText) : info.editingText;
                    // 刷新界面
                    SpreadJsObj.reLoadRowData(info.sheet, info.row, 1);
                }
            });
            this.spread.bind(spreadNS.Events.ClipboardPasted, function (e, info) {
                if (info.sheet.zh_setting) {
                    const sortData = SpreadJsObj.getSortData(info.sheet);
                    for (let iRow = 0; iRow < info.cellRange.rowCount; iRow++) {
                        const curRow = iRow + info.cellRange.row;
                        const curCol = info.cellRange.col;
                        const col = info.sheet.zh_setting.cols[info.cellRange.col];
                        sortData[curRow][col.field] = col.type === 'Number' ? _.toNumber(info.sheet.getText(curRow, curCol)) : info.sheet.getText(curRow, curCol);
                    }
                    SpreadJsObj.reLoadRowData(sheet, info.cellRange.row, sel.cellRange.rowCount);
                }
            });
            SpreadJsObj.addDeleteBind(this.spread, function (sheet) {
                if (sheet.zh_setting) {
                    const sel = sheet.getSelections()[0];
                    const sortData = SpreadJsObj.getSortData(sheet);
                    // 仅本期计量可删除
                    if (sel.col === 5 && sel.colCount === 1) {
                        const col = sheet.zh_setting.cols[sel.col];
                        for (let iRow = sel.row; iRow < sel.row + sel.rowCount; iRow++) {
                            const data = sortData[iRow];
                            data[col.field] = null;
                        }
                        SpreadJsObj.reLoadRowData(sheet, sel.row, sel.rowCount);
                    }
                }
            });
            // 过滤可变更数量为0
            $('#filterEmpty').click(function () {
                self._filterChange(!this.checked, $('#matchPos')[0].checked);
            });
            // 匹配编号
            $('#matchPos').click(function () {
                self._filterChange(!$('#filterEmpty')[0].checked, this.checked);
            });
            // 展开收起 变更令详细信息
            $('#show-bgl-detail').bind('click', function () {
                const detail = $('#bgl-detail'), bgl=$('#bgl'), obj=$(this);
                if (detail.hasClass('col-4')) {
                    detail.attr('class', 'col').hide();
                    bgl.attr('class', 'col-12');
                    $('a', obj).attr('title', '展开侧栏');
                    $('i', obj).attr('class', 'fa fa-chevron-left');
                    self.spread.refresh();
                } else {
                    detail.attr('class', 'col-4').show();
                    bgl.attr('class', 'col-8');
                    $('a', obj).attr('title', '收起侧栏');
                    $('i', obj).attr('class', 'fa fa-chevron-right');
                    self.spread.refresh();
                }
            });
            // 添加调用变更令
            $('#usg-bg-ok').click(function () {
                const data = { target: self.callData, change: [] };
                for (const c of self.displayChanges) {
                    if (c.uamount) {
                        if (c.bamount > 0) {
                            const usedAmount = ZhCalc.add(c.uamount, c.pre_amount);
                            if (usedAmount < 0 || usedAmount > c.bamount) {
                                toastr.error('变更令:' + c.code + ' 超计,请修改本期计量后,再提交');
                                return;
                            }
                        } else if (c.bamount < 0) {
                            const usedAmount = ZhCalc.add(c.uamount, c.pre_amount);
                            if (usedAmount > 0 || usedAmount < c.bamount) {
                                toastr.error('变更令:' + c.code + ' 超计,请修改本期计量后,再提交');
                                return;
                            }
                        } else {
                            toastr.error('变更令:' + c.code + ' 超计,请修改本期计量后,再提交');
                            return;
                        }
                        data.change.push({ cid: c.cid, cbid: c.cbid, qty: c.uamount });
                    }
                }
                // 提交数据到后端
                postData(window.location.pathname + '/use-change', data, function(result) {
                    if (result.pos) {
                        stagePos.loadCurStageData(result.pos.curStageData);
                    }
                    const nodes = stageTree.loadPostStageData(result.bills);
                    stageTreeSpreadObj.refreshTreeNodes(slSpread.getActiveSheet(), nodes);
                    stagePosSpreadObj.loadCurPosData();
                    if (detail) {
                        detail.loadStageChangeUpdateData(result);
                    } else {
                        stageIm.loadUpdateChangeData(result)
                    }
                    self.obj.modal('hide');
                });
            })
        }
        _calculateAmount() {
            for (const c of this.changes) {
                c.bamount = _.toNumber(c.b_amount);
                c.vamount = ZhCalc.sub(c.bamount, c.used_amount);
                const uc = _.find(this.useChanges, {cid: c.cid, cbid: c.cbid});
                if (uc) {
                    c.org_uamount = uc.qty;
                    c.uamount = uc.qty;
                    c.vamount = ZhCalc.add(c.vamount, c.uamount);
                }
                c.pre_amount = ZhCalc.sub(c.used_amount, c.uamount);
            }
        }
        _loadChangeDetail(change) {
            if (change) {
                if (change.cid === this.curChangeId) { return; }
                this.curChangeId = change.cid;
                const inputs = $('input[type!=checkbox][type!=radio]', this.obj);
                for (const i of inputs) {
                    const field = $(i).attr('name');
                    const text = (field && change[field]) ? change[field] : '';
                    $(i).val(text);
                }
                const textareas = $('textarea', this.obj);
                for (const ta of textareas) {
                    const field = $(ta).attr('name');
                    const text = (field && change[field]) ? change[field] : '';
                    ta.textContent = text;
                }
                const html = [];
                for (const a of change.attachments) {
                    html.push('');
                    html.push('', '', a.filename + a.fileext, ' ', ' ');
                    html.push('', a.u_name, ' ');
                    html.push(' ');
                }
                // 变更类型
                if (change.type) {
                    const cType = change.type.split(',');
                    $('input[name="type"]').prop("checked", false);
                    for (const c of cType) {
                        $('input[name="type"][value='+ c +']').prop("checked", true);
                    }
                }
                // 变更类别
                $('select[name=class]').val(change.class);
                // 变更性质
                $('select[name=quality]').val(change.quality);
                // 变更单位
                $('select[name=company]').html('' + (change.company ? change.company : '') + ' ');
                // 费用承担方
                $('input[name=charge][value=' + change.charge + ']').prop('checked', true);
                // 附件
                $('#attachment').html(html.join(''));
            } else {
                const inputs = $('input', this.obj);
                for (const i of inputs) {
                    $(i).val('');
                }
                const textareas = $('textarea', this.obj);
                for (const ta of textareas) {
                    ta.innerText = '';
                }
                $('#attachment').html('');
            }
        }
        _viewChanges() {
            const sheet = this.spread.getActiveSheet();
            if (this.changes) {
                sheet.setSelection(0, 0, 1, 1);
                this._filterChange(!$('#filterEmpty')[0].checked, $('#matchPos')[0].checked);
                this._loadChangeDetail(this.changes[0]);
            } else {
                toastr.error('查询变更令有误,请刷新页面后重试');
            }
        }
        _filterChange(filterEmpty, matchPosName) {
            this.displayChanges = [];
            for (const c of this.changes) {
                const filterVisible = filterEmpty ? (c.vamount ? !checkZero(c.vamount) : false) : true;
                const matchVisible = matchPosName && this.callData.pos ? c.b_bwmx === this.callData.pos.name : true;
                if ((filterVisible && matchVisible) || (c.org_uamount)) {
                    this.displayChanges.push(c);
                }
            }
            SpreadJsObj.loadSheetData(this.spread.getActiveSheet(), SpreadJsObj.DataType.Data, this.displayChanges);
        }
        loadChanges(data) {
            this.callData = data;
            if (this.callData.pos) {
                $('#matchPos').parent().show();
            } else {
                $('#matchPos').parent().hide();
            }
            const self = this;
            $('#b-code-hint').text('当前变更清单:' + data.bills.b_code);
            postData(window.location.pathname + '/valid-change', data, function (result) {
                self.changes = result.changes;
                self.useChanges = result.useChanges;
                self._calculateAmount();
                self._viewChanges();
                self.obj.modal('show');
            });
        }
    }
    const changesObj = new Changes($('#use-bg'));
    // 初始化 台账 spread
    const slSpread = SpreadJsObj.createNewSpread($('#stage-ledger')[0]);
    customizeStageTreeSetting(ledgerSpreadSetting, customColDisplay());
    // 数量变更列,添加按钮
    const col = _.find(ledgerSpreadSetting.cols, {field: 'qc_qty'});
    col.readOnly = true;
    col.cellType = 'activeImageBtn';
    col.normalImg = '#ellipsis-icon';
    col.indent = 5;
    col.showImage = function (data) {
        if (!data || (data.children && data.children.length > 0) || !(data.b_code && data.b_code !== '')) {
            return false;
        } else {
            const nodePos = stagePos.getLedgerPos(data.id);
            return !(nodePos && nodePos.length > 0);
        }
    };
    ledgerSpreadSetting.imageClick = function (data) {
        if (data.children && data.children.length > 0) return;
        const nodePos = stagePos.getLedgerPos(data.id);
        if (nodePos && nodePos.length > 0) return;
        changesObj.loadChanges({bills: data});
    };
    ledgerSpreadSetting.dgnUpFields = ['deal_dgn_qty1', 'deal_dgn_qty2', 'c_dgn_qty1', 'c_dgn_qty2'];
    ledgerSpreadSetting.getColor = function (sheet, data, row, col, defaultColor) {
        if (data) {
            if (col.field === 'gxby') {
                const def = thirdParty.gxby.find(function (x) {
                    return x.value === data.gxby_status;
                });
                if (def && def.color) return def.color;
            } else if (col.field === 'dagl') {
                const def = thirdParty.dagl.find(function (x) {
                    return x.value === data.dagl_status;
                });
                if (def && def.color) return def.color;
            }
            if (checkTzMeasureType()) {
                const posRange = stagePos.ledgerPos[itemsPre + data.id] || [];
                if (posRange.length > 0) {
                    for (const p of posRange) {
                        if (p.end_contract_qty > p.quantity) return '#f8d7da';
                    }
                }
                if (data.is_tp) {
                    return data.end_contract_tp > data.total_price ? '#f8d7da' : defaultColor;
                } else {
                    return data.end_contract_qty > data.quantity ? '#f8d7da' : defaultColor;
                }
            } else {
                if (data.is_tp) {
                    return data.end_contract_tp > data.deal_tp ? '#f8d7da' : defaultColor;
                } else {
                    return data.end_contract_qty > data.deal_qty ? '#f8d7da' : defaultColor;
                }
            }
        } else {
            return defaultColor;
        }
    };
    sjsSettingObj.setFxTreeStyle(ledgerSpreadSetting, sjsSettingObj.FxTreeStyle.jz);
    sjsSettingObj.setPropValue(ledgerSpreadSetting, ['gxby'], 'getValue', getGxbyText);
    sjsSettingObj.setPropValue(ledgerSpreadSetting, ['dagl'], 'getValue', getDaglText);
    if (thousandth) sjsSettingObj.setTpThousandthFormat(ledgerSpreadSetting);
    SpreadJsObj.initSheet(slSpread.getActiveSheet(), ledgerSpreadSetting);
    slSpread.getActiveSheet().frozenColumnCount(5);
    slSpread.getActiveSheet().options.frozenlineColor = '#93b5e4';
    //初始化所有附件列表
    getAllList();
    // 初始化 计量单元 Spread
    const spSpread = SpreadJsObj.createNewSpread($('#stage-pos')[0]);
    const spCol = _.find(posSpreadSetting.cols, {field: 'qc_qty'});
    spCol.readOnly = true;
    spCol.cellType = 'activeImageBtn';
    spCol.normalImg = '#ellipsis-icon';
    spCol.indent = 5;
    spCol.showImage = function (data) {
        return data !== undefined && data !== null;
    };
    posSpreadSetting.imageClick = function (data) {
        const node = SpreadJsObj.getSelectObject(slSpread.getActiveSheet());
        changesObj.loadChanges({bills: node, pos: data});
    };
    posSpreadSetting.getColor = function (sheet, data, row, col, defaultColor) {
        if (data) {
            if (col.field === 'gxby') {
                const def = thirdParty.gxby.find(function (x) {
                    return x.value === data.gxby_status;
                });
                if (def && def.color) return def.color;
            } else if (col.field === 'dagl') {
                const def = thirdParty.dagl.find(function (x) {
                    return x.value === data.dagl_status;
                });
                if (def && def.color) return def.color;
            }
        }
        return data && data.end_contract_qty > data.quantity ? '#f8d7da' : defaultColor;
    };
    sjsSettingObj.setGridSelectStyle(posSpreadSetting);
    if (thousandth) sjsSettingObj.setTpThousandthFormat(posSpreadSetting);
    sjsSettingObj.setPropValue(posSpreadSetting, ['gxby'], 'getValue', getGxbyText);
    sjsSettingObj.setPropValue(posSpreadSetting, ['dagl'], 'getValue', getDaglText);
    SpreadJsObj.initSheet(spSpread.getActiveSheet(), posSpreadSetting);
    const errorList = $.cs_errorList({
        tabSelector: '#error-list-tab',
        selector: '#error-list',
        relaSpread: slSpread,
        storeKey: 'stage-error-' + stage.id,
        afterLocated:  function () {
            stagePosSpreadObj.loadCurPosData();
        },
        afterShow: function () {
            slSpread.refresh();
            if (spSpread) spSpread.refresh();
        },
    });
    const checkList = $.ledger_checkList({
        id: 'check-list',
        tabSelector: '#check-list-tab',
        selector: '#check-list',
        relaSpread: slSpread,
        storeKey: 'stage-check-' + window.location.pathname.split('/')[2] + '-' + window.location.pathname.split('/')[4],
        checkType: ledgerCheckType,
        afterLocated:  function () {
            stagePosSpreadObj.loadCurPosData();
        },
        afterShow: function () {
            slSpread.refresh();
            if (spSpread) spSpread.refresh();
        },
    });
    const stageTreeSpreadObj = {
        loadExprToInput(sheet) {
            const sel = sheet.getSelections()[0];
            const col = sheet.zh_setting.cols[sel.col], cell = sheet.getCell(sel.row, sel.col);
            if (col.type === 'Number') {
                const data = SpreadJsObj.getSelectObject(sheet);
                if (!data) {
                    $('#bills-expr').val('').attr('readOnly', true);
                    $('#bills-expr').removeAttr('data-row');
                    return;
                }
                const nodePos = stagePos.getLedgerPos(data.id);
                if (nodePos && nodePos.length > 0) {
                    $('#bills-expr').val('').attr('readOnly', true);
                } else {
                    const exprInfo = getExprInfo(col.field);
                    const value = exprInfo && data[exprInfo.expr] ? data[exprInfo.expr] : data[col.field];
                    $('#bills-expr').val(value).attr('field', col.field).attr('org', data[col.field]);
                    if (col.field.indexOf('tp') >= 0) {
                        $('#bills-expr').attr('readOnly', readOnly || cell.locked() || data.is_tp !== 1);
                    } else {
                        $('#bills-expr').attr('readOnly', readOnly || cell.locked() || data.is_tp === 1)
                    }
                }
                $('#bills-expr').attr('data-row', sel.row);
            } else {
                $('#bills-expr').val('').attr('readOnly', true);
                $('#bills-expr').removeAttr('data-row');
            }
        },
        refreshTreeNodes: function (sheet, nodes) {
            const tree = sheet.zh_tree;
            if (!tree) { return }
            const rows = [];
            for (const node of nodes) {
                rows.push(tree.nodes.indexOf(node));
            }
            SpreadJsObj.reLoadRowsData(sheet, rows);
        },
        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], updateData = {};
                const orgValue = node[col.field];
                let newValue = trimInvalidChar(info.editingText);
                if (orgValue == newValue || ((!orgValue || orgValue === '') && (!newValue || newValue === ''))) {
                    return;
                }
                if (col.type === 'Number' && newValue && newValue !== '') {
                    const num = _.toNumber(newValue);
                    if (_.isFinite(num)) {
                        newValue = num;
                    } else {
                        try {
                            newValue = math.evaluate(transExpr(newValue));
                        } catch(err) {
                            toastr.error('输入的表达式非法');
                            SpreadJsObj.reLoadRowData(info.sheet, info.row);
                            return;
                        }
                    }
                }
                if (col.field.indexOf('_dgn_') > 0) {
                    if (node.b_code && node.b_code !== '') {
                        toastr.error('仅项目节可输入项目节数量');
                        SpreadJsObj.reLoadRowData(info.sheet, info.row);
                        return;
                    }
                } else if (col.field !== 'postil' && col.field !== 'memo') {
                    if (node.children && node.children.length > 0) {
                        toastr.error('清单父项不可计量');
                        SpreadJsObj.reLoadRowData(info.sheet, info.row);
                        return;
                    } else {
                        const nodePos = stagePos.getLedgerPos(node.id);
                        if (nodePos && nodePos.length > 0) {
                            toastr.error('该清单有计量单元,请在计量单元处计量');
                            SpreadJsObj.reLoadRowData(info.sheet, info.row);
                            return;
                        }
                    }
                }
                if (col.field === 'memo') {
                    updateData.main = {
                        id: node.id
                    };
                    updateData.main[col.field] = newValue;
                } else if (col.field.indexOf('_dgn_') > 0) {
                    updateData.dgn = {
                        id: node.id
                    };
                    updateData.dgn[col.field] = newValue;
                } else if (col.field !== 'is_tp') {
                    updateData.stage = {
                        lid: node.id
                    };
                    updateData.stage[col.field] = newValue;
                    const exprInfo = getExprInfo(col.field);
                    if (exprInfo) {
                        updateData.stage[exprInfo.expr] = info.editingText !== newValue+ '' ? trimInvalidChar(info.editingText) : '';
                    }
                }
                postData(window.location.href + '/update', {bills: updateData}, function (data) {
                    // tag update
                    const nodes = stageTree.loadPostStageData(data);
                    stageTreeSpreadObj.refreshTreeNodes(slSpread.getActiveSheet(), nodes);
                    if (detail) {
                        detail.loadStageLedgerUpdateData(data);
                    } else {
                        stageIm.loadUpdateLedgerData(data);
                    }
                }, function () {
                    SpreadJsObj.reLoadRowData(info.sheet, info.row);
                });
            }
        },
        selectionChanged: function (e, info) {
            if (!info.oldSelections || !info.oldSelections[0] || info.newSelections[0].row !== info.oldSelections[0].row) {
                SpreadJsObj.resetTopAndSelect(spSpread.getActiveSheet());
                stagePosSpreadObj.loadCurPosData();
                if (posSearch) {
                    posSearch.search();
                }
            }
            SpreadJsObj.saveTopAndSelect(info.sheet, ckBillsSpread);
            stageTreeSpreadObj.loadExprToInput(info.sheet);
        },
        deletePress(sheet) {
            if (sheet.zh_setting && sheet.zh_dataType === 'tree') {
                const tree = sheet.zh_tree;
                if (!tree) { return; }
                const sel = sheet.getSelections()[0];
                const validCols = [];
                for (let iCol = sel.col; iCol < sel.col + sel.colCount; iCol++) {
                    const colSetting = sheet.zh_setting.cols[iCol];
                    if (!colSetting.readOnly && colSetting.field !== 'qc_qty') {
                        validCols.push(iCol);
                    }
                }
                if (validCols.length === 0) { return; }
                const sortData = sheet.zh_tree.nodes;
                const datas = [], dgnDatas = [], mainDatas = [];
                for (let iRow = sel.row; iRow < sel.row + sel.rowCount; iRow++) {
                    const node = sortData[iRow];
                    if (node) {
                        const data = { lid: node.id }, dgnData = { id: node.id }, mainData = { id: node.id };
                        let filter = true, filterDgn = true, filterMain = true;
                        for (const iCol of validCols) {
                            const colSetting = sheet.zh_setting.cols[iCol];
                            if (sheet.zh_setting.dgnUpFields.indexOf(colSetting.field) !== -1) {
                                if (node.b_code && node.b_code !== '') continue;
                            } else if (colSetting.field !== 'postil') {
                                if (node.children && node.children.length > 0) { continue; }
                                const nodePos = stagePos.getLedgerPos(node.id);
                                if (nodePos && nodePos.length > 0) { continue; }
                            }
                            if (sheet.zh_setting.dgnUpFields.indexOf(colSetting.field) !== -1) {
                                if (node[colSetting.field] && node[colSetting.field] !== 0) {
                                    dgnData[colSetting.field] = 0;
                                    filterDgn = false;
                                }
                            } else if (colSetting.field === 'memo') {
                                mainData[colSetting.field] = null;
                                filterMain = false;
                            } else {
                                data[colSetting.field] = null;
                                const exprInfo = getExprInfo(colSetting.field);
                                if (exprInfo) {
                                    data[exprInfo.expr] = '';
                                }
                                filter = false;
                            }
                        }
                        if (!filter) datas.push(data);
                        if (!filterDgn) dgnDatas.push(dgnData);
                        if (!filterMain) mainDatas.push(mainData);
                    }
                }
                if (datas.length > 0 || dgnDatas.length > 0 || mainDatas.length > 0) {
                    const bills = {};
                    if (datas.length > 0) bills.stage = datas;
                    if (dgnDatas.length > 0) bills.dgn = dgnDatas;
                    if (mainDatas.length > 0) bills.main = mainDatas;
                    postData(window.location.href + '/update', {bills: bills}, function (result) {
                        const nodes = stageTree.loadPostStageData(result);
                        stageTreeSpreadObj.refreshTreeNodes(slSpread.getActiveSheet(), nodes);
                        if (detail) {
                            detail.loadStageLedgerUpdateData(result);
                        } else {
                            stageIm.loadUpdateLedgerData(result);
                        }
                        stageTreeSpreadObj.loadExprToInput(sheet);
                    });
                }
            }
        },
        clipboardPasting(e, info) {
            if (info.sheet.zh_setting) {
                const setting = info.sheet.zh_setting;
                const range = info.cellRange;
                const stageField = ['contract_qty', 'contract_tp', 'qc_qty', 'postil'];
                for (let iCol = range.col; iCol < range.col + range.colCount; iCol++) {
                    const col = info.sheet.zh_setting.cols[iCol];
                    if ((stageField.indexOf(col.field) === -1) && setting.dgnUpFields.indexOf(col.field) === -1
                        && col.field !== 'memo') {
                        toastr.error('不可修改此数据');
                        info.cancel = true;
                        return;
                    }
                }
            }
        },
        clipboardPasted(e, info) {
            if (info.sheet.zh_setting && info.sheet.zh_tree) {
                const sheet = info.sheet, setting = info.sheet.zh_setting;
                const filterNodes = [], datas = [], dgnDatas = [], mainDatas = [];
                let bHint = false;
                for (let iRow = 0; iRow < info.cellRange.rowCount; iRow++) {
                    const curRow = iRow + info.cellRange.row;
                    const node = sheet.zh_tree.getItemsByIndex(curRow);
                    const data = {lid: node.id}, dgnData = {id: node.id}, mainData = {id: node.id};
                    let filter = true, filterDgn = true, filterMain = true;
                    for (let iCol = 0; iCol < info.cellRange.colCount; iCol++) {
                        const curCol = info.cellRange.col + iCol;
                        const col = info.sheet.zh_setting.cols[curCol];
                        if (col.field === 'contract_tp') {
                            if (!node.is_tp) continue;
                        } else if (col.field === 'contract_qty') {
                            if (node.is_tp) continue;
                        }
                        if (setting.dgnUpFields.indexOf(col.field) !== -1) {
                            if (node.b_code && node.b_code !== '') continue;
                        } else if (col.field !== 'postil') {
                            if (node.children && node.children.length > 0) continue;
                            const nodePos = stagePos.getLedgerPos(node.id);
                            if (nodePos && nodePos.length > 0) continue;
                        }
                        const text = trimInvalidChar(sheet.getText(curRow, curCol));
                        if (setting.dgnUpFields.indexOf(col.field) !== -1) {
                            const num = _.toNumber(text);
                            if (num) {
                                dgnData[col.field] = num;
                                filterDgn = false;
                            } else {
                                try {
                                    dgnData[col.field] = math.evaluate(transExpr(text));
                                    filterDgn = false;
                                } catch(err) {
                                    if (!bHint) {
                                        toastr.warning('粘贴了非法表达式,已过滤');
                                        bHint = true;
                                    }
                                }
                            }
                        } else if (col.field === 'memo') {
                            mainData.memo = text;
                            filterMain = false;
                        } else {
                            if (col.type === 'Number') {
                                const num = _.toNumber(text);
                                if (_.isFinite(num)) {
                                    data[col.field] = num;
                                    filter = false;
                                } else {
                                    try {
                                        data[col.field] = math.evaluate(transExpr(text));
                                        const exprInfo = getExprInfo(col.field);
                                        if (exprInfo) {
                                            data[exprInfo.expr] = text;
                                        }
                                        filter = false;
                                    } catch(err) {
                                        if (!bHint) {
                                            toastr.warning('粘贴了非法表达式,已过滤');
                                            bHint = true;
                                        }
                                    }
                                }
                            } else {
                                data[col.field] = text;
                            }
                        }
                    }
                    if (filter && filterDgn && filterMain) {
                        filterNodes.push(node);
                    } else {
                        if (!filter) datas.push(data);
                        if (!filterDgn) dgnDatas.push(dgnData);
                        if (!filterMain) mainDatas.push(mainData);
                    }
                }
                if (datas.length > 0 || dgnDatas.length > 0 || mainDatas.length > 0) {
                    const updateData = {};
                    if (datas.length > 0) updateData.stage = datas;
                    if (dgnDatas.length > 0) updateData.dgn = dgnDatas;
                    if (mainDatas.length > 0) updateData.main = mainDatas;
                    postData(window.location.href + '/update', {bills: updateData}, function (data) {
                        const nodes = stageTree.loadPostStageData(data);
                        stageTreeSpreadObj.refreshTreeNodes(slSpread.getActiveSheet(), nodes.concat(filterNodes));
                        if (detail) {
                            detail.loadStageLedgerUpdateData(data);
                        } else {
                            stageIm.loadUpdateLedgerData(data);
                        }
                        stageTreeSpreadObj.loadExprToInput(sheet);
                    }, function () {
                        // todo
                        //stageTreeSpreadObj.refreshTreeNodes(slSpread.getActiveSheet(), filterNodes);
                    });
                } else {
                    stageTreeSpreadObj.refreshTreeNodes(slSpread.getActiveSheet(), filterNodes);
                }
            }
        },
        measureAllPosInNode(node, ratio = 1) {
            const posterity = stageTree.getPosterity(node);
            const data = {updateType: 'update', updateData: []};
            for (const p of posterity) {
                if (p.children && p.children.length > 0) continue;
                const posRange = stagePos.getLedgerPos(p.id);
                if (posRange && posRange.length > 0) {
                    for (const pr of posRange) {
                        if (pr.contract_qty && !checkZero(pr.contract_qty)) continue;
                        const validValue = ZhCalc.sub(pr.quantity, pr.end_contract_qty);
                        if (validValue <= 0) continue;
                        const value = ratio !== 1 ? ZhCalc.mul(pr.quantity, ratio) : pr.quantity;
                        const pData = {
                            pid: pr.id,
                            lid: pr.lid,
                            contract_qty: validValue > 0 ? (value > validValue ? validValue : value) : (value < validValue ? validValue : value),
                        };
                        data.updateData.push(pData);
                    }
                }
                if (data.updateData.length > 1000 || _.map(data.updateData, 'lid').length > 500) {
                    toastr.warning('选中的数据过多,仅计量' + data.updateData.length + '条,请稍后');
                    break;
                }
            }
            if (data.updateData.length === 0) {
                toastr.info('其下全部计量单元均已计量');
                return;
            }
            postData(window.location.pathname + '/update', {pos: data}, function (result) {
                if (result.pos) {
                    stagePos.updateDatas(result.pos.pos);
                    stagePos.loadCurStageData(result.pos.curStageData);
                }
                const nodes = stageTree.loadPostStageData(result.ledger);
                stageTreeSpreadObj.refreshTreeNodes(slSpread.getActiveSheet(), nodes);
                stagePosSpreadObj.loadCurPosData();
                if (detail) {
                    detail.loadStagePosUpdateData(result);
                } else {
                    stageIm.loadUpdatePosData(result);
                }
                toastr.success('已计量' + data.updateData.length + '条');
            }, function () {
                stagePosSpreadObj.loadCurPosData();
            });
        },
        topRowChanged(e, info) {
            SpreadJsObj.saveTopAndSelect(info.sheet, ckBillsSpread);
        },
        editStarting(e, info) {
            if (!info.sheet.zh_setting || !info.sheet.zh_tree) return;
            const col = info.sheet.zh_setting.cols[info.col];
            const node = info.sheet.zh_tree.nodes[info.row];
            const exprInfo = getExprInfo(col.field);
            if (exprInfo) {
                if (node[exprInfo.expr] && node[exprInfo.expr] !== '') {
                    info.sheet.getCell(info.row, info.col).text(node[exprInfo.expr]);
                }
            }
            switch (col.field) {
                case 'contract_qty':
                case 'qc_qty':
                    info.cancel = node.is_tp;
                    break;
                case 'contract_tp':
                    info.cancel = !node.is_tp;
                    break;
                case 'is_tp':
                    info.cancel = true;
                    break;
            }
        },
        buttonClicked: function (e, info) {
            if (info.sheet.zh_setting) {
                const node = SpreadJsObj.getSelectObject(info.sheet);
                const col = info.sheet.zh_setting.cols[info.col];
                const posRange = stagePos.getLedgerPos(node.id);
                if (node.pre_used === 1 ||
                    (node.children && node.children.length > 0) ||
                    (node.unit !== '总额' && node.unit !== '元') ||
                    (posRange && posRange.length > 0) /*|| !checkZero(node.qc_qty)*/) {
                    SpreadJsObj.reLoadRowData(info.sheet, info.row);
                    return;
                }
                const postIsTp = function () {
                    const data = { calcType: {id: node.id} };
                    data.calcType.is_tp = info.sheet.getValue(info.row, info.col) || false;
                    // 更新至服务器
                    postData(window.location.pathname + '/update', {bills: data}, function (result) {
                        const nodes = stageTree.loadPostStageData(result);
                        stageTreeSpreadObj.refreshTreeNodes(slSpread.getActiveSheet(), nodes);
                        if (detail) {
                            detail.loadStageLedgerUpdateData(result);
                        } else {
                            stageIm.loadUpdateLedgerData(result);
                        }
                    });
                };
                if (col.field === 'is_tp') {
                    if (info.sheet.isEditing()) {
                        info.sheet.endEdit(true);
                    }
                    if (!checkZero(node.contract_qty) || !checkZero(node.contract_tp)) {
                        $.msgBox({
                            id: 'calc-type',
                            title: '提示',
                            message: '切换计量模式,已计量数据会被清空。',
                            ok: {
                                caption: '确定',
                                callback: postIsTp,
                            },
                            cancel: {
                                caption: '取消',
                                callback: function () {
                                    SpreadJsObj.reLoadRowData(info.sheet, info.row);
                                }
                            }
                        });
                    } else {
                        postIsTp();
                    }
                }
            }
        },
        measureByBatch: function (posNames, ratio, apply2sibling) {
            if (posNames.length <= 0) return;
            if (ratio <= 0) return;
            const fRatio = ZhCalc.div(ratio, 100);
            const sheet = slSpread.getActiveSheet();
            const node = SpreadJsObj.getSelectObject(sheet);
            const parent = stageTree.getParent(node);
            const nodes = apply2sibling === true ? (parent ? parent.children : stageTree.children) : [node];
            const data = {updateType: 'batchUpdate', updateData: []};
            for (const node of nodes) {
                const posRange = stagePos.getLedgerPos(node.id);
                if (!posRange || posRange <= 0) continue;
                for (const p of posRange) {
                    if (posNames.indexOf(p.name) < 0) continue;
                    data.updateData.push({
                        pid: p.id, lid: p.lid,
                        contract_qty: ZhCalc.mul(p.quantity, fRatio),
                        contract_expr: `${p.quantity}*${ratio}%`,
                    });
                }
            }
            postData(window.location.pathname + '/update', {pos: data}, function (result) {
                if (result.pos) {
                    stagePos.updateDatas(result.pos.pos);
                    stagePos.loadCurStageData(result.pos.curStageData);
                }
                const nodes = stageTree.loadPostStageData(result.ledger);
                stageTreeSpreadObj.refreshTreeNodes(slSpread.getActiveSheet(), nodes);
                stagePosSpreadObj.loadCurPosData();
                if (detail) {
                    detail.loadStagePosUpdateData(result);
                } else {
                    stageIm.loadUpdatePosData(result);
                }
                $('#calc-by-ratio').modal('hide');
            }, function () {
                stagePosSpreadObj.loadCurPosData();
                $('#calc-by-ratio').modal('hide');
            });
        }
    };
    slSpread.bind(spreadNS.Events.EditEnded, stageTreeSpreadObj.editEnded);
    slSpread.bind(spreadNS.Events.SelectionChanged, stageTreeSpreadObj.selectionChanged);
    slSpread.bind(spreadNS.Events.ClipboardPasting, stageTreeSpreadObj.clipboardPasting);
    slSpread.bind(spreadNS.Events.ClipboardPasted, stageTreeSpreadObj.clipboardPasted);
    slSpread.bind(spreadNS.Events.TopRowChanged, stageTreeSpreadObj.topRowChanged);
    slSpread.bind(spreadNS.Events.EditStarting, stageTreeSpreadObj.editStarting);
    slSpread.bind(spreadNS.Events.ButtonClicked, stageTreeSpreadObj.buttonClicked);
    SpreadJsObj.addDeleteBind(slSpread, stageTreeSpreadObj.deletePress);
    if (!readOnly) {
        $('#bills-expr').bind('change onblur', function () {
            if (this.readOnly) return;
            const expr = $(this);
            const row = expr.attr('data-row') ? _.toInteger(expr.attr('data-row')) : -1;
            const select = stageTree.getItemsByIndex(row);
            if (!select) return;
            const field = expr.attr('field'), orgValue = expr.attr('org'), updateData = {};
            let newValue = expr.val();
            const num = _.toNumber(newValue);
            if (_.isFinite(num)) {
                newValue = num;
            } else {
                try {
                    newValue = math.evaluate(transExpr(newValue));
                } catch(err) {
                    toastr.error('输入的表达式非法');
                    return;
                }
            }
            if (orgValue === newValue || (!orgValue && newValue == '')) { return; }
            if (field.indexOf('_dgn_') > 0) {
                updateData.dgn = {
                    id: select.id
                };
                updateData.dgn[field] = newValue;
            } else {
                updateData.stage = {
                    lid: select.id
                };
                updateData.stage[field] = newValue;
                const exprInfo = getExprInfo(field);
                if (exprInfo) {
                    updateData.stage[exprInfo.expr] = expr.val();
                }
            }
            // 更新至服务器
            postData(window.location.pathname + '/update', {bills: updateData}, function (result) {
                const nodes = stageTree.loadPostStageData(result);
                stageTreeSpreadObj.refreshTreeNodes(slSpread.getActiveSheet(), nodes);
            });
        });
    }
    stageTreeSpreadObj.loadExprToInput(slSpread.getActiveSheet());
    $.contextMenu({
        selector: '#stage-ledger',
        build: function ($trigger, e) {
            const target = SpreadJsObj.safeRightClickSelection($trigger, e, slSpread);
            return target.hitTestType === spreadNS.SheetArea.viewport || target.hitTestType === spreadNS.SheetArea.rowHeader;
        },
        items: {
            'locateZjjl': {
                name: '定位至中间计量',
                icon: 'fa-sign-in',
                callback: function (key, opt) {
                    if (!detail) {
                        detail = new Detail($('#detail-spread'));
                    }
                    const node = SpreadJsObj.getSelectObject(slSpread.getActiveSheet());
                    const [leafUsedBills, usedPos] = stageIm.getFirstUsed(node);
                    if (leafUsedBills) {
                        if (!$('#zhongjian').hasClass('active')) {
                            const tab = $('#zhongjian'), tabPanel = $(tab.attr('content'));
                            $('a', '.side-menu').removeClass('active');
                            $('.tab-content .tab-select-show').removeClass('active');
                            tab.addClass('active');
                            tabPanel.addClass('active');
                            showSideTools(tab.hasClass('active'));
                            slSpread.refresh();
                            spSpread.refresh();
                        }
                        const relaXmj = stageIm.getRelaXmj(leafUsedBills);
                        const im = stageIm.getRelaImData(relaXmj, leafUsedBills, usedPos);
                        SpreadJsObj.locateData(detail.sheet, im);
                        detail.spread.refresh();
                        $('#zhongjian .sjs-bottom').height('400px');
                        $('.zhongjian-msg').height($('#zhongjian .sjs-bottom').height());
                        detail.reLoadDetailData();
                    } else {
                        toastr.error('无可定位中间计量');
                    }
                },
            },
        }
    });
    const stagePosSpreadObj = {
        loadExprToInput(sheet) {
            const sel = sheet.getSelections()[0];
            if (!sel) return;
            const col = sheet.zh_setting.cols[sel.col], cell = sheet.getCell(sel.row, sel.col);
            if (col && col.type === 'Number') {
                const data = SpreadJsObj.getSelectObject(sheet);
                if (data) {
                    const exprInfo = getExprInfo(col.field);
                    const value = exprInfo && data[exprInfo.expr] ? data[exprInfo.expr] : data[col.field];
                    $('#pos-expr').val(value).attr('field', col.field).attr('org', data[col.field])
                        .attr('readOnly', readOnly || cell.locked());
                    $('#pos-expr').attr('data-row', sel.row);
                } else {
                    $('#pos-expr').val('').attr('readOnly', true);
                    $('#pos-expr').removeAttr('data-row');
                }
            } else {
                $('#pos-expr').val('').attr('readOnly', true);
                $('#pos-expr').removeAttr('data-row');
            }
        },
        /**
         * 加载计量单元 根据当前台账选择节点
         */
        loadCurPosData: function () {
            const node = SpreadJsObj.getSelectObject(slSpread.getActiveSheet());
            if (node) {
                const posData = stagePos.ledgerPos[itemsPre + node.id] || [];
                SpreadJsObj.loadSheetData(spSpread.getActiveSheet(), 'data', posData);
                getNodeList(node.id);
                // 如果是附件是当前节点,隐藏
                // if ($('#dqjiedian').hasClass('active')) {
                //     $('#showAttachment').hide();
                // }
            } else {
                SpreadJsObj.loadSheetData(spSpread.getActiveSheet(), 'data', []);
            }
            stagePosSpreadObj.loadExprToInput(spSpread.getActiveSheet());
        },
        editEnded: function (e, info) {
            if (info.sheet.zh_setting) {
                // 未改变过,则直接跳过
                const sortData = info.sheet.zh_data;
                const posData = sortData ? sortData[info.row] : null;
                const col = info.sheet.zh_setting.cols[info.col];
                const orgText = posData ? posData[col.field] : null;
                const newText = trimInvalidChar(info.editingText);
                if (orgText === info.editingText || ((!orgText || orgText === '') && (newText === ''))) {
                    return;
                }
                // 台账模式下,不可新增
                if (checkTzMeasureType() && !posData) {
                    toastr.error('台账模式不可新增计量单元数据');
                    SpreadJsObj.reLoadRowData(info.sheet, info.row);
                    return ;
                }
                // 不同节点下,计量单元检查输入
                //const node = SpreadJsObj.getSelectObject(slSpread.getActiveSheet());
                const node = stagePosSpreadObj.stageTreeNode;
                if (!node) {
                    toastr.warning('数据错误, 请刷新页面后再试');
                    SpreadJsObj.reLoadRowData(info.sheet, info.row);
                    return;
                } else if (newText !== '' && node.children && node.children > 0) {
                    toastr.error('父节点不可插入计量单元');
                    SpreadJsObj.reLoadRowData(info.sheet, info.row);
                    return;
                } else if (newText !== '' && !node.b_code || node.b_code === '') {
                    toastr.error('项目节不可插入计量单元');
                    SpreadJsObj.reLoadRowData(info.sheet, info.row);
                    return;
                }
                // 生成提交数据
                const data = {};
                if (col.field === 'name') {
                    if ((!newText || newText === '') && posData) {
                        toastr.error('部位名称不可为空');
                        SpreadJsObj.reLoadRowData(info.sheet, info.row);
                        return;
                    } else if (!posData) {
                        if (newText !== '') {
                            data.updateType = 'add';
                            if ((node.pre_used === 1 || !checkZero(node.gather_qty) || !checkZero(node.gather_tp)) && sortData.length === 0) {
                                toastr.error('无计量单元的清单,计量后,不可新增计量单元');
                                SpreadJsObj.reLoadRowData(info.sheet, info.row);
                                return;
                            }
                            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 {
                            SpreadJsObj.reLoadRowData(info.sheet, info.row);
                            return;
                        }
                    } else {
                        data.updateType = 'update';
                        data.updateData = {pid: posData.id, lid: posData.lid, name: newText};
                    }
                } else if (!posData) {
                    toastr.warning('新增计量单元请先输入名称');
                } else {
                    data.updateType = 'update';
                    data.updateData = {pid: posData.id, lid: posData.lid};
                    if (col.type === 'Number') {
                        const exprInfo = getExprInfo(col.field);
                        const num = _.toNumber(newText);
                        if (_.isFinite(num)) {
                            data.updateData[col.field] = num;
                            if (exprInfo) {
                                data.updateData[exprInfo.expr] = '';
                            }
                        } else {
                            try {
                                data.updateData[col.field] = math.evaluate(transExpr(newText));
                                if (exprInfo) {
                                    data.updateData[exprInfo.expr] = newText;
                                }
                            } catch(err) {
                                toastr.error('输入的表达式非法');
                                SpreadJsObj.reLoadRowData(info.sheet, info.row);
                                return;
                            }
                        }
                    } else {
                        data.updateData[col.field] = newText;
                    }
                }
                // 提交数据到服务器
                postData(window.location.pathname + '/update', {pos: data}, function (result) {
                    if (result.pos) {
                        stagePos.updateDatas(result.pos.pos);
                        stagePos.loadCurStageData(result.pos.curStageData);
                    }
                    const refreshData = stageTree.loadPostStageData(result.ledger);
                    stageTreeSpreadObj.refreshTreeNodes(slSpread.getActiveSheet(), refreshData);
                    stagePosSpreadObj.loadCurPosData();
                    if (detail) {
                        detail.loadStagePosUpdateData(result);
                    } else {
                        stageIm.loadUpdatePosData(result);
                    }
                }, function () {
                    stagePosSpreadObj.loadCurPosData();
                });
            }
        },
        editStarting: function (e, info) {
            stagePosSpreadObj.stageTreeNode = SpreadJsObj.getSelectObject(slSpread.getActiveSheet());
            const sel = info.sheet.getSelections();
            if (!sel || !sel[0]) return;
            const col = info.sheet.zh_setting.cols[sel[0].col];
            const node = SpreadJsObj.getSelectObject(info.sheet);
            const exprInfo = getExprInfo(col.field);
            if (exprInfo) {
                if (node[exprInfo.expr] && node[exprInfo.expr] !== '') {
                    info.sheet.getCell(info.row, info.col).text(node[exprInfo.expr]);
                }
            }
        },
        clipboardPasting: function (e, info) {
            if (info.sheet.zh_setting) {
                const sortData = info.sheet.zh_data;
                const range = info.cellRange;
                const validField = ['contract_qty', 'qc_qty', 'postil', 'real_qty'];
                if (!checkTzMeasureType()) {
                    validField.push('name', 'sgfh_qty', 'sjcl_qty', 'qtcl_qty', 'position', 'drawing_code');
                }
                for (let iCol = range.col; iCol < range.col + range.colCount; iCol++) {
                    const col = info.sheet.zh_setting.cols[iCol];
                    if (validField.indexOf(col.field) === -1) {
                        if (checkTzMeasureType()) {
                            toastr.error('不可修改此数据');
                            info.cancel = true;
                            return;
                        } else {
                            for (let iRow = range.row; iRow < range.row + range.rowCount; iRow) {
                                const pos = sortData(iRow);
                                if (pos.add_stage !== stage.id || pos.add_times !== stage.times) {
                                    toastr.error('不可修改此数据');
                                    info.cancel = true;
                                    return;
                                }
                            }
                        }
                    }
                }
            }
        },
        clipboardPasted: function (e, info) {
            if (info.sheet.zh_setting) {
                if (info.sheet.getColumnCount() > info.sheet.zh_setting.cols.length) {
                    info.sheet.setColumnCount(info.sheet.zh_setting.cols.length);
                }
                const data = { updateType: '', updateData: [], };
                const sortData = info.sheet.zh_data;
                const node = SpreadJsObj.getSelectObject(slSpread.getActiveSheet());
                if (sortData && (info.cellRange.row >= sortData.length)) {
                    data.updateType = 'add';
                    if (info.cellRange.col !== 0) {
                        toastr.warning('新增计量单元请先输入名称');
                        stagePosSpreadObj.loadCurPosData();
                        return;
                    }
                    if ((node.pre_used === 1 || !checkZero(node.gather_qty) || !checkZero(node.gather_tp)) && sortData.length === 0) {
                        toastr.error('无计量单元的清单,计量后,不可新增计量单元');
                        stagePosSpreadObj.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 newData = {lid: node.id, porder: lastOrder + curRow - sortData.length};
                        for (let iCol = 0; iCol < info.cellRange.colCount; iCol++) {
                            const curCol = info.cellRange.col + iCol;
                            const colSetting = info.sheet.zh_setting.cols[curCol];
                            if (!colSetting) continue;
                            const newValue = trimInvalidChar(info.sheet.getText(curRow, curCol));
                            if (colSetting.type === 'Number') {
                                const num = _.toNumber(newValue);
                                if (num) {
                                    newData[colSetting.field] = num;
                                } else {
                                    try {
                                        newData[colSetting.field] = math.evaluate(transExpr(newValue));
                                        const exprInfo = getExprInfo(colSetting.field);
                                        if (exprInfo) {
                                            newData[exprInfo.expr] = newValue;
                                        }
                                    } catch(err) {
                                        toastr.error('输入的表达式非法');
                                        stagePosSpreadObj.loadCurPosData();
                                        return;
                                    }
                                }
                            } else {
                                newData[colSetting.field] = newValue;
                            }
                        }
                        data.updateData.push(newData);
                    }
                } else {
                    data.updateType = 'update';
                    for (let iRow = 0; iRow < info.cellRange.rowCount; iRow++) {
                        const curRow = info.cellRange.row + iRow;
                        const curPos = sortData[curRow];
                        if (curPos) {
                            const newData = {pid: curPos.id, lid: curPos.lid};
                            for (let iCol = 0; iCol < info.cellRange.colCount; iCol++) {
                                const curCol = info.cellRange.col + iCol;
                                const colSetting = info.sheet.zh_setting.cols[curCol];
                                const newValue = trimInvalidChar(info.sheet.getText(curRow, curCol));
                                if (colSetting.type === 'Number') {
                                    const num = _.toNumber(newValue);
                                    if (num) {
                                        newData[colSetting.field] = num;
                                    } else {
                                        try {
                                            newData[colSetting.field] = math.evaluate(transExpr(newValue));
                                            const exprInfo = getExprInfo(colSetting.field);
                                            if (exprInfo) {
                                                newData[exprInfo.expr] = newValue;
                                            }
                                        } catch(err) {
                                            toastr.error('输入的表达式非法');
                                            stagePosSpreadObj.loadCurPosData();
                                            return;
                                        }
                                    }
                                } else {
                                    newData[colSetting.field] = newValue;
                                }
                            }
                            data.updateData.push(newData);
                        }
                    }
                }
                postData(window.location.pathname + '/update', {pos: data}, function (result) {
                    if (result.pos) {
                        stagePos.updateDatas(result.pos.pos);
                        stagePos.loadCurStageData(result.pos.curStageData);
                    }
                    const nodes = stageTree.loadPostStageData(result.ledger);
                    stageTreeSpreadObj.refreshTreeNodes(slSpread.getActiveSheet(), nodes);
                    stagePosSpreadObj.loadCurPosData();
                    if (detail) {
                        detail.loadStagePosUpdateData(result);
                    } else {
                        stageIm.loadUpdatePosData(result);
                    }
                }, function () {
                    stagePosSpreadObj.loadCurPosData();
                });
            }
        },
        deletePress: function (sheet) {
            if (sheet.zh_setting && sheet.zh_data) {
                const sortData = sheet.zh_data;
                if (!sortData || sortData.length === 0) { return; }
                const sel = sheet.getSelections()[0];
                const validCols = [];
                for (let iCol = sel.col; iCol < sel.col + sel.colCount; iCol++) {
                    const colSetting = sheet.zh_setting.cols[iCol];
                    if (!colSetting.readOnly && colSetting.field !== 'qc_qty') {
                        validCols.push(iCol);
                    }
                }
                if (validCols.length === 0) { return; }
                const datas = [], posSelects = [];
                for (let iRow = sel.row; iRow < sel.row + sel.rowCount; iRow++) {
                    const node = sortData[iRow];
                    if (node) {
                        const data = {pid: node.id, lid: node.lid};
                        for (const iCol of validCols) {
                            const colSetting = sheet.zh_setting.cols[iCol];
                            if (colSetting.field === 'name') {
                                toastr.error('部位名称不能为空');
                                return;
                            }
                            data[colSetting.field] = null;
                            const exprInfo = getExprInfo(colSetting.field);
                            if (exprInfo) {
                                data[exprInfo.expr] = '';
                            }
                        }
                        datas.push(data);
                        posSelects.push(node);
                    }
                }
                if (datas.length > 0) {
                    postData(window.location.pathname + '/update', {pos: {updateType: 'update', updateData: datas} }, function (result) {
                        if (result.pos) {
                            stagePos.updateDatas(result.pos.pos);
                            stagePos.loadCurStageData(result.pos.curStageData);
                        }
                        const nodes = stageTree.loadPostStageData(result.ledger);
                        stageTreeSpreadObj.refreshTreeNodes(slSpread.getActiveSheet(), nodes);
                        if (detail) {
                            detail.loadStagePosUpdateData(result);
                        } else {
                            stageIm.loadUpdatePosData(result);
                        }
                        // todo 只加载改变项
                        stagePosSpreadObj.loadCurPosData();
                    });
                }
            }
        },
        deletePos: function (sheet) {
            const sels = sheet.getSelections();
            const sel = sels ? sels[0] : null;
            if (sheet.zh_data && sel) {
                const data = {updateType: 'delete', updateData: []};
                for (let iRow = 0; iRow < sel.rowCount; iRow++) {
                    const posData = sheet.zh_data[sel.row + iRow];
                    if (posData) {
                        data.updateData.push(posData.id);
                    }
                }
                if (data.updateData.length > 0) {
                    postData(window.location.pathname + '/update', {pos: data}, function (result) {
                        stagePos.removeDatas(result.pos.pos);
                        const refreshData = stageTree.loadPostStageData(result.ledger);
                        stageTreeSpreadObj.refreshTreeNodes(slSpread.getActiveSheet(), refreshData);
                        stagePosSpreadObj.loadCurPosData();
                        if (detail) {
                            detail.loadStagePosUpdateData(result);
                        } else {
                            stageIm.loadUpdatePosData(result);
                        }
                    });
                }
            }
        },
        selectionChanged: function (e, info) {
            stagePosSpreadObj.loadExprToInput(info.sheet);
        },
        addPegs: function (pegs) {
            if (!pegs || pegs.length <= 0) return;
            const node = SpreadJsObj.getSelectObject(slSpread.getActiveSheet());
            if (!node) return;
            const sheet = spSpread.getActiveSheet();
            const sortData = sheet.zh_data || [];
            let order = sortData.length > 0 ? sortData[sortData.length - 1].porder + 1 : 1;
            pegs.forEach(function (p) {p.porder = ++order; p.lid = node.id});
            postData(window.location.pathname + '/update', {pos: {updateType: 'add', updateData: pegs} }, function (result) {
                if (result.pos) {
                    stagePos.updateDatas(result.pos.pos);
                }
                stagePosSpreadObj.loadCurPosData();
            });
        }
    };
    // 加载上下窗口resizer
    $.divResizer({
        select: '#main-resize',
        callback: function () {
            slSpread.refresh();
            let bcontent = $(".bcontent-wrap") ? $(".bcontent-wrap").height() : 0;
            $(".sp-wrap").height(bcontent-30);
            spSpread.refresh();
            window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty();
        }
    });
    // 加载计量单元数据 - 暂时统一加载,如有需要,切换成动态加载并缓存
    postData(window.location.pathname + '/load', { filter: 'ledger;pos;detail;change' }, function (result) {
        // 加载树结构
        stageTree.loadDatas(result.ledgerData);
        // stageTree.loadCurStageData(curStageData);
        // stageTree.loadPreStageData(preStageData);
        treeCalc.calculateAll(stageTree);
        // 加载部位明细
        stagePos.loadDatas(result.posData);
        stagePos.calculateAll();
        SpreadJsObj.loadSheetData(slSpread.getActiveSheet(), 'tree', stageTree);
        SpreadJsObj.loadTopAndSelect(slSpread.getActiveSheet(), ckBillsSpread);
        stagePosSpreadObj.loadCurPosData();
        SpreadJsObj.resetTopAndSelect(spSpread.getActiveSheet());
        // 加载中间计量
        stageIm.init(stage, imType, tenderInfo.decimal);
        stageIm.loadData(result.ledgerData, result.posData, result.detailData, result.changeData);
        errorList.loadHisErrorData();
        checkList.loadHisCheckData();
    }, null, true);
    spSpread.bind(spreadNS.Events.EditEnded, stagePosSpreadObj.editEnded);
    spSpread.bind(spreadNS.Events.ClipboardPasting, stagePosSpreadObj.clipboardPasting);
    spSpread.bind(spreadNS.Events.ClipboardPasted, stagePosSpreadObj.clipboardPasted);
    spSpread.bind(spreadNS.Events.EditStarting, stagePosSpreadObj.editStarting);
    spSpread.bind(spreadNS.Events.SelectionChanged, stagePosSpreadObj.selectionChanged);
    SpreadJsObj.addDeleteBind(spSpread, stagePosSpreadObj.deletePress);
    if (!readOnly) {
        $('#pos-expr').bind('change onblur', function () {
            if (this.readOnly) return;
            const expr = $(this);
            const posSheet = spSpread.getActiveSheet();
            const row = expr.attr('data-row') ? _.toInteger(expr.attr('data-row')) : -1;
            const select = posSheet.zh_data ? posSheet.zh_data[row] : null;
            if (!select) return;
            const field = expr.attr('field'), orgValue = expr.attr('org'), newValue = expr.val();
            if (orgValue === newValue || (!orgValue && newValue == '')) { return; }
            const data = {pid: select.id, lid: select.lid};
            const exprInfo = getExprInfo(field);
            if (newValue !== '') {
                const num = _.toNumber(newValue);
                if (num) {
                    data[field] = num;
                    if (exprInfo) data[exprInfo.expr] = '';
                } else {
                    try {
                        data[field] = math.evaluate(transExpr(newValue));
                        if (exprInfo) data[exprInfo.expr] = newValue;
                    } catch (err) {
                        toastr.error('输入的表达式非法');
                        return;
                    }
                }
            } else {
                data[field] = null;
                if (exprInfo) data[exprInfo.expr] = '';
            }
            // 提交数据到服务器
            postData(window.location.pathname + '/update', {pos: {updateType: 'update', updateData: data}}, function (result) {
                if (result.pos) {
                    stagePos.updateDatas(result.pos.pos);
                    stagePos.loadCurStageData(result.pos.curStageData);
                    SpreadJsObj.reLoadRowData(posSheet, _.toNumber(row));
                }
                const refreshData = stageTree.loadPostStageData(result.ledger);
                stageTreeSpreadObj.refreshTreeNodes(slSpread.getActiveSheet(), refreshData);
            });
        });
    }
    const mergePeg = NewMergePeg({ callback: stagePosSpreadObj.addPegs});
    $.contextMenu({
        selector: '#stage-pos',
        build: function ($trigger, e) {
            const target = SpreadJsObj.safeRightClickSelection($trigger, e, spSpread);
            return target.hitTestType === spreadNS.SheetArea.viewport || target.hitTestType === spreadNS.SheetArea.rowHeader;
        },
        items: {
            'del': {
                name: '删除',
                icon: 'fa-remove',
                visible: function (key, opt) {
                    return !checkTzMeasureType();
                },
                disabled: function (key, opt) {
                    const sheet = spSpread.getActiveSheet();
                    if (sheet.zh_data && !readOnly) {
                        const selection = sheet.getSelections();
                        if (selection && selection[0]) {
                            let valid = sheet.zh_data.length < selection[0].row + selection[0].rowCount;
                            for (let iRow = 0; iRow < selection[0].rowCount; iRow++) {
                                const posData = sheet.zh_data[selection[0].row + iRow];
                                if (posData) {
                                    if (posData.add_stage_order < stage.order || ZhCalc.isNonZero(posData.gather_qty) || ZhCalc.isNonZero(posData.end_gather_qty)) {
                                        valid = true;
                                        break;
                                    }
                                } else {
                                    valid = true;
                                    break;
                                }
                            }
                            return valid;
                        } else {
                            return true;
                        }
                    } else {
                        return true;
                    }
                },
                callback: function (key, opt) {
                    stagePosSpreadObj.deletePos(spSpread.getActiveSheet());
                }
            },
            'merge-peg': {
                name: '合并起讫桩号',
                visible: function (key, opt) {
                    return !checkTzMeasureType();
                },
                disabled: function (key, opt) {
                    const node = SpreadJsObj.getSelectObject(slSpread.getActiveSheet());
                    return _.isNil(node) || _.isNil(node.b_code) || node.b_code === '';
                },
                callback: function (key, opt) {
                    mergePeg.show();
                }
            },
            'calcByRatio': {
                name: '按比例计量',
                visible: function (key, opt) {
                    const data = spSpread.getActiveSheet().zh_data;
                    return data && data.length > 0;
                },
                callback: function (key, opt) {
                    $('#cbr-ratio').val('');
                    $('#apply2sibling')[0].checked = false;
                    $('#cbr-check-all')[0].checked = false;
                    const html = [];
                    for (const [i, p] of spSpread.getActiveSheet().zh_data.entries()) {
                        html.push('');
                        html.push('', i+1, ' ');
                        html.push('', p.name, ' ');
                        html.push('', p.quantity, ' ');
                        html.push(' ');
                    }
                    $('#cbr-pos-list').html(html.join(''));
                    $('#calc-by-ratio').modal('show');
                }
            }
        }
    });
    $.subMenu({
        menu: '#sub-menu', miniMenu: '#sub-mini-menu', miniMenuList: '#mini-menu-list',
        toMenu: '#to-menu', toMiniMenu: '#to-mini-menu',
        key: 'menu.1.0.0',
        miniHint: '#sub-mini-hint', hintKey: 'menu.hint.1.0.1',
        callback: function (info) {
            if (info.mini) {
                $('.panel-title').addClass('fluid');
                $('#sub-menu').removeClass('panel-sidebar');
            } else {
                $('.panel-title').removeClass('fluid');
                $('#sub-menu').addClass('panel-sidebar');
            }
            autoFlashHeight();
            slSpread.refresh();
            spSpread.refresh();
            if (searchLedger) {
                searchLedger.spread.refresh();
            }
            if (detail) {
                detail.spread.refresh();
            }
            if (checkedChanges) checkedChanges.refresh();
            if (errorList && errorList.spread) {
                errorList.spread.refresh();
            }
            if (checkList) {
                checkList.spread.refresh();
            }
        }
    });
    $('#row-view').on('show.bs.modal', function () {
        const html = [], customDisplay = customColDisplay();
        for (const cd of customDisplay) {
            html.push('');
            html.push('', cd.title, ' ');
            html.push('', ' ');
            html.push(' ');
        }
        $('#row-view-list').html(html.join(''));
    });
    $('#row-view-ok').click(function () {
        const customDisplay = customColDisplay();
        const cvl = $('#row-view-list').children();
        for (const cv of cvl) {
            const title = $(cv).children()[0].innerHTML;
            const check = $('input', cv)[0].checked;
            const cd = customDisplay.find(function (c) {
                return c.title === title;
            });
            cd.visible = check;
        }
        customizeStageTreeSetting(ledgerSpreadSetting, customDisplay);
        SpreadJsObj.refreshColumnVisible(slSpread.getActiveSheet());
        Cookies.set(ckColSetting, JSON.stringify(customDisplay), 30*24*60*60*1000);
        $('#row-view').modal('hide');
    });
    const posSearch = (function () {
        let resultArr = [];
        const search = function () {
            resultArr = [];
            const keyword = $('#pos-search-keyword').val();
            const checkOver = $('#pos-over-search')[0].checked;
            const checkEmpty = $('#pos-empty-search')[0].checked;
            const sortData = spSpread.getActiveSheet().zh_data;
            if (checkOver || checkEmpty) {
                if (sortData) {
                    for (let i = 0, iLength = sortData.length; i < iLength; i++) {
                        const sd = sortData[i];
                        let match = false;
                        if (checkOver) {
                            if (sd.end_gather_qty) {
                                if (!sd.quantity || Math.abs(sd.end_gather_qty) > Math.abs(ZhCalc.add(sd.quantity, sd.end_qc_qty))) match = true;
                            }
                        }
                        if (checkEmpty) {
                            if (sd.quantity) {
                                if (!sd.end_gather_qty || ZhCalc.sub(ZhCalc.add(sd.quantity, sd.end_qc_qty), sd.end_gather_qty) > 0) match = true;
                            }
                        }
                        if (keyword && keyword !== '' && sd.name && sd.name.indexOf(keyword) === -1) match = false;
                        if (match) {
                            resultArr.push({index: i, data: sd});
                        }
                    }
                }
            } else if (keyword && keyword !== '') {
                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-result').html('结果:' + resultArr.length);
        };
        const searchAndLocate = function () {
            search();
            if (resultArr.length > 0) {
                const sheet = spSpread.getActiveSheet();
                const sel = sheet.getSelections()[0];
                const curRow = sel ? sel.row : 0;
                const pos = resultArr[0];
                if (pos.index !== curRow) {
                    sheet.setSelection(pos.index, sel ? sel.col : 0, 1, 1);
                    sheet.showRow(pos.index, spreadNS.VerticalPosition.center);
                    SpreadJsObj.reloadRowsBackColor(sheet, [pos.index, curRow]);
                }
            }
        };
        const locateNext = function () {
            if (resultArr.length > 0) {
                const sheet = spSpread.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);
                    SpreadJsObj.reloadRowsBackColor(sheet, [next.index, curRow]);
                }
            }
        };
        const locatePre = function () {
            if (resultArr.length > 0) {
                const sheet = spSpread.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);
                    SpreadJsObj.reloadRowsBackColor(sheet, [next.index, curRow]);
                }
            }
        };
        return {search, searchAndLocate, locateNext, locatePre};
    })();
    $('#pos-search-keyword').bind('keydown', function(e){
        if (e.keyCode == 13) posSearch.searchAndLocate();
    });
    $('#pos-empty-search').click(function () {
        if (this.checked) {
            $('[for=' + this.id +']').addClass('text-warning');
        } else {
            $('[for=' + this.id +']').removeClass('text-warning');
        }
        if (this.checked) {
            if ($('#pos-over-search')[0].checked) {
                $('#pos-search-keyword').attr('placeholder', '按名称查询');
            } else {
                $('#pos-search-keyword').attr('placeholder', '漏计中按名称查询');
            }
        } else {
            if ($('#pos-over-search')[0].checked) {
                $('#pos-search-keyword').attr('placeholder', '超计中按名称查询');
            } else {
                $('#pos-search-keyword').attr('placeholder', '按名称查询');
            }
        }
        posSearch.searchAndLocate();
    });
    $('#pos-over-search').click(function () {
        if (this.checked) {
            $('[for=' + this.id +']').addClass('text-danger');
        } else {
            $('[for=' + this.id +']').removeClass('text-danger');
        }
        if (this.checked) {
            if ($('#pos-empty-search')[0].checked) {
                $('#pos-search-keyword').attr('placeholder', '按名称查询');
            } else {
                $('#pos-search-keyword').attr('placeholder', '超计中按名称查询');
            }
        } else {
            if ($('#pos-empty-search')[0].checked) {
                $('#pos-search-keyword').attr('placeholder', '漏计中按名称查询');
            } else {
                $('#pos-search-keyword').attr('placeholder', '按名称查询');
            }
        }
        posSearch.searchAndLocate();
    });
    $('#pos-search-next').click(() => {posSearch.locateNext()});
    $('#pos-search-pre').click(() => {posSearch.locatePre()});
    $.divResizer({
        select: '#right-spr',
        callback: function () {
            slSpread.refresh();
            spSpread.refresh();
            if (searchLedger) {
                searchLedger.spread.refresh();
            }
            if (detail) {
                detail.spread.refresh();
            }
            if (checkedChanges) checkedChanges.refresh();
            if (errorList && errorList.spread) {
                errorList.spread.refresh();
            }
            if (checkList) {
                checkList.spread.refresh();
            }
            window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty();
        }
    });
    // 中间计量加载上下窗口resizer
    $.divResizer({
        select: '#zhongjian-spr',
        callback: function () {
            if (detail) {
                detail.spread.refresh();
            }
            $('.zhongjian-msg').height($('#zhongjian .sjs-bottom').height());
            window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty();
        }
    });
    // 附件加载上下窗口resizer
    $.divResizer({
        select: '#file-spr',
        callback: function () {
            window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty();
        }
    });
    // 变更令加载上下窗口resizer
    $.divResizer({
        select: '#change-spr',
        callback: function () {
            if (checkedChanges) checkedChanges.refresh();
            window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty();
        }
    });
    class Detail {
        constructor (obj) {
            const self = this;
            this.spreadSetting = {
                cols: [
                    {title: '编号', colSpan: '1', rowSpan: '1', field: 'code', hAlign: 0, width: 80, formatter: '@', readOnly: true},
                    {title: '中间计量表号', colSpan: '1', rowSpan: '1', field: 'im_code', hAlign: 0, width: 85, formatter: '@', readOnly: true},
                    {title: '交工证书/凭证号', colSpan: '1', rowSpan: '1', field: 'doc_code', hAlign: 0, width: 110, formatter: '@'},
                    {
                        title: stage.im_type === imType.tz.value ? '本期计量金额' : '本期计量数量',
                        colSpan: '1', rowSpan: '1', field: 'jl', hAlign: 2, width: 85, formatter: '@', readOnly: true
                    },
                ],
                headRows: 1,
                emptyRows: 0,
                headRowHeight: [32],
                headColWidth: [30],
                defaultRowHeight: 21,
                headerFont: '12px 微软雅黑',
                font: '12px 微软雅黑',
                readOnly: readOnly,
                selectedBackColor: '#fffacd',
            };
            this.spread = SpreadJsObj.createNewSpread(obj[0]);
            this.sheet = this.spread.getActiveSheet();
            this.spread.options.allowUserDragFill = true;
            this.spread.options.defaultDragFillType = spreadNS.Fill.AutoFillType.fillSeries;
            SpreadJsObj.initSheet(this.spread.getActiveSheet(), this.spreadSetting);
            this.detailObj = {
                selectionChanged: function (e, info) {
                    self.reLoadDetailData();
                    if (!info.oldSelections || !info.oldSelections[0] || info.oldSelections[0].row !== info.newSelections[0].row) {
                        self.loadLocateInfo();
                    }
                },
                editEnded: function(e, info) {
                    if (info.sheet.zh_setting) {
                        const col = info.sheet.zh_setting.cols[info.col];
                        if (col.field !== 'doc_code') {
                            SpreadJsObj.reLoadRowData(info.sheet, info.row);
                            return;
                        }
                        const data = SpreadJsObj.getSelectObject(info.sheet);
                        if (data) {
                            const updateData = {lid: data.lid, pid: data.pid};
                            if (data.uuid) {
                                updateData.uuid = data.uuid;
                            } else {
                                updateData.code = data.code;
                                updateData.name = data.name;
                                updateData.unit = data.unit;
                                updateData.unit_price = data.unit_price;
                                updateData.pid = data.pid;
                                updateData.pos_name = data.pos_name;
                            }
                            if (data.custom_define.indexOf('doc_code') === -1) {
                                updateData.custom_define = data.custom_define;
                                updateData.custom_define.push('doc_code');
                                updateData.custom_define = updateData.custom_define.join(',');
                            }
                            updateData.doc_code = info.editingText === null ? '' : info.editingText;
                            postData(window.location.pathname + '/detail/save', updateData, function (result) {
                                stageIm.loadUpdateDetailData(result);
                                SpreadJsObj.reLoadRowData(info.sheet, info.row);
                            }, function () {
                                SpreadJsObj.reLoadRowData(info.sheet, info.row);
                            });
                        } else {
                            SpreadJsObj.reLoadRowData(info.sheet, info.row);
                        }
                    }
                },
                clipboardPasted: function (e, info) {
                    if (info.sheet.zh_setting && info.sheet.zh_data) {
                        const col = info.sheet.zh_setting.cols[info.cellRange.col];
                        if (info.cellRange.colCount > 1) {
                            toastr.warning('请勿同时复制粘贴多列数据');
                            SpreadJsObj.reLoadSheetData(paySpread.getActiveSheet());
                            return;
                        }
                        if (col.field !== 'doc_code') {
                            SpreadJsObj.reLoadSheetData(paySpread.getActiveSheet());
                            return;
                        }
                        const datas = [];
                        for (let iRow = 0; iRow < info.cellRange.rowCount; iRow++) {
                            const curRow = info.cellRange.row + iRow;
                            const data = info.sheet.zh_data[curRow];
                            if (data) {
                                const updateData = {lid: data.lid, pid: data.pid};
                                if (data.uuid) {
                                    updateData.uuid = data.uuid;
                                } else {
                                    updateData.code = data.code;
                                    updateData.name = data.name;
                                    updateData.unit = data.unit;
                                    updateData.unit_price = data.unit_price;
                                    updateData.pid = data.pid;
                                    updateData.pos_name = data.pos_name;
                                }
                                if (data.custom_define.indexOf('doc_code') === -1) {
                                    updateData.custom_define = data.custom_define;
                                    updateData.custom_define.push('doc_code');
                                    updateData.custom_define = updateData.custom_define.join(',');
                                }
                                updateData.doc_code = info.sheet.getText(curRow, info.cellRange.col).replace('\n', '');
                                datas.push(updateData);
                            }
                        }
                        if (datas.length > 0) {
                            postData(window.location.pathname + '/detail/save', datas, function (result) {
                                stageIm.loadUpdateDetailData(result);
                                SpreadJsObj.reLoadRowData(info.sheet, info.cellRange.row, info.cellRange.rowCount);
                            }, function () {
                                SpreadJsObj.reLoadRowData(info.sheet, info.cellRange.row, info.cellRange.rowCount);
                            })
                        }
                    }
                },
                deletePress: function (sheet) {
                    if (sheet.zh_setting) {
                        const datas = [];
                        const sel = sheet.getSelections()[0];
                        for (let iCol = sel.col; iCol < sel.col + sel.colCount; iCol++) {
                            const col = sheet.zh_setting.cols[iCol];
                            for (let iRow = sel.row; iRow < sel.row + sel.rowCount; iRow++) {
                                const data = sheet.zh_data[iRow];
                                if (col.field === 'doc_code') {
                                    const updateData = {lid: data.lid};
                                    if (data.uuid) {
                                        updateData.uuid = data.uuid;
                                        updateData.doc_code = '';
                                        datas.push(updateData);
                                    }
                                }
                            }
                        }
                        if (datas.length > 0) {
                            postData(window.location.pathname + '/detail/save', datas, function (result) {
                                stageIm.loadUpdateDetailData(result);
                                SpreadJsObj.reLoadRowData(sheet, sel.row, sel.rowCount);
                            }, function () {
                                SpreadJsObj.reLoadRowData(sheet, sel.row, sel.rowCount);
                            });
                        }
                    }
                },
                dragFillBlock: function (e, info) {
                    info.cancel = true;
                    if (!info.sheet.zh_setting || !info.sheet.zh_data) return;
                    const sel = info.sheet.getSelections()[0];
                    const col = info.sheet.zh_setting.cols[info.fillRange.col];
                    if (info.fillRange.colCount > 1 || !sel || col.field !== 'doc_code') return;
                    const text = info.sheet.getText(sel.row + sel.rowCount - 1, sel.col);
                    if (text === '') return;
                    const regRst = /(\d+)$/g.exec(text), datas = [];
                    for (let iRow = 0; iRow < info.fillRange.rowCount; iRow++) {
                        const curRow = info.fillRange.row + iRow;
                        const data = info.sheet.zh_data[curRow];
                        if (data) {
                            const updateData = {lid: data.lid};
                            if (data.uuid) {
                                updateData.uuid = data.uuid;
                            } else {
                                updateData.code = data.code;
                                updateData.name = data.name;
                                updateData.unit = data.unit;
                                updateData.unit_price = data.unit_price;
                                updateData.pid = data.pid;
                                updateData.pos_name = data.pos_name;
                            }
                            if (regRst) {
                                updateData.doc_code = text.substr(0, regRst.index) + (parseInt(regRst[0]) + iRow + 1);
                            } else {
                                updateData.doc_code = text.replace('\n', '');
                            }
                            if (data.custom_define.indexOf('doc_code') === -1) {
                                updateData.custom_define = data.custom_define;
                                updateData.custom_define.push('doc_code');
                                updateData.custom_define = updateData.custom_define.join(',');
                            }
                            datas.push(updateData);
                        }
                    }
                    if (datas.length > 0) {
                        postData(window.location.pathname + '/detail/save', datas, function (result) {
                            stageIm.loadUpdateDetailData(result);
                            SpreadJsObj.reLoadRowData(info.sheet, info.fillRange.row, info.fillRange.rowCount);
                        }, function () {
                            SpreadJsObj.reLoadRowData(info.sheet, info.fillRange.row, info.fillRange.rowCount);
                        })
                    }
                },
            };
            this.spread.bind(spreadNS.Events.SelectionChanged, this.detailObj.selectionChanged);
            if (!readOnly) {
                this.spread.bind(spreadNS.Events.EditEnded, this.detailObj.editEnded);
                this.spread.bind(spreadNS.Events.ClipboardPasted, this.detailObj.clipboardPasted);
                this.spread.bind(spreadNS.Events.DragFillBlock, this.detailObj.dragFillBlock);
                SpreadJsObj.addDeleteBind(this.spread, this.detailObj.deletePress);
            }
            this._initImTypeSetRela();
            this._initModifyDetail();
            this._initLocateRela();
            // 草图相关
            this._initImageRela();
            this.reBuildImData();
        }
        _initImTypeSetRela() {
            const self = this;
            const gatherConfirmPopover = {
                reBind: function (obj, eventName, fun) {
                    obj.unbind(eventName);
                    obj.bind(eventName, fun);
                },
                check: function (pos, hint, okCallback) {
                    const confirmObj = $('#gather-confirm'), hintObj = $('#gather-confirm-hint');
                    const okObj = $('#gather-confirm-ok'), cancelObj = $('#gather-confirm-cancel');
                    this.reBind(cancelObj, 'click', function () {
                        confirmObj.hide();
                    });
                    this.reBind(okObj, 'click', function () {
                        okCallback();
                        confirmObj.hide();
                    });
                    hintObj.text(hint);
                    confirmObj.css("top", pos.y).css("left", pos.x).show();
                }
            };
            this.gsTree = stageIm.getGsTree();
            if (stage.im_type === imType.tz.value || stage.im_type === imType.bb.value) {
                const jlCol = self.spreadSetting.cols.find(function (x) {return x.field === 'jl'});
                jlCol.title = '本期计量金额';
                SpreadJsObj.reLoadSheetHeader(self.sheet);
                $('#type-title-contract').text('本期合同计量金额');
                $('#type-title-qc').text('本期变更计量金额');
            } else {
                const jlCol = self.spreadSetting.cols.find(function (x) {return x.field === 'jl'});
                jlCol.title = '本期计量数量';
                SpreadJsObj.reLoadSheetHeader(self.sheet);
                $('#type-title-contract').text('本期合同计量数量');
                $('#type-title-qc').text('本期变更计量数量');
            }
            if (stage.im_type === imType.bb.value || stage.im_type === imType.bw.value) {
                $('#show-jldy').parent().show();
                $('#jldy').parent().show();
                $('#show-xm-name').parent().hide();
                $('#xm-name').parent().hide();
            } else {
                $('#show-jldy').parent().hide();
                $('#jldy').parent().hide();
                $('#show-xm-name').parent().show();
                $('#xm-name').parent().show();
            }
            // 选择中间计量模式
            $('div[name="im-type"]').click(function () {
                function chooseType(obj) {
                    obj.style.cursor = 'default';
                    $(obj).children().addClass('text-primary');
                    $(obj).addClass('border-primary');
                    $('h5', obj).prepend('');
                    html.push('
');
                    html.push('
');
                    html.push('
');
                    html.push('
');
                    html.push('
');
                        html.push('
');
                        html.push('
');
                        html.push('
');
                        html.push('
');
                        html.push('
请选择退回流程
');
            return false
        }
        $('#sp-back').modal('hide');
        checkType && dataChecker.checkAndPost(this.action, data);
        $('#hide-all').hide();
        return false;
    });
    $('#exportExcel').click(function () {
        const data = [];
        const setting = {
            cols: [
                {title: '项目节编号', colSpan: '1', rowSpan: '2', field: 'code', hAlign: 0, width: 145, formatter: '@', cellType: 'tree'},
                {title: '清单编号', colSpan: '1', rowSpan: '2', field: 'b_code', hAlign: 0, width: 70, formatter: '@'},
                {title: '计量单元', colSpan: '1', rowSpan: '2', field: 'pos_code', hAlign: 0, width: 70, formatter: '@'},
                {title: '名称', colSpan: '1', rowSpan: '2', field: 'name', hAlign: 0, width: 185, formatter: '@'},
                {title: '单位', colSpan: '1', rowSpan: '2', field: 'unit', hAlign: 1, width: 60, formatter: '@', cellType: 'unit'},
                {title: '单价', colSpan: '1', rowSpan: '2', field: 'unit_price', hAlign: 2, width: 60, type: 'Number'},
                {title: '台账|数量', colSpan: '2|1', rowSpan: '1|1', field: 'quantity', hAlign: 2, width: 60, type: 'Number'},
                {title: '|金额', colSpan: '|1', rowSpan: '|1', field: 'total_price', hAlign: 2, width: 60, type: 'Number'},
                {title: '本期合同计量|数量', colSpan: '2|1', rowSpan: '1|1', field: 'contract_qty', hAlign: 2, width: 60, type: 'Number'},
                {title: '|金额', colSpan: '|1', rowSpan: '|1', field: 'contract_tp', hAlign: 2, width: 60, type: 'Number'},
                {title: '本期数量变更|数量', colSpan: '2|1', rowSpan: '1|1', field: 'qc_qty', hAlign: 2, width: 60, type: 'Number'},
                {title: '|金额', colSpan: '|1', rowSpan: '|1', field: 'qc_tp', hAlign: 2, width: 60, type: 'Number'},
                {title: '本期完成计量|数量', colSpan: '2|1', rowSpan: '1|1', field: 'gather_qty', hAlign: 2, width: 60, type: 'Number'},
                {title: '|金额', colSpan: '|1', rowSpan: '|1', field: 'gather_tp', hAlign: 2, width: 60, type: 'Number'},
                {title: '截止本期合同计量|数量', colSpan: '2|1', rowSpan: '1|1', field: 'end_contract_qty', hAlign: 2, width: 60, type: 'Number'},
                {title: '|金额', colSpan: '|1', rowSpan: '|1', field: 'end_contract_tp', hAlign: 2, width: 60, type: 'Number'},
                {title: '截止本期数量变更|数量', colSpan: '2|1', rowSpan: '1|1', field: 'end_qc_qty', hAlign: 2, width: 60, type: 'Number'},
                {title: '|金额', colSpan: '|1', rowSpan: '|1', field: 'end_qc_tp', hAlign: 2, width: 60, type: 'Number'},
                {title: '截止本期完成计量|数量', colSpan: '3|1', rowSpan: '1|1', field: 'end_gather_qty', hAlign: 2, width: 60, type: 'Number'},
                {title: '|金额', colSpan: '|1', rowSpan: '|1', field: 'end_gather_tp', hAlign: 2, width: 60, type: 'Number'},
                {title: '|完成率(%)', colSpan: '|1', rowSpan: '|1', field: 'end_gather_percent', hAlign: 2, width: 80, type: 'Number'},
                {title: '合同|项目节数量1',  colSpan: '2|1', rowSpan: '1|1', field: 'deal_dgn_qty1', hAlign: 2, width: 60, type: 'Number'},
                {title: '|项目节数量2',  colSpan: '|1', rowSpan: '|1', field: 'deal_dgn_qty2', hAlign: 2, width: 60, type: 'Number'},
                {title: '变更|项目节数量1',  colSpan: '2|1', rowSpan: '1|1', field: 'c_dgn_qty1', hAlign: 2, width: 60, type: 'Number'},
                {title: '|项目节数量2',  colSpan: '|1', rowSpan: '|1', field: 'c_dgn_qty2', hAlign: 2, width: 60, type: 'Number'},
                {title: '经济指标',  colSpan: '1', rowSpan: '2', field: 'final_dgn_price', hAlign: 2, width: 60, type: 'Number'},
                {title: '本期批注', colSpan: '1', rowSpan: '2', field: 'postil', hAlign: 0, width: 100, formatter: '@', cellType: 'autoTip'},
                {title: '图(册)号', colSpan: '1', rowSpan: '2', field: 'drawing_code', hAlign: 0, width: 80, formatter: '@'},
                {title: '备注', colSpan: '1', rowSpan: '2', field: 'memo', hAlign: 0, width: 100, formatter: '@', cellType: 'ellipsisAutoTip'},
            ],
            headRows: 2,
            headRowHeight: [25, 25],
            defaultRowHeight: 21,
            headerFont: 'bold 10px 微软雅黑',
            font: '10px 微软雅黑'
        };
        for (const node of stageTree.nodes) {
            data.push({
                code: node.code, b_code: node.b_code, name: node.name, unit: node.unit,
                unit_price: node.unit_price, quantity: node.quantity, total_price: node.total_price,
                contract_qty: node.contract_qty, contract_tp: node.contract_tp,
                qc_qty: node.qc_qty, qc_tp: node.qc_tp,
                gather_qty: node.gather_qty, gather_tp: node.gather_tp,
                end_contract_qty: node.end_contract_qty, end_contract_tp: node.end_contract_tp,
                end_qc_qty: node.end_qc_qty, end_qc_tp: node.end_qc_tp,
                end_gather_qty: node.end_gather_qty, end_gather_tp: node.end_gather_tp, end_gather_percent: node.end_gather_percent,
                deal_dgn_qty1: node.deal_dgn_qty1, deal_dgn_qty2: node.deal_dgn_qty2,
                c_dgn_qty1: node.c_dgn_qty1, c_dgn_qty2: node.c_dgn_qty2,
                final_dgn_price: node.final_dgn_price,
                postil: node.postil, drawing_code: node.drawing_code, memo: node.memo,
            });
            const posRange = stagePos.getLedgerPos(node.id);
            if (posRange && posRange.length > 0) {
                for (const [i, p] of posRange.entries()) {
                    data.push({
                        pos_code: (i + 1) + '', name: p.name,
                        quantity: p.quantity,
                        contract_qty: p.contract_qty, qc_qty: p.qc_qty, gather_qty: p.gather_qty,
                        end_contract_qty: p.end_contract_qty, end_qc_qty: p.end_qc_qty, end_gather_qty: p.end_gather_qty,
                        drawing_code: p.drawing_code, memo: p.memo
                    });
                }
            }
        }
        SpreadExcelObj.exportSimpleXlsxSheet(setting, data, $('.sidebar-title').attr('data-original-title') + "计量台账.xlsx");
    });
    $('#cbr-check-all').click(function () {
        if (this.checked) {
            $('input', '#cbr-pos-list').attr('checked', 'checked');
        } else {
            $('input', '#cbr-pos-list').removeAttr('checked');
        }
    });
    $('#cbr-ok').click(() => {
        const ratio = parseInt($('#cbr-ratio').val());
        if (!ratio) {
            toastr.warning('请输入计量比例');
            return;
        } else if (ratio < 1) {
            toastr.warning('计量比例不可小于1');
            return;
        } else if (ratio > 100) {
            toastr.warning('计量比例不可大于100');
            return;
        }
        const apply2sibling = $('#apply2sibling')[0].checked;
        const posName = _.map($('input:checked', '#cbr-pos-list'), function (x) {return $(x).attr('pos-name')});
        if (posName.length === 0) {
            toastr.warning('请勾选需要按计量比例的计量单元');
            return;
        }
        stageTreeSpreadObj.measureByBatch(posName, ratio, apply2sibling);
    })
});