'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);
    ledgerTree.loadDatas(ledger);
    treeCalc.calculateAll(ledgerTree);
    SpreadJsObj.initSheet(ledgerSpread.getActiveSheet(), ledgerSpreadSetting);
    SpreadJsObj.loadSheetData(ledgerSpread.getActiveSheet(), 'tree', ledgerTree);
    SpreadJsObj.loadTopAndSelect(ledgerSpread.getActiveSheet(), ckBillsSpread);

    // 初始化 部位明细
    const pos = new PosData({
        id: 'id', ledgerId: 'lid',
    });
    const posSpread = SpreadJsObj.createNewSpread($('#pos-spread')[0]);

    const 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-40);
                posSpread.refresh();
            }
        });
        SpreadJsObj.initSheet(posSpread.getActiveSheet(), posSpreadSetting);
        postData('/tender/' + getTenderId() + '/pos', null, function (data) {
            pos.loadDatas(data);
            loadCurPosData();
            SpreadJsObj.resetTopAndSelect(posSpread.getActiveSheet());
        });
    }

    ledgerSpread.bind(GC.Spread.Sheets.Events.SelectionChanged, function (e, info) {
        loadCurPosData();
        SpreadJsObj.saveTopAndSelect(info.sheet, ckBillsSpread);
    });
    ledgerSpread.bind(spreadNS.Events.TopRowChanged, function (e, info) {
        SpreadJsObj.saveTopAndSelect(info.sheet, ckBillsSpread);
    });

    let dealBills;
    $.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: 120, formatter: '@', readOnly: true},
                        {title: '名称', field: 'name', width: 230, 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},
                    ],
                    emptyRows: 0,
                    headRows: 1,
                    headRowHeight: [40],
                    defaultRowHeight: 21,
                });
                dealBills.loadData();
            }
        } 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) {
        if (!sheet.zh_tree) return;
        $(select).click(function () {
            const tag = $(this).attr('tag');
            const tree = sheet.zh_tree;
            switch (tag) {
                case "1":
                case "2":
                case "3":
                case "4":
                case "5":
                    tree.expandByLevel(parseInt(tag));
                    SpreadJsObj.refreshTreeRowVisible(sheet);
                    break;
                case "last":
                    tree.expandByCustom(() => { return true; });
                    SpreadJsObj.refreshTreeRowVisible(sheet);
                    break;
                case "leafXmj":
                    tree.expandToLeafXmj();
                    SpreadJsObj.refreshTreeRowVisible(sheet);
                    break;
            }
        });
    })('a[name=showLevel]', ledgerSpread.getActiveSheet());
});
