'use strict';

/**
 *
 *
 * @author Mai
 * @date 2018/7/24
 * @version
 */

$(document).ready(() => {
    autoFlashHeight();

    const billsTree = createNewPathTree('measure', {
        id: 'ledger_id',
        pid: 'ledger_pid',
        order: 'order',
        level: 'level',
        rootId: -1,
        keys: ['id', 'tender_id', 'ledger_id'],
    });
    billsTree.loadDatas(billsData);
    treeCalc.calculateAll(billsTree, ['total_price', 'deal_totalprice', 'qc_totalprice']);
    const billsSpread = SpreadJsObj.createNewSpread($('#billsSpread')[0]);
    const sheet = billsSpread.getActiveSheet();
    SpreadJsObj.initSheet(sheet, measureSpreadSetting);
    SpreadJsObj.loadSheetData(sheet, 'tree', billsTree);
    /**
     * 父项不可编辑
     * sender - {type: 'EditStarting'}
     * args - {sheet, sheetName, row, col, cancel}
     */
    sheet.bind(spreadNS.Events.EditStarting, function (sender, args) {
        const sheet = args.sheet;
        if (sheet.zh_tree) {
            const node = sheet.zh_tree.nodes[args.row];
            args.cancel = node ? !node.is_leaf : true;
        } else {
            args.cancel = true;
        }
    });
    /**
     * 最底层清单编辑后，提交
     * sender - {type: 'EditEnding'}
     * args - {sheet, sheetName, row, col, editor, editingText cancel}
     */
    sheet.bind(spreadNS.Events.EditEnding, function (sender, args) {
        const sheet = args.sheet;
        if (sheet.zh_tree || sheet.zh_setting) {
            const node = sheet.zh_tree.nodes[args.row];
            const col = sheet.zh_setting.cols[args.col];
            if (node && node.is_leaf) {
                const updateData = {
                    mid: window.location.pathname.split('/')[3],
                    bid: node.ledger_id,
                    update: {},
                }
                updateData.update[col.field] = col.type === 'Number' ? parseFloat(args.editingText) : args.editingText;
                postData('/measure/billsUpdate', updateData, function (data) {
                    if (sheet.zh_tree.loadLeafData) {
                        sheet.zh_tree.loadLeafData(data);
                        const nodes = treeCalc.calculateParent(sheet.zh_tree, node, ['deal_totalprice', 'qc_totalprice']);
                        SpreadJsObj.reLoadNodesData(sheet, nodes);
                    }
                }, function () {
                    args.cancel = true;
                });
            } else {
                args.cancel = true;
            }
        } else {
            args.cancel = true;
        }
    });
});
