'use strict';
/**
 *
 *
 * @author Mai
 * @date 2018/5/30
 * @version
 */
const ckBillsSpread = window.location.pathname + '-billsSelect';
function getTenderId() {
    return window.location.pathname.split('/')[2];
}
function checkTzMeasureType () {
    return tender.measure_type === measureType.tz.value;
}
$(document).ready(() => {
    autoFlashHeight();
    const ledgerSpread = SpreadJsObj.createNewSpread($('#ledger-spread')[0]);
    const treeSetting = {
        id: 'ledger_id',
        pid: 'ledger_pid',
        order: 'order',
        level: 'level',
        rootId: -1,
        keys: ['id', 'tender_id', 'ledger_id'],
        preUrl: '/ledger',
    };
    if (checkTzMeasureType()) {
        treeSetting.calcFields = ['sgfh_tp', 'sjcl_tp', 'qtcl_tp', 'total_price'];
    } else {
        treeSetting.calcFields = ['deal_tp', 'sgfh_tp', 'sjcl_tp', 'qtcl_tp', 'total_price'];
    }
    const ledgerTree = createNewPathTree('fx', treeSetting);
    sjsSettingObj.setFxTreeStyle(ledgerSpreadSetting, sjsSettingObj.FxTreeStyle.jz);
    SpreadJsObj.initSheet(ledgerSpread.getActiveSheet(), ledgerSpreadSetting);
    // 初始化 部位明细
    const pos = new PosData({
        id: 'id', ledgerId: 'lid',
    });
    const posSpread = SpreadJsObj.createNewSpread($('#pos-spread')[0]);
    const posSearch = $.posSearch({selector: '#pos-search', searchSpread: posSpread});
    $.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();
            ledgerSpread.refresh();
            posSpread.refresh();
        }
    });
    const loadCurPosData = function () {
        const node = SpreadJsObj.getSelectObject(ledgerSpread.getActiveSheet());
        if (node) {
            const posData = pos.ledgerPos[itemsPre + node.id] || [];
            SpreadJsObj.loadSheetData(posSpread.getActiveSheet(), 'data', posData);
        } else {
            SpreadJsObj.loadSheetData(posSpread.getActiveSheet(), 'data', []);
        }
    };
    // 台账模式加载部位明细数据
    if (checkTzMeasureType()) {
        $.divResizer({
            select: '#main-resize',
            callback: function () {
                ledgerSpread.refresh();
                let bcontent = $(".bcontent-wrap") ? $(".bcontent-wrap").height() : 0;
                $(".sp-wrap").height(bcontent-30);
                posSpread.refresh();
            }
        });
        SpreadJsObj.initSheet(posSpread.getActiveSheet(), posSpreadSetting);
    }
    postData('/tender/' + getTenderId() + '/ledger/load', null, function (data) {
        ledgerTree.loadDatas(data.bills);
        treeCalc.calculateAll(ledgerTree);
        SpreadJsObj.loadSheetData(ledgerSpread.getActiveSheet(), 'tree', ledgerTree);
        SpreadJsObj.loadTopAndSelect(ledgerSpread.getActiveSheet(), ckBillsSpread);
        pos.loadDatas(data.pos);
        loadCurPosData();
        SpreadJsObj.resetTopAndSelect(posSpread.getActiveSheet());
    }, null, true);
    ledgerSpread.bind(spreadNS.Events.SelectionChanged, function (e, info) {
        loadCurPosData();
        SpreadJsObj.saveTopAndSelect(info.sheet, ckBillsSpread);
        posSearch.search($('#pos-keyword').val());
    });
    ledgerSpread.bind(spreadNS.Events.TopRowChanged, function (e, info) {
        SpreadJsObj.saveTopAndSelect(info.sheet, ckBillsSpread);
    });
    let dealBills, searchLedger;
    $.divResizer({
        select: '#right-spr',
        callback: function () {
            ledgerSpread.refresh();
            if (posSpread) {
                posSpread.refresh();
            }
            if (dealBills) {
                dealBills.spread.refresh();
            }
        }
    });
    // 展开收起 签约清单|清单意见
    $('a', '.side-menu').bind('click', function () {
        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')) {
            $('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') === '#deal-bills' && !dealBills) {
                dealBills = new DealBills($('#deal-bills-spread')[0], {
                    cols: [
                        {title: '清单编号', field: 'code', width: 85, formatter: '@', readOnly: true},
                        {title: '名称', field: 'name', width: 150, formatter: '@', readOnly: true},
                        {title: '单位', field: 'unit', width: 50, formatter: '@', readOnly: true},
                        {title: '单价', field: 'unit_price', width: 50, readOnly: true},
                        {title: '数量', field: 'quantity', width: 50, readOnly: true},
                        {title: '金額', field: 'total_price', width: 50, readOnly: true},
                    ],
                    emptyRows: 0,
                    headRows: 1,
                    headRowHeight: [32],
                    defaultRowHeight: 21,
                    headerFont: '12px 微软雅黑',
                    font: '12px 微软雅黑',
                    headColWidth: [0],
                    selectedBackColor: '#fffacd',
                });
                dealBills.loadData();
            } else if (tab.attr('content') === '#search' && !searchLedger) {
                if (!searchLedger) {
                    searchLedger = $.billsSearch({
                        selector: '#search',
                        searchSpread: ledgerSpread,
                        resultSpreadSetting: {
                            cols: [
                                {title: '项目节编号', field: 'code', hAlign: 0, width: 90, formatter: '@', readOnly: true},
                                {title: '清单编号', field: 'b_code', hAlign: 0, width: 80, formatter: '@', readOnly: true},
                                {title: '名称', field: 'name', width: 150, hAlign: 0, formatter: '@', readOnly: true},
                                {title: '单位', field: 'unit', width: 50, hAlign: 1, formatter: '@', readOnly: true},
                                {title: '单价', field: 'unit_price', hAlign: 2, width: 50, readOnly: true},
                                {title: '数量', field: 'quantity', hAlign: 2, width: 50, readOnly: true},
                            ],
                            emptyRows: 0,
                            headRows: 1,
                            headRowHeight: [32],
                            defaultRowHeight: 21,
                            headerFont: '12px 微软雅黑',
                            font: '12px 微软雅黑',
                            selectedBackColor: '#fffacd',
                        },
                        afterLocated: function () {
                            loadCurPosData();
                        }
                    });
                }
                searchLedger.spread.refresh();
            }
        } else {
            tab.removeClass('active');
            tabPanel.removeClass('active');
            showSideTools(tab.hasClass('active'));
        }
        ledgerSpread.refresh();
        if (posSpread) {
            posSpread.refresh();
        }
    });
    class DealBills {
        constructor (obj, spreadSetting) {
            this.obj = obj;
            this.url = '/tender/' + getTenderId() + '/deal';
            this.spreadSetting = spreadSetting;
            this.spread = SpreadJsObj.createNewSpread(this.obj);
            SpreadJsObj.initSheet(this.spread.getActiveSheet(), this.spreadSetting);
        }
        loadData () {
            const self = this;
            postData(this.url+'/get-data', {}, function (data) {
                SpreadJsObj.loadSheetData(self.spread.getActiveSheet(), 'data', data);
            });
        }
    }
    // 显示层次
    (function (select, sheet) {
        $(select).click(function () {
            if (!sheet.zh_tree) return;
            const tag = $(this).attr('tag');
            const tree = sheet.zh_tree;
            switch (tag) {
                case "1":
                case "2":
                case "3":
                case "4":
                case "5":
                    tree.expandByLevel(parseInt(tag));
                    SpreadJsObj.refreshTreeRowVisible(sheet);
                    break;
                case "last":
                    tree.expandByCustom(() => { return true; });
                    SpreadJsObj.refreshTreeRowVisible(sheet);
                    break;
                case "leafXmj":
                    tree.expandToLeafXmj();
                    SpreadJsObj.refreshTreeRowVisible(sheet);
                    break;
            }
        });
    })('a[name=showLevel]', ledgerSpread.getActiveSheet());
});
// texterea换行
function auditCheck(i) {
    const opinion = $('textarea[name="opinion"]').eq(i).val().replace(/\r\n/g, '
').replace(/\n/g, '
').replace(/\s/g, ' ');
    $('textarea[name="opinion"]').eq(i).val(opinion);
    return true;
}