'use strict';

/**
 *
 *
 * @author Mai
 * @date
 * @version
 */

$(document).ready(function () {
    autoFlashHeight();
    // 根据设置整理Spread设置
    function setSpreadSettingCols(setting, fieldSufs, Roles) {
        function addExtraCols(fieldSuf, Role) {
            for (const ec of setting.extraCols) {
                const col = JSON.parse(JSON.stringify(ec));
                col.title = _.replace(col.title, '%s', Role);
                col.field = _.replace(col.field, '%s', fieldSuf);
                setting.cols.push(col);
            }
        }
        setting.cols = [];
        for (const col of setting.baseCols) {
            setting.cols.push(col);
        }
        for (const index in fieldSufs) {
            addExtraCols(fieldSufs[index], Roles[index]);
        }
    }
    setSpreadSettingCols(ledgerSpreadSetting, ['0'], ['原报']);
    setSpreadSettingCols(posSpreadSetting, ['0'], ['原报']);

    function calculateStageLedgerData(datas) {
        for (const d of datas) {
            d.gather_qty = _.add(d.contract_qty, d.qc_qty);
            d.gather_tp = _.add(d.contract_tp, d.qc_tp);
        }
    }
    function calculateStagePosData(datas) {
        for (const d of datas) {
            d.gather_qty = _.add(d.contract_qty, d.qc_qty);
            d.gather_tp = _.add(d.contract_tp, d.qc_tp);
        }
    }

    // 初始化台账
    const ledgerSpread = SpreadJsObj.createNewSpread($('#ledger-spread')[0]);
    SpreadJsObj.initSheet(ledgerSpread.getActiveSheet(), ledgerSpreadSetting);
    // 初始化部位
    const posSpread = SpreadJsObj.createNewSpread($('#pos-spread')[0]);
    SpreadJsObj.initSheet(posSpread.getActiveSheet(), posSpreadSetting);
    // 上下窗口resizer
    $.divResizer({
        select: '#main-resize',
        callback: function () {
            ledgerSpread.refresh();
            let bcontent = $(".bcontent-wrap").length > 0 ? $(".bcontent-wrap").height() : 0;
            $(".sp-wrap").height(bcontent-40);
            posSpread.refresh();
        }
    });
    // 加载 台账树结构 数据
    const scTreeSetting = {
        id: 'ledger_id',
        pid: 'ledger_pid',
        order: 'order',
        level: 'level',
        rootId: -1,
        keys: ['id', 'tender_id', 'ledger_id'],
        masterId: 'id',
        minorId: 'lid',
    }
    //scTreeSetting.updateFields = ['contract_qty', 'contract_tp', 'qc_qty', 'qc_tp'];
    scTreeSetting.calcFields = ['gather_tp0'];
    const scTree = createNewPathTree('master', scTreeSetting);
    scTree.loadDatas(ledger);
    calculateStageLedgerData(orgStageLedger);
    scTree.loadMinorData(orgStageLedger, '0', ['gather_qty', 'gather_tp']);
    treeCalc.calculateAll(scTree);
    scTree.expandByCalcFields();
    SpreadJsObj.loadSheetData(ledgerSpread.getActiveSheet(), SpreadJsObj.DataType.Tree, scTree);
    // 加载 部位 数据
    const scPosSetting = {
        id: 'id', ledgerId: 'lid', masterId: 'id', minorId: 'pid',
        updateFields: ['contract_qty', 'qc_qty'],
    };
    scPosSetting.calcFun = function (pos) {
        pos.gather_qty = _.add(pos.contract_qty, pos.qc_qty);
    };
    const scPos = new MasterPosData(scPosSetting);
    scPos.loadDatas(pos);
    calculateStagePosData(orgStagePos);
    scPos.loadMinorData(orgStagePos, '0', ['gather_qty']);

    // 获取项目节数据
    function loadPosData(iRow) {
        const node = ledgerSpread.getActiveSheet().zh_tree.nodes[iRow];
        if (node) {
            SpreadJsObj.loadSheetData(posSpread.getActiveSheet(), SpreadJsObj.DataType.Data, scPos.getLedgerPos(node.id));
        } else {
            SpreadJsObj.loadSheetData(posSpread.getActiveSheet(), SpreadJsObj.DataType.Data, []);
        }
    }
    loadPosData(0);
    // 切换清单行，读取所属项目节数据
    ledgerSpread.getActiveSheet().bind(spreadNS.Events.SelectionChanged, function (e, info) {
        const iOldRow = info.oldSelections[0].row, iNewRow = info.newSelections[0].row;
        if (iNewRow !== iOldRow) {
            loadPosData(iNewRow);
        }
    });
    // 显示本期计量
    $('#customCheckDisabled').click(function () {
        if (this.checked) {
            scTree.expandByCalcFields();
        } else {
            scTree.expandByLevel(20);
        }
        SpreadJsObj.refreshTreeRowVisible(ledgerSpread.getActiveSheet());
    });
    // 选择比较人
    $('#select-qi-ok').click(function () {
        function refreshView () {
            scTreeSetting.calcFields = [];
            const fieldSufs = ['0'], roles = ['原报'], trs = $('tr[auditorId]');
            for (let order = 0, iLength = trs.length; order < iLength; order++) {
                fieldSufs.push(order + '');
                roles.push(tr.children()[0].text);
                scTreeSetting.calcFields.push('gather_tp' + order);
            }
            setSpreadSettingCols(ledgerSpreadSetting, fieldSufs, roles);
            SpreadJsObj.initSheet(ledgerSpread.getActiveSheet(), ledgerSpreadSetting);
            treeCalc.calculateAll(scTree);
            scTree.expandByCalcFields();
            SpreadJsObj.loadSheetData(ledgerSpread.getActiveSheet(), SpreadJsObj.DataType.Tree, scTree);
            setSpreadSettingCols(posSpreadSetting, fieldSufs, roles);
            SpreadJsObj.initSheet(posSpread.getActiveSheet(), posSpreadSetting);
            loadPosData(0);
        }
        let loadData = [], showData = [], trs = $('tr[auditorId]');
        for (let order = 0, iLength = trs.length; order < iLength; order++) {
            const tr = trs[order];
            if ($('input[type=check]', tr)[0].checked) {
                if (!scTree.minorData[tr]) {
                    loadData.push(order + 1);
                }
                showData.push(order + 1);
            }
        }
        if (loadData.length > 0) {
            postData(window.location.pathname + '/load', {auditors: loadData}, function (result) {
                for (const aData of result) {
                    calculateStageLedgerData(aData.bills);
                    scTree.loadMinorData(aData.bills, aData.order + '', ['gather_qty', 'gather_tp']);
                    treeCalc.calculateAll(scTree);
                    calculateStagePosData(aData.pos);
                    scPos.loadMinorData(aData.pos, aData.order + '', ['gather_qty']);
                }
                refreshView();
                $('#select-qi').modal('hide');
            });
        } else {
            refreshView();
            $('#select-qi').modal('hide');
        }
    });
});