'use strict';

/**
 * 台账修订页面js
 *
 * @author Mai
 * @date
 * @version
 */

const ckBillsSpread = window.location.pathname + '-billsSelect';

$(document).ready(() => {
    autoFlashHeight();
    // 初始化spread
    const billsSpread = SpreadJsObj.createNewSpread($('#bills-spread')[0]);
    const billsSheet = billsSpread.getActiveSheet();
    SpreadJsObj.initSheet(billsSheet, billsSpreadSetting);
    const posSpread = SpreadJsObj.createNewSpread($('#pos-spread')[0]);
    const posSheet = posSpread.getActiveSheet();
    SpreadJsObj.initSheet(posSheet, posSpreadSetting);
    // 初始化 清单树结构
    const treeSetting = {
        id: 'ledger_id',
        pid: 'ledger_pid',
        order: 'order',
        level: 'level',
        rootId: -1,
        keys: ['id', 'tender_id', 'ledger_id'],
        calcFields: ['sgfh_tp', 'sjcl_tp', 'qtcl_tp', 'total_price'],
    };
    if (!isTz) {
        treeSetting.calcFields.push('deal_tp');
    }
    treeSetting.calcFun = function (node) {
        node.dgn_price = ZhCalc.round(ZhCalc.div(node.total_price, node.dgn_qty1), 2);
    };
    const billsTree = createNewPathTree('ledger', treeSetting);
    billsTree.loadDatas(billsData);
    treeCalc.calculateAll(billsTree);
    // 加载至spread
    SpreadJsObj.loadSheetData(billsSheet, SpreadJsObj.DataType.Tree, billsTree);
    SpreadJsObj.loadTopAndSelect(billsSheet, ckBillsSpread);
    // 初始化 部位明细
    const pos = new PosData({ id: 'id', ledgerId: 'lid' });
    pos.loadDatas(posData);

    const billsTreeSpreadObj = {
        /**
         * 刷新顶部按钮是否可用
         * @param sheet
         * @param selections
         */
        refreshOperationValid: function (sheet) {
            const setObjEnable = function (obj, enable) {
                if (enable) {
                    obj.removeClass('disabled');
                } else {
                    obj.addClass('disabled');
                }
            };
            const tree = sheet.zh_tree;
            const node = SpreadJsObj.getSelectObject(sheet);
            const preNode = tree.getPreSiblingNode(node);
            const valid = !sheet.zh_setting.readOnly;

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

                        for (const node of newNodes) {
                            sheet.addRows(node.index, 1);
                            SpreadJsObj.reLoadRowData(sheet, tree.nodes.indexOf(node), 1);
                        }
                    }
                }
                // 处理更新
                if (data.update) {
                    const rows = [];
                    for (const u of data.update) {
                        rows.push(tree.nodes.indexOf(u));
                    }
                    SpreadJsObj.reLoadRowsData(sheet, rows);
                }
                // 处理展开
                if (data.expand) {
                    const expanded = [];
                    for (const e of data.expand) {
                        if (expanded.indexOf(e) === -1) {
                            const posterity = tree.getPosterity(e);
                            for (const p of posterity) {
                                sheet.setRowVisible(tree.nodes.indexOf(p), p.visible);
                                expanded.push(p);
                            }
                        }
                    }
                }
            });
        },
        selectionChanged: function (e, info) {
            if (info.newSelections[0].row !== info.oldSelections[0].row) {
                billsTreeSpreadObj.refreshOperationValid(info.sheet);
                posSpreadObj.loadCurPosData();
                SpreadJsObj.saveTopAndSelect(posSheet, ckBillsSpread);
                SpreadJsObj.resetTopAndSelect(billsSheet);
                //posSearch.search($('#pos-keyword').val());
            }
        },
        /**
         * 新增节点
         * @param spread
         */
        baseOpr: function (sheet, type) {
            const self = this;
            const tree = sheet.zh_tree;
            const node = SpreadJsObj.getSelectObject(sheet);
            if (!tree || !node) return;

            postData(window.location.pathname + '/base-opr', {id: node.ledger_id, postType: type}, function (result) {
                const refreshData = tree.loadPostData(result);
                self.refreshTree(sheet, refreshData);
                if (['up-move', 'down-move', 'up-level', 'down-level'].indexOf(type) > -1) {
                    const sel = sheet.getSelections()[0];
                    if (sel) {
                        sheet.setSelection(tree.nodes.indexOf(node), sel.col, sel.rowCount, sel.colCount);
                    }
                }
                self.refreshOperationValid(sheet);
            });
        },
        /**
         * 编辑单元格响应事件
         * @param {Object} e
         * @param {Object} info
         */
        editEnded: function (e, info) {
            if (info.sheet.zh_setting) {
                const col = info.sheet.zh_setting.cols[info.col];
                const sortData = info.sheet.zh_dataType === 'tree' ? info.sheet.zh_tree.nodes : info.sheet.zh_data;
                const node = sortData[info.row];
                const data = {
                    id: node.id,
                    tender_id: node.tender_id,
                    ledger_id: node.ledger_id
                };
                // 未改变值则不提交
                const orgValue = node[col.field];
                if (orgValue == info.editingText || ((!orgValue || orgValue === '') && (info.editingText === ''))) {
                    return;
                }
                // 台账模式，检查部位明细相关
                if (checkTzMeasureType()) {
                    if (col.field === 'sgfh_qty' || col.field === 'sgfh_tp' ||
                        col.field === 'sjcl_qty' || col.field === 'sjcl_tp' ||
                        col.field === 'qtcl_qty' || col.field === 'qtcl_tp') {
                        if (!node.children || node.children.length ===0) {
                            const lPos = pos.getLedgerPos(node.id);
                            if (lPos && lPos.length > 0) {
                                toast('清单含有部位明细，不可修改施工图复核数量', 'error');
                                SpreadJsObj.reLoadRowData(info.sheet, info.row);
                                return;
                            }
                        }
                    }
                    if (col.field === 'b_code' && (info.editingText === '' || !info.editingText)) {
                        const lPos = pos.getLedgerPos(node.id);
                        if (lPos && lPos.length > 0) {
                            toast('清单含有部位明细，请先删除部位明细，再删除清单编号', 'error');
                            SpreadJsObj.reLoadRowData(info.sheet, info.row);
                            return;
                        }
                    }
                }
                // 获取更新数据
                if (info.editingText) {
                    data[col.field] = col.type === 'Number' ? parseFloat(info.editingText) : info.editingText.replace('\n', '');
                } else {
                    data[col.field] = null;
                }
                // 更新至服务器
                info.sheet.zh_tree.update('/tender/' + getTenderId() + '/ledger/update', data, function (result) {
                    treeOperationObj.refreshTree(info.sheet, result);
                });
            }
        },
        topRowChanged: function (e, info) {
            SpreadJsObj.saveTopAndSelect(info.sheet, ckBillsSpread);
        },
    };
    billsTreeSpreadObj.refreshOperationValid(billsSheet);
    billsSpread.bind(spreadNS.Events.SelectionChanged, billsTreeSpreadObj.selectionChanged);
    billsSpread.bind(spreadNS.Events.topRowChanged, billsTreeSpreadObj.topRowChanged);
    if (!readOnly) {
        // 增删上下移升降级
        $('a[name="base-opr"]').click(function () {
            billsTreeSpreadObj.baseOpr(billsSheet, this.getAttribute('type'));
        });
        let batchInsertObj;
        // 右键菜单
        $.contextMenu({
            selector: '#bills-spread',
            build: function ($trigger, e) {
                const target = SpreadJsObj.safeRightClickSelection($trigger, e, billsSpread);
                return target.hitTestType === spreadNS.SheetArea.viewport || target.hitTestType === spreadNS.SheetArea.rowHeader;
            },
            items: {
                'batchInsertBillsPos': {
                    name: '批量插入清单-部位',
                    icon: 'fa-sign-in',
                    disabled: function (key, opt) {
                        const select = SpreadJsObj.getSelectObject(billsSheet);
                        if (select) {
                            if (select.code && select.code !== '') {
                                return !billsTree.isLeafXmj(select);
                            } else {
                                const parent = billsTree.getParent(select);
                                return !(parent && billsTree.isLeafXmj(parent));
                            }
                        } else {
                            return false;
                        }
                    },
                    callback: function (key, opt) {
                        if (!batchInsertObj) {
                            batchInsertObj = new BatchInsertBillsPosObj($('#batch'));
                        } else {
                            batchInsertObj.initView();
                        }
                        $('#batch').modal('show');
                    }
                },
            }
        });
    }

    const posSpreadObj = {
        /**
         * 加载部位明细 根据当前台账选择节点
         */
        loadCurPosData: function () {
            const node = SpreadJsObj.getSelectObject(billsSheet);
            if (node) {
                const posData = pos.getLedgerPos(node.id) || [];
                SpreadJsObj.loadSheetData(posSheet, 'data', posData);
            } else {
                SpreadJsObj.loadSheetData(posSheet, 'data', []);
            }
            SpreadJsObj.resetFieldReadOnly(posSheet);
        },
        editStarting: function (e, info) {
            posSpreadObj.ledgerTreeNode = SpreadJsObj.getSelectObject(billsSheet);
        },
    };
    posSpreadObj.loadCurPosData();
    SpreadJsObj.resetTopAndSelect(posSheet);

    $.divResizer({
        select: '#revise-resize',
        callback: function () {
            billsSpread.refresh();
            let bcontent = $(".bcontent-wrap") ? $(".bcontent-wrap").height() : 0;
            $(".sp-wrap").height(bcontent-40);
            posSpread.refresh();
        }
    });

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

                const stdTree = stdSheet.zh_tree;
                const stdNode = stdTree.nodes[info.row];
                const mainTree = mainSheet.zh_tree;
                const sel = mainSheet.getSelections()[0];
                const mainNode = mainTree.nodes[sel.row];
                if (!stdNode) { return; }

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

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

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

                postData('/tender/' + getTenderId() + '/ledger/add-by-deal', {
                    id: mainNode.ledger_id,
                    type: mainNode.code ? 'child' : 'next',
                    dealBills: {
                        b_code: dealBills.code, name: dealBills.name, unit: dealBills.unit,
                        unit_price: dealBills.unit_price,
                    },
                }, function (result) {
                    const refreshData = mainTree.loadPostData(result);
                    treeOperationObj.refreshTree(mainSheet, refreshData);
                    treeOperationObj.refreshOperationValid(mainSheet);
                });
            });
            SpreadJsObj.forbiddenSpreadContextMenu(selector, this.spread);
        }
        loadData () {
            if (this.loaded) return;
            const self = this;
            postData(this.url+'/get-data', {}, function (data) {
                self.data = data;
                //self.calculateData();
                SpreadJsObj.loadSheetData(self.spread.getActiveSheet(), 'data', data);
                self.loaded = true;
            });
        }
        calculateData () {
            if (this.data) {
                for (const d of this.data) {
                    d.total_price = _.multiply(d.quantity, d.unit_price);
                }
            }
        }
    }
    class BatchInsertBillsPosObj {
        constructor (obj) {
            const self = this;
            this.obj = obj;
            this.billsCount = 6;
            this.posCount = 1000;
            // 初始化 清单编号窗口 参数
            this.qdSpreadSetting = {
                cols: [
                    {title: '编号', field: 'code', hAlign: 0, width: 80, formatter: '@'},
                    {title: '名称', field: 'name', hAlign: 0, width: 120, formatter: '@'},
                    {title: '单位', field: 'unit', hAlign: 1, width: 50, formatter: '@'},
                    {title: '单价', field: 'unit_price', hAlign: 2, width: 50},
                    {title: '图册号', field: 'name', hAlign: 0, width: 60, formatter: '@'},
                ],
                emptyRows: this.billsCount,
                headRows: 1,
                headRowHeight: [40],
            };
            this.qdSpread = SpreadJsObj.createNewSpread($('.batch-l-t', this.obj)[0]);
            // 初始化 部位数量复核表 参数
            this.posSpreadSetting = {
                cols: [
                    {title: '部位', field: 'bw', hAlign: 0, width: 80, formatter: '@'},
                    {title: '图册号', field: 'drawingCode', hAlign: 0, formatter: '@', width: 60},
                ],
                emptyRows: this.posCount,
                headRows: 1,
                headRowHeight: [40],
            };
            for (let iNum = 1; iNum <= this.billsCount; iNum++) {
                this.posSpreadSetting.cols.push(
                    {title: '清单' + iNum, field: 'bills' + iNum, hAlign: 2, width: 50}
                )
            }
            this.posSpread = SpreadJsObj.createNewSpread($('.batch-l-b', this.obj)[0]);
            // 初始化 签约清单 参数
            this.dealSpreadSetting = {
                cols: [
                    {title: '清单编号', field: 'code', width: 80, formatter: '@', readOnly: true},
                    {title: '名称', field: 'name', width: 120, formatter: '@', readOnly: true},
                    {title: '单位', field: 'unit', width: 50, formatter: '@', readOnly: true},
                    {title: '单价', field: 'unit_price', width: 50, readOnly: true},
                ],
                emptyRows: 0,
                headRows: 1,
                headRowHeight: [40],
            };
            this.dealSpread = SpreadJsObj.createNewSpread($('.batch-r', this.obj)[0]);
            // 初始化 清单编号、部位数量复核表 表格
            this.initView();
            SpreadJsObj.initSheet(this.dealSpread.getActiveSheet(), this.dealSpreadSetting);
            SpreadJsObj.refreshColumnAlign(this.dealSpread.getActiveSheet());
            // 拉取签约清单数据
            dealBills.loadData();
            SpreadJsObj.loadSheetData(this.dealSpread.getActiveSheet(), 'data', dealBills.data);
            // 双击签约清单，自动添加到清单编号窗口
            this.dealSpread.bind(GC.Spread.Sheets.Events.CellDoubleClick, function (e, info) {
                const deal = info.sheet.zh_data[info.row];
                const qdSheet = self.qdSpread.getActiveSheet(), posSheet = self.posSpread.getActiveSheet();
                const sel = qdSheet.getSelections()[0];
                qdSheet.getCell(sel.row, 0).value(deal.code);
                qdSheet.getCell(sel.row, 1).value(deal.name);
                qdSheet.getCell(sel.row, 2).value(deal.unit);
                qdSheet.getCell(sel.row, 3).value(deal.unit_price);
                if (sel.row + 1 === qdSheet.getRowCount()) {
                    const count = sel.row + 2;
                    qdSheet.setRowCount(count);
                    qdSheet.getCell(sel.row + 1, 0, GC.Spread.Sheets.SheetArea.rowHeader).text('清单' + count);

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

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

            $('#batch-ok').click(function () {
                const selection = billsSheet.getSelections();
                const row = selection[0].row;
                const select = billsTree.nodes[row];
                if (select) {
                    const insertData = {};
                    insertData.batchType = (select.code && select.code !== '') ? 'child' : 'next';
                    insertData.id = select[billsTree.setting.id];
                    insertData.batchData = self.getBatchData();
                    postData(window.location.pathname + '/batch-insert', insertData, function (data) {
                        pos.updateDatas(data.pos);
                        const result = billsTree.loadPostData(data.ledger);
                        billsTreeSpreadObj.refreshTree(billsSheet, result);
                        billsTreeSpreadObj.refreshOperationValid(billsSheet, selection);
                        self.obj.modal('hide');
                    });
                }
            });
        }
        // 初始化左侧表格
        initView () {
            // 初始化 清单编号
            const qdSheet = this.qdSpread.getActiveSheet();
            SpreadJsObj.initSheet(qdSheet, this.qdSpreadSetting);
            SpreadJsObj.refreshColumnAlign(qdSheet);
            // 清理原有数据
            SpreadJsObj.beginMassOperation(qdSheet);
            qdSheet.clear(0, 0, qdSheet.getRowCount(), qdSheet.getColumnCount(), GC.Spread.Sheets.SheetArea.viewport, GC.Spread.Sheets.StorageType.data);
            for (let iRow = 1; iRow <= this.billsCount; iRow++) {
                qdSheet.getCell(iRow - 1, 0, GC.Spread.Sheets.SheetArea.rowHeader).text('清单' + iRow);
            }
            qdSheet.setSelection(0, 0, 1 ,1);
            SpreadJsObj.endMassOperation(qdSheet);
            // 初始化 部位数量复核表
            const posSheet = this.posSpread.getActiveSheet();
            SpreadJsObj.initSheet(posSheet, this.posSpreadSetting);
            SpreadJsObj.refreshColumnAlign(posSheet);
            // 清理原有数据
            SpreadJsObj.beginMassOperation(posSheet);
            posSheet.setColumnWidth(0, 45, GC.Spread.Sheets.SheetArea.rowHeader);
            posSheet.clear(0, 0, posSheet.getRowCount(), posSheet.getColumnCount(), GC.Spread.Sheets.SheetArea.viewport, GC.Spread.Sheets.StorageType.data);
            posSheet.setSelection(0, 0, 1 ,1);
            SpreadJsObj.endMassOperation(posSheet);
            // 检查签约清单数据，以工具栏数据为准
            if (dealBills) {
                SpreadJsObj.loadSheetData(this.dealSpread.getActiveSheet(), 'data', dealBills.data);
            }
            this.dealSpread.getActiveSheet().setSelection(0, 0, 1, 1);
        }
        // 获取界面数据
        getBatchData () {
            const result = [];
            const qdSheet = this.qdSpread.getActiveSheet(), posSheet = this.posSpread.getActiveSheet();
            for (let iRow = 0; iRow < qdSheet.getRowCount(); iRow++) {
                if (qdSheet.getText(iRow, 0) === '') { continue; }
                const qd = {
                    b_code: qdSheet.getText(iRow, 0),
                    name: qdSheet.getText(iRow, 1),
                    unit: qdSheet.getText(iRow, 2),
                    price: _.toNumber(qdSheet.getText(iRow, 3)),
                    pos: [],
                };
                result.push(qd);
                for (let iPosRow = 0; iPosRow < posSheet.getRowCount(); iPosRow++) {
                    const value = _.toNumber(posSheet.getText(iPosRow, iRow + 2));
                    if (value !== 0 && !isNaN(value)) {
                        qd.pos.push({
                            name: posSheet.getText(iPosRow, 0),
                            drawing_code: posSheet.getText(iPosRow, 1),
                            quantity: value,
                        });
                    }
                }
            }
            return result;
        }
    }
    let stdChapter, stdBills;
    const dealBills = new DealBills('#deal-bills-spread', {
        cols: [
            {title: '清单编号', field: 'code', hAlign: 0, width: 120, formatter: '@', readOnly: true},
            {title: '名称', field: 'name', hAlign: 0, width: 230, formatter: '@', readOnly: true},
            {title: '单位', field: 'unit', hAlign: 1, width: 50, formatter: '@', readOnly: true},
            {title: '单价', field: 'unit_price', hAlign: 2, width: 50, readOnly: true},
            {title: '数量', field: 'quantity', hAlign: 2, width: 50, readOnly: true},
            {title: '金额', field: 'total_price', hAlign: 2, width: 50, readOnly: true},
        ],
        emptyRows: 0,
        headRows: 1,
        headRowHeight: [40],
        defaultRowHeight: 21,
    });
    $.divResizer({
        select: '#revise-right-spr',
        callback: function () {
            billsSpread.refresh();
            if (posSpread) {
                posSpread.refresh();
            }
            if (stdChapter) {
                stdChapter.spread.refresh();
            }
            if (stdBills) {
                stdBills.spread.refresh();
            }
        }
    });
    // 展开收起标准清单
    $('a', '#side-menu').bind('click', function (e) {
        e.preventDefault();
        const tab = $(this), tabPanel = $(tab.attr('content'));
        const showSideTools = function (show) {
            const left = $('#left-view'), right = $('#right-view'), parent = left.parent();
            if (show) {
                right.show();
                autoFlashHeight();
                /**
                 * right.show()后, parent被撑开成2倍left.height, 导致parent.width减少了10px
                 * 第一次left.width调整后，parent的缩回left.height, 此时parent.width又增加了10px
                 * 故需要通过最终的parent.width再计算一次left.width
                 *
                 * Q: 为什么不通过先计算left.width的宽度，以避免计算两次left.width?
                 * A: 右侧工具栏不一定显示，当右侧工具栏显示过一次后，就必须使用parent和right来计算left.width
                 *
                 */
                    //left.css('width', parent.width() - right.outerWidth());
                    //left.css('width', parent.width() - right.outerWidth());
                const percent = 100 - right.outerWidth() /parent.width() * 100;
                left.css('width', percent + '%');
            } else {
                left.width(parent.width());
                right.hide();
            }
        };
        // 展开工具栏、切换标签
        if (!tab.hasClass('active')) {
            const close = $('.active', '#side-menu').length === 0;
            $('a', '#side-menu').removeClass('active');
            tab.addClass('active');
            $('.tab-content .tab-pane').removeClass('active');
            tabPanel.addClass('active');
            showSideTools(tab.hasClass('active'));
            if (tab.attr('content') === '#std-chapter') {
                if (!stdChapter) {
                    stdChapter = new stdLib($('#std-chapter-spread')[0], 'chapter', {
                        id: 'chapter_id',
                        pid: 'pid',
                        order: 'order',
                        level: 'level',
                        rootId: -1,
                        keys: ['id', 'list_id', 'chapter_id'],
                    }, {
                        cols: [
                            {title: '项目节编号', field: 'code', hAlign: 0, width: 120, formatter: '@', readOnly: true, cellType: 'tree'},
                            {title: '名称', field: 'name', hAlign: 0, width: 230, formatter: '@', readOnly: true},
                            {title: '单位', field: 'unit', hAlign: 1, width: 50, formatter: '@', readOnly: true}
                        ],
                        treeCol: 0,
                        emptyRows: 0,
                        headRows: 1,
                        headRowHeight: [40],
                        defaultRowHeight: 21,
                    });
                    stdChapter.loadLib(1);
                }
                stdChapter.spread.refresh();
            } else if (tab.attr('content') === '#std-bills') {
                if (!stdBills) {
                    stdBills = new stdLib($('#std-bills-spread')[0], 'bills', {
                        id: 'bill_id',
                        pid: 'pid',
                        order: 'order',
                        level: 'level',
                        rootId: -1,
                        keys: ['id', 'list_id', 'bill_id']
                    }, {
                        cols: [
                            {title: '清单编号', field: 'code', hAlign: 0, width: 120, formatter: '@', readOnly: true, cellType: 'tree'},
                            {title: '名称', field: 'name', hAlign: 0, width: 230, formatter: '@', readOnly: true},
                            {title: '单位', field: 'unit', hAlign: 1, width: 50, formatter: '@', readOnly: true}
                        ],
                        treeCol: 0,
                        emptyRows: 0,
                        headRows: 1,
                        headRowHeight: [40],
                        defaultRowHeight: 21,
                    });
                    stdBills.loadLib(1);
                }
                stdBills.spread.refresh();
            } else if (tab.attr('content') === '#deal-bills') {
                dealBills.loadData();
                dealBills.spread.refresh();
            }
        }
        billsSpread.refresh();
        if (posSpread) {
            posSpread.refresh();
        }
    });

    // 修订详情 保存
    $('#save').click(function () {
        const content = $('textarea').val();
        postData('save', { content: content });
    });

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