'use strict';

/**
 *
 *
 * @author Mai
 * @date 2018/5/30
 * @version
 */

function loadContent(data) {
    const html = [];
    html.push('<div name="auditContent" class="card my-3">');
    html.push('<div class="card-body">');
    html.push('<table class="table table-sm table-bordered mb-2">');
    console.log(data);
    console.log(data.rela_bills);
    const bills = JSON.parse(data.rela_bills);
    console.log(bills);
    for (const b of bills) {
        html.push('<tr bid=' + b.ledger_id + '>');
        const code = b.code ? b.code : b.b_code;
        html.push('<td>' + code + '</td>');
        html.push('<td>' + b.name + '</td>');
        html.push('</tr>');
    }
    html.push('</table>');
    html.push('<p>'+ data.content +'</p>');
    html.push('<span class="text-muted">' + data.in_time.toLocaleString() + '</span>');
    html.push('</div>');
    html.push('</div>');
    $('#opinion>div.sjs-height-2').append(html.join(''));
}

function loadContents(data) {
    $('div[name=auditContent]').remove();
    for (const d of data) {
        loadContent(d);
    }
};

$(document).ready(() => {
    autoFlashHeight();
    const ledgerSpread = SpreadJsObj.createNewSpread($('#ledger-spread')[0]);
    const ledgerTree = createNewPathTree({
        id: 'ledger_id',
        pid: 'ledger_pid',
        order: 'order',
        level: 'level',
        rootId: -1,
        keys: ['id', 'tender_id', 'ledger_id']
    });
    ledgerTree.loadDatas(ledger);
    SpreadJsObj.initSheet(ledgerSpread.getActiveSheet(), ledgerSpreadSetting);
    SpreadJsObj.loadSheetData(ledgerSpread.getActiveSheet(), 'tree', ledgerTree);

    let dealBills;
    // 展开收起标准清单
    $('a', '.side-menu').bind('click', function () {
        const tab = $(this), tabPanel = $(tab.attr('content'));
        const showSideTools = function (show) {
            if (show) {
                $('.c-body.col-12').removeClass('col-12').addClass('col-8');
                $('.c-body.col-0').removeClass('col-0').addClass('col-4').show();
            } else {
                $('.c-body.col-8').removeClass('col-8').addClass('col-12');
                $('.c-body.col-4').removeClass('col-4').addClass('col-0').hide();
            }
        }
        if (!tab.hasClass('active')) {
            $('a', '#side-menu').removeClass('active');
            tab.addClass('active');
            showSideTools(tab.hasClass('active'));
            $('.tab-content .tab-pane').hide();
            tabPanel.show();
            if (tab.attr('content') === '#deal-bills' && !dealBills) {
                dealBills = new DealBills($('#deal-bills-spread')[0], {
                    cols: [
                        {title: '清单编号', field: 'code', width: 120, readOnly: true},
                        {title: '名称', field: 'name', width: 230, readOnly: true},
                        {title: '单位', field: 'unit', width: 50, readOnly: true},
                        {title: '单价', field: 'unit_price', width: 50, readOnly: true},
                        {title: '数量', field: 'quantity', width: 50, readOnly: true},
                    ],
                    emptyRows: 0,
                });
                dealBills.loadData();
            }
        } else {
            tab.removeClass('active');
            showSideTools(tab.hasClass('active'));
            tabPanel.hide();
        }
        ledgerSpread.refresh();
    });
    class DealBills {
        constructor (obj, spreadSetting) {
            this.obj = obj;
            this.url = '/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);
            });
        }
    }

    // 右键菜单
    $.contextMenu({
        selector: '#ledger-spread',
        build: function ($trigger, e) {
            const target = SpreadJsObj.safeRightClickSelection($trigger, e, ledgerSpread);
            return target.hitTestType === GC.Spread.Sheets.SheetArea.viewport || target.hitTestType === GC.Spread.Sheets.SheetArea.rowHeader;
        },
        items: {
            'addRelaBills': {
                name: '添加至“清单意见”',
                icon: 'fa-sign-in',
                callback: function (key, opt) {
                    const sheet = ledgerSpread.getActiveSheet();
                    const selection = sheet.getSelections();
                    const row = selection[0].row;
                    const select = ledgerTree.nodes[row];
                    const exist = $('tr[bid=' + select.ledger_id +']', '#rela_bills').length > 0;
                    if (!exist) {
                        const html = [];
                        html.push('<tr bid=' + select.ledger_id + '>');
                        html.push('<td>');
                        html.push(select.code && select.code !== '' ? select.code : select.b_code);
                        html.push('</td>');
                        html.push('<td>' + select.name + '</td>');
                        html.push('<td><a href="javascript: void(0);">移除</a></td>');
                        html.push('</tr>');
                        $('#rela_bills').append(html.join(''));
                    }
                    $('#billsHint').hide();

                    if ($('tr[bid]', '#rela_bills').length === 1) {
                        $('a', '#rela_bills').bind('click', function () {
                            $(this).parent().parent().remove();
                            if ($('tr[bid]', '#rela_bills').length === 0) {
                                $('#billsHint').show();
                            }
                        });
                    }
                },
                visible: function(key, opt){
                    const sheet = ledgerSpread.getActiveSheet();
                    const selection = sheet.getSelections();
                    const row = selection[0].row;
                    const select = ledgerTree.nodes[row];
                    return select;
                }
            },
        }
    });
    $('textarea').bind('input propertychange', function () {
        if ($(this).val().length > 0) {
            $('#opinionHint').hide();
        } else {
            $('#opinionHint').show();
        }
    });
    $('#addContent').click(function () {
        const bills = [];
        for (const tr of $('#rela_bills>tr')) {
            bills.push($(tr).attr('bid'));
        }
        const data = {
            opinion: $('#content').val(),
            bills,
        };
        postData('/ledger/audit/addContent', data, (data) => {
            $('legend', '#opinion').text(userName + ' 清单意见');
            loadContents(data);
        });
    });
    $('select').change(function () {
        postData('/ledger/audit/getContent', {audit_id: parseInt($(this).val())}, (data) => {
            $('legend', '#opinion').text($(this).find('option:selected').text() + ' 清单意见');
            loadContents(data);
        });
    });
});
