'use strict';

/**
 *
 *
 * @author Mai
 * @date 2019/5/24
 * @version
 */
class ChangeAnalysis {

    constructor (ledgerData) {
        this.ledgerTreeSetting = {
            id: 'ledger_id',
            pid: 'ledger_pid',
            order: 'order',
            level: 'level',
            rootId: -1,
            keys: ['id', 'tender_id', 'ledger_id'],
        };
        this.ledgerTree = createNewPathTree('ledger', this.ledgerTreeSetting);
        this.ledgerTree.loadDatas(ledgerData);
    }

    getLeafXmj (node) {
        let n = node;
        while (n) {
            if (this.ledgerTree.isLeafXmj(n)) {
                return n;
            }
            n = this.ledgerTree.getParent(n);
        }
        return null;
    }

    analyze (change) {
        change.filterBills = false;
        change.attachments = change.detail.attachments;
        change.bills = change.detail.addUsedBills;
        for (const b of change.bills) {
            b.qty = _.toNumber(b.samount);
            b.valid_qty = ZhCalc.sub(b.qty - b.used_qty);
            b.pos = _.filter(change.detail.curUsedBills, {cbid: b.id});
            b.cur_qty = 0;
            for (const p of b.pos) {
                // 查询最底层项目节
                const node = this.ledgerTree.getItems(p.ledger_id);
                const leafXmj = this.getLeafXmj(node);
                if (leafXmj) {
                    p.leaf_xmj_code = leafXmj.code;
                    p.leaf_xmj_name = leafXmj.name;
                }
                b.cur_qty = ZhCalc.add(b.cur_qty, p.qty);
            }

        }
    }
}

