'use strict';

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

const stageIm = (function () {
    const imFields = ['uuid', 'doc_code', 'bgl_code', 'start_peg', 'end_peg', 'bw', 'jldy', 'drawing_code', 'calc_memo', 'calc_img'];
    const splitChar = '-';
    let stage, imType, details, ImData, pre;
    const gsTreeSetting = {
        id: 'ledger_id',
        pid: 'ledger_pid',
        order: 'order',
        level: 'level',
        rootId: -1,
        keys: ['id', 'tender_id', 'ledger_id'],
        stageId: 'id',
    };
    gsTreeSetting.updateFields = ['contract_qty', 'contract_tp', 'qc_qty', 'qc_tp'];
    gsTreeSetting.calcFields = ['deal_tp', 'total_price', 'contract_tp', 'qc_tp', 'gather_tp', 'end_contract_tp', 'end_qc_tp', 'end_gather_tp'];
    gsTreeSetting.calcFun = function (node) {
        if (node.children && node.children.length === 0) {
            node.pre_gather_qty = ZhCalc.add(node.pre_contract_qty, node.pre_qc_qty);
            node.gather_qty = ZhCalc.add(node.contract_qty, node.qc_qty);
            node.end_contract_qty = ZhCalc.add(node.pre_contract_qty, node.contract_qty);
            node.end_qc_qty = ZhCalc.add(node.pre_qc_qty, node.qc_qty);
            node.end_gather_qty = ZhCalc.add(node.pre_gather_qty, node.gather_qty);
        }
        node.pre_gather_tp = ZhCalc.add(node.pre_contract_tp, node.pre_qc_tp);
        node.gather_tp = ZhCalc.add(node.contract_tp, node.qc_tp);
        node.end_contract_tp = ZhCalc.add(node.pre_contract_tp, node.contract_tp);
        node.end_qc_tp = ZhCalc.add(node.pre_qc_tp, node.qc_tp);
        node.end_gather_tp = ZhCalc.add(node.pre_gather_tp, node.gather_tp);
    };
    const gsTree = createNewPathTree('stage', gsTreeSetting);
    const gsPosSetting = {
        id: 'id', ledgerId: 'lid',
        updateFields: ['contract_qty', 'qc_qty', 'postil'],
    };
    gsPosSetting.calcFun = function (pos) {
        pos.pre_gather_qty = ZhCalc.add(pos.pre_contract_qty, pos.pre_qc_qty);
        pos.gather_qty = ZhCalc.add(pos.contract_qty, pos.qc_qty);
        pos.end_contract_qty = ZhCalc.add(pos.pre_contract_qty, pos.contract_qty);
        pos.end_qc_qty = ZhCalc.add(pos.pre_qc_qty, pos.qc_qty);
        pos.end_gather_qty = ZhCalc.add(pos.pre_gather_qty, pos.gather_qty);
    };
    const gsPos = new StagePosData(gsPosSetting);

    function init (s, i) {
        stage = s;
        imType = i;
    }

    function initCheck () {
        const gatherNodes = stage.im_gather_node ? _.map(stage.im_gather_node.split(','), _.toNumber) : [];
        for (const node of gsTree.datas) {
            node.check = gatherNodes.indexOf(node.id) !== -1;
        }

    }

    function loadData (ledger, pos, stageDetail) {
        gsTree.loadDatas(ledger);
        treeCalc.calculateAll(gsTree);

        gsPos.loadDatas(pos);
        gsPos.calculateAll();

        initCheck();
        details = stageDetail;
    }

    // function loadData (ledger, curStage, pos, curPosStage, stageDetail) {
    //     gsTree.loadDatas(ledger);
    //
    //     gsTree.loadCurStageData(curStage);
    //     // 根据设置 计算 台账树结构
    //     treeCalc.calculateAll(gsTree);
    //
    //     gsPos.loadDatas(pos);
    //     gsPos.loadCurStageData(curPosStage);
    //     gsPos.calculateAll();
    //
    //     initCheck();
    //     details = stageDetail;
    // }

    /**
     * 整数前补零
     * @param {Number} num - 数字
     * @param {Number} length - 总位数
     * @returns {*}
     */
    function getNumberFormat(num, length) {
        let s = '0000000000';
        s = s + num;
        return s.substr(s.length - length);
    }

    /**
     * 获取新 计量编号
     * @returns {string}
     */
    function getNewImCode () {
        return pre + getNumberFormat(stage.order, 2) + splitChar + getNumberFormat(ImData.length + 1, 3);
    }

    function getNodeByLevel(node, level) {
        let cur = node;
        while (cur && cur.level > level) {
            cur = gsTree.getParent(cur);
        }
        return cur;
    }

    function getFbfx (node, pegNode) {
        if (pegNode) {
            const subPegNode = getNodeByLevel(node, pegNode.level + 1);
            return subPegNode.id === pegNode.id ? pegNode.name : pegNode.name + '-' + subPegNode.name;
        } else {
            if (node.level < 3) {
                return node.name;
            } else {
                const l3Node = getNodeByLevel(node, 3);
                const l4Node = getNodeByLevel(node, 4);
                return l3Node.id === l4Node.id ? l3Node.name : l3Node.name + '-' + l4Node.name;
            }
        }
        return node.name;
    }

    function CheckPeg(text) {
        const pegReg = /[kK][0-9][+＋][0-9]{3}/;
        return pegReg.test(text);
    }

    function getPegNode (node) {
        if (node) {
            if (CheckPeg(node.name)) {
                return node;
            } else {
                const parent = gsTree.getParent(node);
                return parent ? getPegNode(parent) : null;
            }
        }
    }

    function getDrawingCode(node) {
        if (!node) {
            return '';
        } else if (node.drawing_code) {
            return node.drawing_code;
        } else {
            const parent = gsTree.getParent(node);
            return parent ? getDrawingCode(parent) : '';
        }
    }

    function checkCustomDetail(im) {
        const cd = _.find(details, function (d) {
            return im.lid === d.lid &&
                (!im.code || im.code === d.code) &&
                (!im.name || im.name === d.name) &&
                (!im.unit || im.unit === d.unit);
        });
        if (cd) {
            _.assignInWith(im, cd, function (oV, sV, key) {
                return imFields.indexOf(key) > -1 && sV !== undefined ? sV : oV;
            });
            console.log(im);
        }
    }

    function generatePosData(node, lx) {
        if (!lx.pos) {
            lx.pos = [];
        }
        const posRange = gsPos.getLedgerPos(node.id);
        if (!posRange) { return }
        for (const p of posRange) {
            if (!p.gather_qty || checkZero(p.gather_qty)) { continue; }
            let lp = _.find(lx.pos, {name: p.name});
            if (!lp) {
                lp = {name: p.name, qty: p.quantity};
                lx.pos.push(lp);
            }
            lp.jl = ZhCalc.add(lp.jl, p.gather_qty);
        }
    }

    /**
     * 生成所属项目节数据(取最底层项目节)
     * @param node - 生成数据基于的台账节点
     * @param im - 中间计量数据
     */
    function generateLeafXmjData(node, im, jlField) {
        if (!im.leafXmjs) {
            im.leafXmjs = [];
        }
        const leafXmj = gsTree.getLeafXmjParent(node);
        if (!leafXmj) { return }
        let lx = _.find(im.leafXmjs, {lxid: leafXmj.id});
        if (!lx) {
            lx = {
                lxid: leafXmj.id,
                code: leafXmj.code,
                name: leafXmj.name
            };
            im.leafXmjs.push(lx);
        }
        lx.jl = ZhCalc.add(lx.jl, node[jlField]);
        generatePosData(node, lx);
    }

    /**
     * 生成 0号台账 中间计量数据
     * @param {Object} node - 生成中间计量表的节点
     */
    function generateTzImData (node) {
        if (node.gather_tp) {
            const peg = getPegNode(node);
            const im = {
                lid: node.id,
                code: node.code,
                jl: node.gather_tp,
                im_code: getNewImCode(),
                fbfx: getFbfx(node, peg),
                peg: peg ? peg.name : '',
                drawing_code: getDrawingCode(node),
            };
            if (stage.im_gather && node.check) {
                im.bw = node.name;
            } else {
                im.jldy = node.name;
                // to do
                im.bw = node.name
            }
            checkCustomDetail(im);
            generateLeafXmjData(node, im, 'gather_tp');
            ImData.push(im);
        }
    }

    /**
     * 生成 总量控制 中间计量数据
     * @param {Object} node - 生成中间计量表的节点
     */
    function generateZlImData (node) {
        const nodeImData = [], posterity = gsTree.getPosterity(node);
        for (const p of posterity) {
            if (p.children && p.children.length > 0 ) { continue; }
            if (!p.b_code || p.b_code === '') { continue }
            if (!p.gather_qty || p.gather_qty === 0 ) { continue; }
            let im = nodeImData.find(function (d) {
                return d.code === p.b_code && p.name === d.name && p.unit === d.unit && checkZero(p.unit_price - d.unit_price);
            });
            if (!im) {
                const peg = getPegNode(node);
                im = {
                    lid: node.id,
                    code: p.b_code,
                    name: p.name,
                    unit: p.unit,
                    unit_price: p.unit_price,
                    jl: 0,
                    im_code: getNewImCode(),
                    fbfx: getFbfx(node, peg),
                    peg: peg ? peg.name : '',
                    drawing_code: getDrawingCode(node),
                    bw: node.name,
                };
                if (stage.im_gather && node.check) {

                } else {
                    im.jldy = p.name;
                }
                nodeImData.push(im);
                checkCustomDetail(im);
                ImData.push(im);
            }
            generateLeafXmjData(p, im, 'gather_qty');
            im.jl = ZhCalc.add(im.jl, p.gather_qty);
        }
    }

    /**
     * 递归 生成中间计量表
     * @param {Array} nodes
     */
    function recursiveBuildImData (nodes) {
        if (!nodes || nodes.length === 0) { return; }
        for (const node of nodes) {
            if (gsTree.isLeafXmj(node) || (stage.im_gather && node.check)) {
                if (stage.im_type === imType.tz.value) {
                    generateTzImData(node);
                } else {
                    generateZlImData(node);
                }
            } else {
                recursiveBuildImData(node.children);
            }
        }
    }

    /**
     * 生成 中间计量表 全部数据
     * @returns {Array}
     */
    function buildImData () {
        // 初始化
        ImData = [];
        pre = (stage.im_pre && stage.im_pre !== '') ? stage.im_pre + splitChar : '';
        if (stage.im_gather) {
            initCheck();
        }
        // 生成数据
        recursiveBuildImData(gsTree.children);
        return ImData;
    }

    function loadUpdateDetailData (data) {
        const datas = data instanceof Array ? data : [data];
        for (const d of datas) {
            const detail = _.find(details, {uuid: d.uuid});
            if (detail) {
                _.assignIn(detail, d);
            } else {
                details.push(d);
            }
            let imData = _.find(ImData, {lid: d.lid, uuid: d.uuid});
            if (!imData) {
                imData = _.find(ImData, {lid: d.lid, code: d.code, name: d.name, unit: d.unit});
            }
            if (imData) {
                _.assignInWith(imData, d, function (oV, sV, key) {
                    return imFields.indexOf(key) > -1 && !_.isUndefined(sV) ? sV : oV;
                });
            }
        }
    }

    return {
        init,
        initCheck,
        loadData,
        buildImData,
        loadUpdateDetailData,
        getGsTree: function () {
            return gsTree;
        },
        getImData: function () {
            return ImData;
        },

    }
})();