'use strict';
/**
 *
 *
 * @author Mai
 * @date 2018/10/11
 * @version
 */
const EmptyTenderHtml = [
    '
',
    '
还没有标段数据 ',
    ''
];
// levelTree - setting
const levelTreeSetting = {
    view: {
        selectedMulti: false
    },
    data: {
        simpleData: {
            idKey: 'lid',
            pIdKey: 'lpId',
            rootPId: 0,
            enable: true,
        }
    },
    edit: {
        enable: true,
        showRemoveBtn: false,
        showRenameBtn: false,
        drag: {
            autoExpandTrigger: true,
            isCopy: false,
            isMove:  true,
            prev: false,
            next: false,
            inner: true,
        }
    },
    callback: {
        beforeDrop: beforeDropNode,
        onDrop: onDropNode,
    }
};
const levelNodes =[];
const tenderTree = [];
let parentId = 0;
function createTree() {
    const zTree = $.fn.zTree.getZTreeObj('treeLevel');
    if (zTree) {
        zTree.destroy();
    }
    $.fn.zTree.init($("#treeLevel"), levelTreeSetting, levelNodes);
}
function beforeDropNode(treeId, treeNodes, targetNode, moveType, isCopy) {
    if (targetNode.lid !== 1) {
        const parent = targetNode.getParentNode();
        if (parent && parent.lid === 1) {
            return false;
        }
    }
}
function onDropNode(event, treeId, treeNodes, targetNode, moveType) {
    const zTree = $.fn.zTree.getZTreeObj(treeId);
    function resetFixNode(id) {
        const node = zTree.getNodeByParam('lid', id);
        node.isParent = true;
        zTree.updateNode(node, false);
        zTree.expandNode(node, true);
    }
    function moveChildren(children, node) {
        if (!children || children.length === 0) { return }
        for (const c of children) {
            moveChildren(c.children, node);
            zTree.moveNode(node, c, 'inner');
        }
    }
    resetFixNode(1);
    resetFixNode(2);
    if (targetNode.lid === 1 && treeNodes[0].children && treeNodes[0].children.length !== 0) {
        moveChildren(treeNodes[0].children, zTree.getNodeByParam('lid', 1));
    } else if (targetNode.lid !== 1) {
        if (targetNode.children.length >= 2) {
            for (const c of targetNode.children) {
                if (c.lid !== treeNodes[0].lid) {
                    zTree.moveNode(treeNodes[0], c, 'inner');
                }
            }
        }
    }
}
// 查询方法
function findNode (key, value, arr) {
    for (const a of arr) {
        if (a[key] && a[key] === value) {
            return a;
        }
    }
}
function getPId(level) {
    if (level !== 1) {
        const p = findNode('level', level - 1, levelNodes);
        if (p) {
            return p.lid
        } else {
            return 1;
        }
    } else {
        return 2;
    }
}
// 分类数据排序
function sortCategory() {
    category.sort(function (a, b) {
        return a.level ? (b.level ? a.level - b.level : -1) : a.id - b.id;
    });
}
// 初始化分类树结构数据
function initCategoryLevelNode() {
    levelNodes.splice(0, levelNodes.length);
    levelNodes.push(
        { lid:1, lpId:0, name:"可用类别", open:true, isParent: true},
        { lid:2, lpId:0, name:"已用类别", open:true, isParent: true}
    );
    for (const c of category) {
        const cate = JSON.parse(JSON.stringify(c));
        cate.lid = levelNodes.length + 1;
        cate.open = true;
        if (!cate.level) {
            cate.lpId = 1;
            levelNodes.push(cate);
        } else {
            cate.lpId = getPId(cate.level);
            levelNodes.push(cate);
        }
    }
}
// 新建标段 -- 分类属性选择
function getCategoryHtml() {
    function getSelectCategoryHtml (cate) {
        const html = [];
        html.push('');
        html.push('', cate.name, ' ');
        html.push('');
        html.push('不选 ');
        for (const v of cate.value) {
            html.push('', v.value, ' ');
        }
        html.push(' ');
        html.push('
');
        return html.join('');
    }
    function getRadioCategoryHtml (cate) {
        const html = [];
        html.push('');
        return html.join('');
    }
    const html = [];
    for (const c of category) {
        // if (c.type === categoryType.key.dropDown) {
            html.push(getSelectCategoryHtml(c));
        // } else if (c.type === categoryType.key.radio) {
            // html.push(getRadioCategoryHtml(c));
        // }
    }
    return html.join('');
}
// 初始化TenderTree数据
function initTenderTree () {
    const levelCategory = category.filter(function (c) {
        return c.level && c.level > 0;
    });
    function findCategoryNode(cid, value, array) {
        for (const a of array) {
            if (a.cid === cid && a.vid === value) {
                return a;
            }
        }
    }
    function getCategoryNode(category, value, parent, i = null) {
        const array = parent ?  parent.children : tenderTree;
        let cate = findCategoryNode(category.id, value, array);
        if (!cate) {
            const cateValue = findNode('id', value, category.value);
            if (!cateValue) return null;
            cate = {
                cid: category.id,
                vid: value,
                name: cateValue.value,
                children: [],
                level: i ? i : category.level,
                sort_id: ++parentId,
            };
            array.push(cate);
        }
        return cate;
    }
    function loadTenderCategory (tender) {
        let tenderCategory = null;
        for (const [index,lc] of levelCategory.entries()) {
            const tenderCate = findNode('cid', lc.id, tender.category);
            if (tenderCate) {
                tenderCategory = getCategoryNode(lc, tenderCate.value, tenderCategory);
            } else {
                if (index === 0 && tender.category) {
                    for (const [i,c] of tender.category.entries()) {
                        const cate = findNode('id', c.cid, category);
                        tenderCategory = getCategoryNode(cate, c.value, tenderCategory, i+1);
                    }
                }
                return tenderCategory;
            }
        }
        return tenderCategory;
    }
    function calculateTender(tender) {
        if (tender.lastStage) {
            tender.gather_tp = ZhCalc.add(tender.lastStage.contract_tp, tender.lastStage.qc_tp);
            tender.end_contract_tp = ZhCalc.add(tender.lastStage.pre_contract_tp, tender.lastStage.contract_tp);
            tender.end_qc_tp = ZhCalc.add(tender.lastStage.pre_qc_tp, tender.lastStage.qc_tp);
            tender.end_gather_tp = ZhCalc.add(tender.end_contract_tp, tender.end_qc_tp);
            tender.pre_gather_tp = ZhCalc.add(tender.lastStage.pre_contract_tp, tender.lastStage.pre_qc_tp);
            tender.yf_tp = ZhCalc.add(tender.lastStage.yf_tp);
            tender.end_yf_tp = ZhCalc.add(tender.lastStage.pre_yf_tp, tender.yf_tp);
        }
    }
    tenderTree.splice(0, tenderTree.length);
    for (const t of tenders) {
        calculateTender(t);
        t.valid = true;
        delete t.level;
        if (t.category && levelCategory.length > 0) {
            const parent = loadTenderCategory(t);
            if (parent) {
                t.level = parent.level + 1;
                parent.children.push(t);
            } else {
                tenderTree.push(t);
            }
        } else {
            tenderTree.push(t);
        }
    }
}
function recursiveGetTenderNodeHtml (node, arr, pid) {
    const html = [];
    html.push('');
    // 名称
    html.push('');
    if (node.cid) {
        html.push('    ', node.name);
    } else {
        html.push('');
        html.push(arr.indexOf(node) === arr.length - 1 ? '└' : '├');
        html.push(' ');
        //html.push('', node[c.field], ' ');
        html.push('', node.name, ' ');
    }
    html.push(' ');
    // 创建人
    html.push('', node.user_name ? node.user_name : '', ' ');
    // 创建时间
    html.push('', node.create_time ? moment(node.create_time).format('YYYY-MM-DD HH:mm:ss') : '', ' ');
    // 计量模式
    // html.push('');
    // if (node.measure_type) {
    //     html.push(node.measure_type === measureType.tz.value ? '0号台账' : '工程量清单');
    // }
    // html.push(' ');
    // 计量期数
    html.push('');
    if (!node.cid) {
        html.push(node.lastStage ? '第' + node.lastStage.order + '期' : '台账');
    }
    html.push(' ');
    // 审批状态
    html.push('');
    html.push(node.lastStage ? auditConst.stage.statusString[node.lastStage.status] : auditConst.ledger.statusString[node.ledger_status]);
    html.push(' ');
    html.push(' ');
    if (node.children) {
        for (const c of node.children) {
            html.push(recursiveGetTenderNodeHtml(c, node.children, node.sort_id));
        }
    }
    return html.join('');
}
// 根据TenderTree数据获取Html代码
function getTenderTreeHtml () {
    if (tenderTree.length > 0) {
        const html = [];
        html.push('');
        html.push('', '');
        html.push('', '标段名称', ' ');
        html.push('', '创建人', ' ');
        html.push('', '创建时间', ' ');
        html.push('', '计量期数', ' ');
        html.push('', '审批状态', ' ');
        html.push(' ', ' ');
        for (const t of tenderTree) {
            html.push(recursiveGetTenderNodeHtml(t, tenderTree, ''));
        }
        html.push('
');
        return html.join('');
    } else {
        return EmptyTenderHtml.join('');
    }
}
function bindTenderUrl() {
    $('a', '.c-body').bind('click', function () {
        const tenderId = parseInt($(this).attr('id'));
        const tender = _.find(tenders, function (t) {
            return t.id === tenderId;
        });
        if (tender.measure_type) {
            window.location.href = '/tender/' + tenderId;
        } else {
            for (const a of $('a', '#jlms')) {
                a.href = '/tender/' + tenderId + '/type?type=' + $(a).attr('mst');
            }
            $('#jlms').modal('show');
        }
    });
}
$(document).ready(() => {
    autoFlashHeight();
    sortCategory();
    // 初始化分类数据
    initCategoryLevelNode();
    $('.modal-body', '#add-bd').append(getCategoryHtml());
    // 初始化标段树结构
    initTenderTree();
    $('.c-body').html(getTenderTreeHtml());
    bindTenderUrl();
    // 分类
    $('#cate-set').on('show.bs.modal', function () {
        createTree();
    });
    $('#set-cate-ok').click(function () {
        const data = [];
        const zTree = $.fn.zTree.getZTreeObj('treeLevel');
        for (const c of category) {
            const node = zTree.getNodeByParam('id', c.id);
            const parent = node.getParentNode();
            if (parent.lid === 1) {
                data.push({id: c.id, level: 0});
            } else {
                data.push({id: c.id, level: node.getPath().length - 1});
            }
        }
        postData('/setting/category/level', data, function (rst) {
            for (const d of data) {
                const c = findNode('id', d.id, category);
                c.level = d.level;
            }
            sortCategory();
            initCategoryLevelNode();
            initTenderTree();
            $('.c-body').html(getTenderTreeHtml());
            $('#cate-set').modal('hide');
        });
    });
    // 新增标段
    $('#add-bd-ok').click(function () {
        const data = {
            name: $('[name=name]', '#add-bd').val(),
            valuation: $('[name=valuation]:checked').val(),
            category: [],
        };
        if (!data.name || data.name === '') {
            // TODO 提示用户
            return;
        }
        for (const c of category) {
            if (parseInt($('select', '[cate-id=' + c.id + ']').val()) !== 0) {
                const cate = {cid: c.id};
                // if (c.type === categoryType.key.dropDown) {
                cate.value = parseInt($('select', '[cate-id=' + c.id + ']').val());
                // } else if (c.type === categoryType.key.radio) {
                //     cate.value = parseInt($('input:checked', '[cate-id=' + c.id + ']').val());
                // }
                data.category.push(cate);
            }
        }
        $('#hide-all').show();
        postData('/list/add', data, function (result) {
            tenders.push(result);
            initTenderTree();
            $('.c-body').html(getTenderTreeHtml());
            bindTenderUrl();
            $('#add-bd').modal('hide');
            $('[name=name]', '#add-bd').val('');
            $('#hide-all').hide();
        });
    });
    // 展开和收起
    $('body').on('click', '.fold-switch', function () {
        if ($(this).children('i').hasClass('fa-minus-square-o')) {
            $(this).children('i').removeClass('fa-minus-square-o').addClass('fa-plus-square-o');
            $(this).attr('title', '展开');
            const cid = $(this).attr('cid');
            const node = findTenderTreeNode(parseInt(cid), tenderTree);
            doTrStatus(returnItem, 'hide');
        } else {
            $(this).children('i').removeClass('fa-plus-square-o').addClass('fa-minus-square-o');
            $(this).attr('title', '收起');
            const cid = $(this).attr('cid');
            const node = findTenderTreeNode(parseInt(cid), tenderTree);
            doTrStatus(returnItem, 'show');
        }
    })
});
function doTrStatus(node, status) {
    if (status === 'show') {
        $('.c-body').find('tr[pid="'+ node.sort_id +'"]').show();
        $('.c-body').find('tr[pid="'+ node.sort_id +'"] .fold-switch').attr('title', '收起');
        $('.c-body').find('tr[pid="'+ node.sort_id +'"] .fold-switch i').removeClass('fa-plus-square-o').removeClass('fa-minus-square-o').addClass('fa-minus-square-o');
    } else {
        $('.c-body').find('tr[pid="'+ node.sort_id +'"]').hide();
        $('.c-body').find('tr[pid="'+ node.sort_id +'"] .fold-switch').attr('title', '展开');
        $('.c-body').find('tr[pid="'+ node.sort_id +'"] .fold-switch i').removeClass('fa-minus-square-o').removeClass('fa-plus-square-o').addClass('fa-plus-square-o');
    }
    // 判断是否还有一层
    if (node.children) {
        for (const c of node.children) {
            doTrStatus(c, status);
        }
    }
}
let returnItem;
const findTenderTreeNode = function(sortId, tree) {
    tree.forEach((item) => {
        if (item.sort_id !== undefined && item.sort_id === sortId) {
            returnItem = item;
            return item;
        } else if (item.children && item.children.length > 0) {
            findTenderTreeNode(sortId, item.children);
        }
    });
}