'use strict';

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

const stageIm = (function () {
    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.gather_qty = _.toNumber(node.contract_qty) + _.toNumber(node.qc_qty);
            node.end_contract_qty = _.toNumber(node.pre_contract_qty) + _.toNumber(node.contract_qty);
            node.end_qc_qty = _.toNumber(node.pre_qc_qty) + _.toNumber(node.qc_qty);
            node.end_gather_qty = _.toNumber(node.pre_gather_qty) + _.toNumber(node.gather_qty);
        }
        node.gather_tp = _.toNumber(node.contract_tp) + _.toNumber(node.qc_tp);
        node.end_contract_tp = _.toNumber(node.pre_contract_tp) + _.toNumber(node.contract_tp);
        node.end_qc_tp = _.toNumber(node.pre_qc_tp) + _.toNumber(node.qc_tp);
        node.end_gather_tp = _.toNumber(node.pre_gather_tp) + _.toNumber(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 gsTree = createNewPathTree('stage', gsTreeSetting);

    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, curStage, stageDetail) {
        gsTree.loadDatas(ledger);

        gsTree.loadCurStageData(curStage);
        // 根据设置 计算 台账树结构
        treeCalc.calculateAll(gsTree);

        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 fields = ['uuid', 'doc_code', 'bgl_code', 'start_peg', 'end_peg', 'bw', 'jldy', 'drawing_code', 'calc_memo', 'calc_img'];
        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 fields.indexOf(key) > -1 && sV ? sV : oV;
            });
            console.log(im);
        }
    }

    /**
     * 生成 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);
            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.lid,
                    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);
            }
            im.jl = _.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;
    }

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