'use strict';

/**
 * 期计量 - 本期计量台账页面 js
 *
 * @author Mai
 * @date 2018/12/7
 * @version
 */
function checkTzMeasureType () {
    return tender.measure_type === measureType.tz.value;
}

/**
 * 从cookie中读取缓存的列显示设置，没有则取默认
 * @returns {*[]}
 */
function customColDisplay () {
    const defaultSetting = [
        { title: '签约合同', fields: ['deal_qty', 'deal_tp'], visible: true },
        { title: '施工图复核', fields: ['quantity', 'total_price'], visible: true },
        { title: '本期计量合同', fields: ['contract_qty', 'contract_tp'], visible: true },
        { title: '本期数量变更', fields: ['qc_qty', 'qc_tp', 'qc_bgl'], visible: true },
        { title: '本期完成计量', fields: ['gather_qty', 'gather_tp'], visible: true },
        { title: '截止本期计量合同', fields: ['end_contract_qty', 'end_contract_tp'], visible: true },
        { title: '截止本期数量变更', fields: ['end_qc_qty', 'end_qc_tp', 'end_qc_bgl'], visible: true },
        { title: '截止本期完成计量', fields: ['end_gather_qty', 'end_gather_tp'], visible: true },
        { title: '图册号', fields: ['drawing_code'], visible: true },
        { title: '累计完成率(%)', fields: ['percent'], visible: true },
        { title: '备注', fields: ['memo'], visible: true },
    ];
    const settingStr = Cookies.get('stage-col-visible');
    return settingStr ? JSON.parse(settingStr) : defaultSetting;
}

/**
 * 根据列显示设置，调整setting中的列是否显示
 * @param setting
 * @param customDisplay
 */
function customizeStageTreeSetting(setting, customDisplay) {
    for (const cd of customDisplay) {
        for (const c of setting.cols) {
            if (cd.fields.indexOf(c.field) !== -1) {
                c.visible = cd.visible;
            }
        }
    }
}