$(document).ready(() => {
    autoFlashHeight();
    // ------------- begin 初始化界面
    // 初始化变更令spread
    const changeSpreadSetting = {
        cols: [
            {title: '变更令号', colSpan: '1', rowSpan: '1', field: 'code', hAlign: 0, width: 150, formatter: '@', readOnly: true},
            {title: '变更名称', colSpan: '1', rowSpan: '1', field: 'name', hAlign: 0, width: 350, formatter: '@', readOnly: true},
            {title: '金额', colSpan: '1', rowSpan: '1', field: 'total_price', hAlign: 2, width: 100, type: 'Number', readOnly: true},
            {title: '批复文号', colSpan: '1', rowSpan: '1', field: 'w_code', hAlign: 0, width: 150, formatter: '@', readOnly: true},
            {title: '已执行（%）', colSpan: '1', rowSpan: '1', field: 'used_pt', hAlign: 2, width: 100, type: 'Number', readOnly: true},
        ],
        emptyRows: 0,
        headRows: 1,
        headRowHeight: [40],
        defaultRowHeight: 21,
    };
    const changeSpread = SpreadJsObj.createNewSpread($('#bgl-spread')[0]);
    SpreadJsObj.initSheet(changeSpread.getActiveSheet(), changeSpreadSetting);
    // 初始化变更清单spread
    const billsSpreadSetting = {
        cols: [
            {title: '本期使用', colSpan: '1', rowSpan: '1', field: '', hAlign: 1, width: 40, formatter: '@', readOnly: true, cellType: 'image', img: function (data) {
                if (!checkZero(data.cur_qty)) {
                    return $('#icon-ok')[0];
                } else {
                    return null;
                }
            }},
            {title: '清单编号', colSpan: '1', rowSpan: '1', field: 'code', hAlign: 0, width: 80, formatter: '@', readOnly: true},
            {title: '名称', colSpan: '1', rowSpan: '1', field: 'name', hAlign: 0, width: 150, type: 'Number', readOnly: true},
            {title: '单位', colSpan: '1', rowSpan: '1', field: 'unit', hAlign: 1, width: 50, formatter: '@', readOnly: true},
            {title: '单价', colSpan: '1', rowSpan: '1', field: 'unit_price', hAlign: 2, width: 60, type: 'Number', readOnly: true},
            {title: '数量', colSpan: '1', rowSpan: '1', field: 'qty', hAlign: 2, width: 60, formatter: '@', readOnly: true},
            {title: '金额', colSpan: '1', rowSpan: '1', field: 'tp', hAlign: 2, width: 60, formatter: '@', readOnly: true},
            {title: '已变更', colSpan: '1', rowSpan: '1', field: 'used_qty', hAlign: 2, width: 60, type: 'Number', readOnly: true},
            {title: '未变更', colSpan: '1', rowSpan: '1', field: 'valid_qty', hAlign: 2, width: 60, formatter: '@', readOnly: true},
        ],
        emptyRows: 0,
        headRows: 1,
        headRowHeight: [40],
        defaultRowHeight: 21,
    };
    const billsSpread = SpreadJsObj.createNewSpread($('#bills-spread')[0]);
    SpreadJsObj.initSheet(billsSpread.getActiveSheet(), billsSpreadSetting);
    // 初始化相关台账spread
    const posSpreadSetting = {
        cols: [
            {title: '相关台账|项目节编号', colSpan: '5|1', rowSpan: '1|1', field: 'l_code', hAlign: 0, width: 120, formatter: '@', readOnly: true},
            {title: '|名称', colSpan: '|1', rowSpan: '1', field: 'l_name', hAlign: 0, width: 150, formatter: '@', readOnly: true},
            {title: '|部位明细', colSpan: '|1', rowSpan: '1', field: 'p_name', hAlign: 0, width: 150, type: 'Number', readOnly: true},
            {title: '|0号台帐数量', colSpan: '|1', rowSpan: '1', field: 'l_qty', hAlign: 2, width: 60, formatter: '@', readOnly: true},
            {title: '|本期变更数量', colSpan: '|1', rowSpan: '1', field: 'qty', hAlign: 2, width: 65, type: 'Number', readOnly: true},
        ],
        emptyRows: 0,
        headRows: 2,
        headRowHeight: [25, 40],
        defaultRowHeight: 21,
    };
    const posSpread = SpreadJsObj.createNewSpread($('#pos-spread')[0]);
    SpreadJsObj.initSheet(posSpread.getActiveSheet(), posSpreadSetting);
    // 上下窗口resizer
    $.divResizer({
        select: '#main-resize',
        callback: function () {
            changeSpread.refresh();
            let bcontent = $(".bcontent-wrap").length > 0 ? $(".bcontent-wrap").height() : 0;
            $(".sp-wrap").height(bcontent-40);
            if ($('#qingdan').hasClass('active')) {
                billsSpread.refresh();
                posSpread.refresh();
            }
        }
    });
    // 左右窗口resizer
    $.divResizer({
        select: '#bills-resize',
        callback: function () {
            billsSpread.refresh();
            posSpread.refresh();
        }
    });
    // ------------end 初始化界面

    // ------------begin 预处理数据
    const analysis = new ChangeAnalysis(ledger);
    if (changes.length > 0) {
        analysis.analyze(changes[0]);
    }
    // ------------end 预处理数据

    // ------------begin spread界面操作方法
    const posSpreadObj = {
        loadCurPosData () {
            const bills = SpreadJsObj.getSelectObject(billsSpread.getActiveSheet());
            if (bills) {
                console.log(bills.pos);
                SpreadJsObj.loadSheetData(posSpread.getActiveSheet(), SpreadJsObj.DataType.Data, bills.pos);
            } else {
                SpreadJsObj.loadSheetData(posSpread.getActiveSheet(), SpreadJsObj.DataType.Data, []);
            }
        }
    };
    const billsSpreadObj = {
        loadCurBillsData () {
            const change = SpreadJsObj.getSelectObject(changeSpread.getActiveSheet());
            if (change) {
                SpreadJsObj.loadSheetData(billsSpread.getActiveSheet(), SpreadJsObj.DataType.Data, change.bills);
            } else {
                SpreadJsObj.loadSheetData(billsSpread.getActiveSheet(), SpreadJsObj.DataType.Data, []);
            }
        },
        selectionChanged: function () {
            posSpreadObj.loadCurPosData();
        },
        filterUsedBills: function (isFilter) {
            const bills = SpreadJsObj.getSortData(billsSpread.getActiveSheet());
            for (const b of bills) {
                b.visible = !isFilter || !checkZero(b.cur_qty);
            }
            SpreadJsObj.refreshTreeRowVisible(billsSpread.getActiveSheet());
        }
    };
    billsSpread.bind(spreadNS.Events.SelectionChanged, billsSpreadObj.selectionChanged);
    let curChangeId;
    const changeSpreadObj = {
        loadChangeDetailData() {
            const change = SpreadJsObj.getSelectObject(changeSpread.getActiveSheet());
            billsSpreadObj.loadCurBillsData();
            posSpreadObj.loadCurPosData();
            if (change && change.filterBills !== $('#used-bills')[0].checked) {
                change.fitlerBills = $('#used-bills')[0].checked;
                billsSpreadObj.filterUsedBills(change.fitlerBills);
            }
            // 加载变更信息和附件
            const obj = $('.tab-content');
            if (change) {
                const inputs = $('input[type!=checkbox]', obj);
                for (const i of inputs) {
                    const field = $(i).attr('name');
                    const text = (field && change[field]) ? change[field] : '';
                    $(i).val(text);
                }
                const textareas = $('textarea', obj);
                for (const ta of textareas) {
                    const field = $(ta).attr('name');
                    const text = (field && change[field]) ? change[field] : '';
                    ta.innerText = text;
                }
                const html = [];
                for (const a of change.attachments) {
                    html.push('<tr>');
                    html.push('<td>', '<a href="/change/download/file/' + a.id + '">', a.filename + a.fileext, '</a>', '</td>');
                    html.push('<td>', a.u_name, '</td>');
                    html.push('</tr>');
                }
                // 变更类型
                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('<option>' + change.company ? change.company : '' + '</option>');
                // 费用承担方
                $('input[name=charge][value=' + change.charge + ']').prop('checked', true);
                // 附件
                $('#attachment').html(html.join(''));
            } else {
                const inputs = $('input', obj);
                for (const i of inputs) {
                    $(i).val('');
                }
                const textareas = $('textarea', obj);
                for (const ta of textareas) {
                    ta.innerText = '';
                }
                $('#attachment').html('');
            }
        },
        selectionChanged: function () {
            const change = SpreadJsObj.getSelectObject(changeSpread.getActiveSheet());
            if (change.cid === curChangeId) { return; }
            curChangeId = change.cid;
            if (change.detail) {
                changeSpreadObj.loadChangeDetailData();
            } else {
                postData(window.location.pathname + '/detail', {cid: change.cid}, function (result) {
                    change.detail = result;
                    analysis.analyze(change);
                    changeSpreadObj.loadChangeDetailData();
                });
            }
        },
        filterUsedChange: function (isFilter) {
            for (const c of changes) {
                c.visible = !isFilter || usedChangesId.indexOf(c.cid) >= 0;
            }
            SpreadJsObj.refreshTreeRowVisible(changeSpread.getActiveSheet());
        }
    };
    changeSpread.bind(spreadNS.Events.SelectionChanged, changeSpreadObj.selectionChanged);
    // ------------end spread界面操作方法


    // ------------begin 加载数据至界面
    SpreadJsObj.loadSheetData(changeSpread.getActiveSheet(), SpreadJsObj.DataType.Data, changes);
    changeSpreadObj.loadChangeDetailData();
    if (usedChangesId.length > 0) {
        changeSpreadObj.filterUsedChange(true);
    } else {
        $('#used-change')[0].checked = false;
    }
    // ------------end 加载数据至界面

    // ------------begin dom事件定义
    // 本期已用变更
    $('#used-change').click(function () {
        if (usedChangesId.length === 0 && this.checked) {
            toast('本期无已用变更令', 'hint');
            this.checked = false;
        }
        changeSpreadObj.filterUsedChange(this.checked);
    });
    // 切换标签页
    $('a[data-toggle="tab"]').on('show.bs.tab', function (e) {
        if (e.target.href.indexOf('#qingdan') !== -1) {
            $('#qd-filter').show();
        } else {
            $('#qd-filter').hide();
        }
    });
    // 只显示本期使用 变更清单
    $('#used-bills').click(function () {
        const change = SpreadJsObj.getSelectObject(changeSpread.getActiveSheet());
        change.filterBills = this.checked;
        billsSpreadObj.filterUsedBills(this.checked);
    });
    // ------------end dom事件定义
});