$(document).ready(() => {
    autoFlashHeight();
    // 初始化 台账 spread
    const slSpread = SpreadJsObj.createNewSpread($('#stage-ledger')[0]);
    customizeStageTreeSetting(ledgerSpreadSetting, customColDisplay());
    SpreadJsObj.initSheet(slSpread.getActiveSheet(), ledgerSpreadSetting);
    const stageTreeSetting = {
        id: 'ledger_id',
        pid: 'ledger_pid',
        order: 'order',
        level: 'level',
        rootId: -1,
        keys: ['id', 'tender_id', 'ledger_id'],
        stageId: 'id',
    };
    // 台账树结构计算相关设置
    stageTreeSetting.updateFields = ['contract_qty', 'contract_tp', 'qc_qty', 'qc_tp'];
    stageTreeSetting.calcFields = ['deal_tp', 'total_price', 'contract_tp', 'qc_tp', 'gather_tp', 'end_contract_tp', 'end_qc_tp', 'end_gather_tp'];
    stageTreeSetting.calcFun = function (node) {
        if (node.children && node.children.length === 0) {
            node.gather_qty = _.add(node.contract_qty, node.qc_qty);
            node.end_contract_qty = _.add(node.pre_contract_qty, node.contract_qty);
            node.end_qc_qty = _.add(node.pre_qc_qty, node.qc_qty);
            node.end_gather_qty = _.add(node.pre_gather_qty, node.gather_qty);
        }
        node.gather_tp = _.add(node.contract_tp, node.qc_tp);
        node.end_contract_tp = _.add(node.pre_contract_tp, node.contract_tp);
        node.end_qc_tp = _.add(node.pre_qc_tp, node.qc_tp);
        node.end_gather_tp = _.add(node.pre_gather_tp, node.gather_tp);
        if (checkZero(node.dgn_qty1)) {
            node.dgn_price = _.round(node.total_price/node.dgn_qty1, 2);
        } else {
            node.dgn_price = null;
        }
    };
    // 初始化 台账树结构
    const stageTree = createNewPathTree('stage', stageTreeSetting);
    stageTree.loadDatas(ledgerData);
    stageTree.loadCurStageData(curStageData);
    // 根据设置 计算 台账树结构
    treeCalc.calculateAll(stageTree);
    // 绘制界面
    SpreadJsObj.loadSheetData(slSpread.getActiveSheet(), 'tree', stageTree);

    // 初始化 部位明细
    const stagePosSetting = {
        id: 'id', ledgerId: 'lid',
        updateFields: ['contract_qty', 'qc_qty'],
    };
    stagePosSetting.calcFun = function (pos) {
        pos.gather_qty = _.add(pos.contract_qty, pos.qc_qty);
    };
    const stagePos = new StagePosData(stagePosSetting);
    const spSpread = SpreadJsObj.createNewSpread($('#stage-pos')[0]);
    SpreadJsObj.initSheet(spSpread.getActiveSheet(), posSpreadSetting);

    const stageTreeSpreadObj = {
        refreshTreeNodes: function (sheet, nodes) {
            const tree = sheet.zh_tree;
            if (!tree) { return }
            const rows = [];
            for (const node of nodes) {
                rows.push(tree.nodes.indexOf(node));
            }
            SpreadJsObj.reLoadRowsData(sheet, rows);
        },
        editEnding: function (e, info) {
            if (info.sheet.zh_setting) {
                const col = info.sheet.zh_setting.cols[info.col];
                const sortData = info.sheet.zh_dataType === 'tree' ? info.sheet.zh_tree.nodes : info.sheet.zh_data;
                const node = sortData[info.row];

                if (node.children && node.children.length > 0) {
                    toast('清单父项不可计量', 'error');
                    info.cancel = true;
                    return;
                } else {
                    const nodePos = stagePos.getLedgerPos(node.id);
                    if (nodePos && nodePos.length > 0) {
                        toast('该清单有部位明细，请在部位明细处计量', 'error');
                        info.cancel = true;
                        return;
                    }
                }
                const billsData = {
                    lid: node.id
                };
                billsData[col.field] = col.type === 'Number' ? parseFloat(info.editingText) : info.editingText;

                postData(window.location.href + '/update', { bills: billsData }, function (data) {
                    const nodes = stageTree.loadPostStageData(data.bills);
                    stageTreeSpreadObj.refreshTreeNodes(slSpread.getActiveSheet(), nodes);
                });
            }
        },
        selectionChanged: function (e, info) {
            stagePosSpreadObj.loadCurPosData();
        },
        deletePress(sheet) {
            if (sheet.zh_setting && sheet.zh_dataType === 'tree') {
                const tree = sheet.zh_tree;
                if (!tree) { return; }

                const sel = sheet.getSelections()[0];
                const validCols = [];
                for (let iCol = sel.col; iCol < sel.col + sel.colCount; iCol++) {
                    if (!sheet.zh_setting.cols[iCol].readOnly) {
                        validCols.push(iCol);
                    }
                }
                if (validCols.length === 0) { return; }

                const sortData = sheet.zh_tree.nodes;
                const datas = [];
                for (let iRow = sel.row; iRow < sel.row + sel.rowCount; iRow++) {
                    const node = sortData[iRow];
                    if (node) {
                        if (node.children && node.children.length > 0) { continue; }
                        const nodePos = stagePos.getLedgerPos(node.id);
                        if (nodePos && nodePos.length > 0) { continue; }

                        const data = { lid: node.id };
                        for (const iCol of validCols) {
                            const colSetting = sheet.zh_setting.cols[iCol];
                            data[colSetting.field] = null;
                        }
                        datas.push(data);
                    }
                }
                if (datas.length > 0) {
                    postData(window.location.href + '/update', {bills: datas}, function (result) {
                        const nodes = stageTree.loadPostStageData(result.bills);
                        stageTreeSpreadObj.refreshTreeNodes(slSpread.getActiveSheet(), nodes);
                    });
                }
            }
        },
        clipboardPasting(e, info) {
            if (info.sheet.zh_setting) {
                const sortData = info.sheet.zh_data;
                const range = info.cellRange;
                const validField = ['contract_qty', 'contract_tp', 'qc_qty', 'postil'];
                for (let iCol = range.col; iCol < range.col + range.colCount; iCol++) {
                    const col = info.sheet.zh_setting.cols[iCol];
                    if (validField.indexOf(col.field) === -1) {
                        toast('不可修改此数据', 'error');
                        info.cancel = true;
                        return;
                    }
                }
            }
        },
        clipboardPasted(e, info) {
            if (info.sheet.zh_setting && info.sheet.zh_tree) {
                const sheet = info.sheet;
                const filterNodes = [], datas = [];

                console.log(info.cellRange);
                for (let iRow = 0; iRow < info.cellRange.rowCount; iRow++) {
                    const curRow = iRow + info.cellRange.row;
                    const node = sheet.zh_tree.getItemsByIndex(curRow);
                    if (node.children && node.children.length > 0) {
                        filterNodes.push(node);
                        continue;
                    }
                    const nodePos = stagePos.getLedgerPos(node.id);
                    if (nodePos && nodePos.length > 0) {
                        filterNodes.push(node);
                        continue;
                    }

                    const data = {lid: node.id};
                    for (let iCol = 0; iCol < info.cellRange.colCount; iCol++) {
                        const curCol = info.cellRange.col + iCol;
                        const col = info.sheet.zh_setting.cols[curCol];
                        data[col.field] = col.type === 'Number' ? _.toNumber(info.sheet.getText(curRow, curCol)) : info.sheet.getText(curRow, curCol);
                    }
                    datas.push(data);
                }
                console.log(datas);
                if (datas.length > 0) {
                    postData(window.location.href + '/update', { bills: datas }, function (data) {
                        const nodes = stageTree.loadPostStageData(data.bills);
                        stageTreeSpreadObj.refreshTreeNodes(slSpread.getActiveSheet(), nodes.concat(filterNodes));
                    });
                } else {
                    stageTreeSpreadObj.refreshTreeNodes(slSpread.getActiveSheet(), filterNodes);
                }
            }
        }
    };
    slSpread.bind(spreadNS.Events.EditEnding, stageTreeSpreadObj.editEnding);
    slSpread.bind(spreadNS.Events.SelectionChanged, stageTreeSpreadObj.selectionChanged);
    slSpread.bind(spreadNS.Events.ClipboardPasting, stageTreeSpreadObj.clipboardPasting);
    slSpread.bind(spreadNS.Events.ClipboardPasted, stageTreeSpreadObj.clipboardPasted);
    SpreadJsObj.addDeleteBind(slSpread, stageTreeSpreadObj.deletePress);

    const stagePosSpreadObj = {
        /**
         * 加载部位明细 根据当前台账选择节点
         */
        loadCurPosData: function () {
            const node = SpreadJsObj.getSelectObject(slSpread.getActiveSheet());
            if (node) {
                const posData = stagePos.ledgerPos[itemsPre + node.id] || [];
                SpreadJsObj.loadSheetData(spSpread.getActiveSheet(), 'data', posData);
            } else {
                SpreadJsObj.loadSheetData(spSpread.getActiveSheet(), 'data', []);
            }
        },
        editEnding: function(e, info) {
            if (info.sheet.zh_setting) {
                // 未改变过，则直接跳过
                const orgText = info.sheet.getCell(info.row, info.row).value();
                if (orgText === info.editingText || ((!orgText || orgText === '') && (info.editingText === ''))) {
                    info.cancel = true;
                    return;
                }
                // 台账模式下，不可新增
                const pos = info.sheet.zh_data ? info.sheet.zh_data[info.row] : null;
                if (checkTzMeasureType() && !pos) {
                    toast('台账模式不可新增部位明细数据', 'error');
                    info.cancel = true;
                    return ;
                }
                // 不同节点下，部位明细检查输入
                const node = SpreadJsObj.getSelectObject(slSpread.getActiveSheet());
                if (!node) {
                    toast('数据错误, 请刷新页面后再试', 'warning');
                    info.cancel = true;
                    return;
                } else if (info.editingText !== '' && node.children && node.children > 0) {
                    toast('父节点不可插入部位明细', 'error');
                    info.cancel = true;
                    return;
                } else if (info.editingText !== '' && !node.b_code || node.b_code === '') {
                    toast('项目节不可插入部位明细', 'error');
                    info.cancel = true;
                    return;
                }
                const col = info.sheet.zh_setting.cols[info.col];
                const data = {};
                if (col.field === 'name') {
                    if (info.editingText === '' && pos) {
                        toast('部位名称不可为空', 'error', 'exclamation-circle');
                        info.cancel = true;
                        return;
                    } else if (!pos) {
                        if (info.editingText !== '') {
                            data.updateType = 'add';
                            data.updateData = {name: info.editingText, lid: node.id, tid: tender.id};
                        } else {
                            return;
                        }
                    } else {
                        data.updateType = 'update';
                        data.updateData = {id: pos.id, name: info.editingText};
                    }
                } else if (!pos) {
                    toast('新增部位请先输入名称', 'warning');
                } else {
                    data.updateType = 'update';
                    data.updateData = {pid: pos.id, lid: pos.lid};
                    data.updateData[col.field] = col.type === 'Number' ? parseFloat(info.editingText) : info.editingText;
                }
                postData(window.location.pathname + '/update', {pos: data}, function (result) {
                    if (result.pos) {
                        stagePos.updateDatas(result.pos.pos);
                        stagePos.loadCurStageData(result.pos.curStageData);
                    }
                    const nodes = stageTree.loadPostStageData(result.ledger.curStageData);
                    stageTreeSpreadObj.refreshTreeNodes(slSpread.getActiveSheet(), nodes);
                    stagePosSpreadObj.loadCurPosData();
                }, function () {
                    stagePosSpreadObj.loadCurPosData();
                });
            }
        },
        clipboardPasting: function (e, info) {
            if (info.sheet.zh_setting) {
                const sortData = info.sheet.zh_data;
                const range = info.cellRange;
                const validField = ['contract_qty', 'qc_qty', 'postil'];
                for (let iCol = range.col; iCol < range.col + range.colCount; iCol++) {
                    const col = info.sheet.zh_setting.cols[iCol];
                    if (validField.indexOf(col.field) === -1) {
                        if (checkTzMeasureType()) {
                            toast('不可修改此数据', 'error');
                            info.cancel = true;
                            return;
                        } else {
                            for (let iRow = range.row; iRow < range.row + range.rowCount; iRow) {
                                const pos = sortData(iRow);
                                if (pos.add_stage !== stage.id || pos.add_times !== stage.times) {
                                    toast('不可修改此数据', 'error');
                                    info.cancel = true;
                                    return;
                                }
                            }
                        }
                    }
                }
            }
        },
        clipboardPasted: function (e, info) {
            const self = this;
            if (info.sheet.zh_setting) {
                const data = { updateType: '', updateData: [], };
                const sortData = info.sheet.zh_data;
                const node = SpreadJsObj.getSelectObject(slSpread.getActiveSheet());
                if (sortData && (info.cellRange.row >= sortData.length)) {
                    data.updateType = 'add';
                    if (info.cellRange.col !== 0) {
                        toast('新增部位请先输入名称', 'warning');
                        self.loadCurPosData();
                        return;
                    }
                    for (let iRow = 0; iRow < info.cellRange.rowCount; iRow++) {
                        const curRow = info.cellRange.row + iRow;
                        const newData = {lid: node.id};
                        for (let iCol = 0; iCol < info.cellRange.colCount; iCol++) {
                            const curCol = info.cellRange.col + iCol;
                            const colSetting = info.sheet.zh_setting.cols[curCol];
                            newData[colSetting.field] = info.sheet.getText(curRow, curCol);
                            if (colSetting.type === 'Number') {
                                newData[colSetting.field] = _.toNumber(newData[colSetting.field]);
                            }
                        }
                        data.updateData.push(newData);
                    }
                } else {
                    data.updateType = 'update';
                    for (let iRow = 0; iRow < info.cellRange.rowCount; iRow++) {
                        const curRow = info.cellRange.row + iRow;
                        const curPos = sortData[curRow];
                        if (curPos) {
                            const newData = {pid: curPos.id, lid: curPos.lid};
                            for (let iCol = 0; iCol < info.cellRange.colCount; iCol++) {
                                const curCol = info.cellRange.col + iCol;
                                const colSetting = info.sheet.zh_setting.cols[curCol];
                                newData[colSetting.field] = info.sheet.getText(curRow, curCol);
                                if (colSetting.type === 'Number') {
                                    newData[colSetting.field] = _.toNumber(newData[colSetting.field]);
                                }
                            }
                            data.updateData.push(newData);
                        }
                    }
                }
                console.log(data);
                postData(window.location.pathname + '/update', {pos: data}, function (result) {
                    if (result.pos) {
                        stagePos.updateDatas(result.pos.pos);
                        stagePos.loadCurStageData(result.pos.curStageData);
                    }
                    const nodes = stageTree.loadPostStageData(result.ledger.curStageData);
                    stageTreeSpreadObj.refreshTreeNodes(slSpread.getActiveSheet(), nodes);
                    stagePosSpreadObj.loadCurPosData();
                }, function () {
                    stagePosSpreadObj.loadCurPosData();
                });
            }
        },
        deletePress: function (sheet) {
            if (sheet.zh_setting && sheet.zh_data) {
                const sortData = sheet.zh_data;
                if (!sortData || sortData.length === 0) { return; }

                const sel = sheet.getSelections()[0];
                const validCols = [];
                for (let iCol = sel.col; iCol < sel.col + sel.colCount; iCol++) {
                    if (!sheet.zh_setting.cols[iCol].readOnly) {
                        validCols.push(iCol);
                    }
                }
                if (validCols.length === 0) { return; }

                const datas = [], posSelects = [];
                for (let iRow = sel.row; iRow < sel.row + sel.rowCount; iRow++) {
                    const node = sortData[iRow];
                    if (node) {
                        const data = {pid: node.id, lid: node.lid};
                        for (const iCol of validCols) {
                            const colSetting = sheet.zh_setting.cols[iCol];
                            if (colSetting.field === 'name') {
                                toast('部位名称不能为空', 'error');
                                return;
                            }
                            data[colSetting.field] = null;
                        }
                        datas.push(data);
                        posSelects.push(node);
                    }
                }
                if (datas.length > 0) {
                    postData(window.location.pathname + '/update', {pos: {updateType: 'update', updateData: datas} }, function (result) {
                        if (result.pos) {
                            stagePos.updateDatas(result.pos.pos);
                            stagePos.loadCurStageData(result.pos.curStageData);
                        }
                        const nodes = stageTree.loadPostStageData(result.ledger.curStageData);
                        stageTreeSpreadObj.refreshTreeNodes(slSpread.getActiveSheet(), nodes);
                        // todo 只加载改变项
                        stagePosSpreadObj.loadCurPosData();
                    });
                }
            }
        },
    };
    // 加载上下窗口resizer
    $.divResizer({
        select: '#main-resize',
        callback: function () {
            slSpread.refresh();
            let bcontent = $(".bcontent-wrap") ? $(".bcontent-wrap").height() : 0;
            $(".sp-wrap").height(bcontent-40);
            spSpread.refresh();
        }
    });

    // 加载部位明细数据 - 暂时统一加载，如有需要，切换成动态加载并缓存
    postData(window.location.pathname + '/pos', null, function (result) {
        stagePos.loadDatas(result.pos);
        if (result.curStageData) {
            stagePos.loadCurStageData(result.curStageData);
        }
        if (result.preStageData) {
            stagePos.loadPreStageData(result.preStageData);
        }
        stagePosSpreadObj.loadCurPosData();
    });
    spSpread.bind(spreadNS.Events.EditEnding, stagePosSpreadObj.editEnding);
    spSpread.bind(spreadNS.Events.ClipboardPasting, stagePosSpreadObj.clipboardPasting);
    spSpread.bind(spreadNS.Events.ClipboardPasted, stagePosSpreadObj.clipboardPasted);
    SpreadJsObj.addDeleteBind(spSpread, stagePosSpreadObj.deletePress);

    $('#row-view').on('show.bs.modal', function () {
        const html = [], customDisplay = customColDisplay();
        for (const cd of customDisplay) {
            html.push('<tr>');
            html.push('<td>', cd.title, '</td>');
            html.push('<td>', '<input type="checkbox"' + (cd.visible ? ' checked=""' : '') + '>', '</td>');
            html.push('</tr>');
        }
        $('#row-view-list').html(html.join(''));
    });
    $('#row-view-ok').click(function () {
        const customDisplay = customColDisplay();
        const cvl = $('#row-view-list').children();
        for (const cv of cvl) {
            const title = $(cv).children()[0].innerHTML;
            const check = $('input', cv)[0].checked;
            const cd = customDisplay.find(function (c) {
                return c.title === title;
            });
            cd.visible = check;
        }
        customizeStageTreeSetting(ledgerSpreadSetting, customDisplay);
        SpreadJsObj.refreshColumnVisible(slSpread.getActiveSheet());
        Cookies.set('stage-col-visible', JSON.stringify(customDisplay), 7*24*60*60*1000);
        $('#row-view').modal('hide');
    });
});