'use strict';

/**
 *
 *
 * @author Mai
 * @date 2019/3/7
 * @version
 */
const EmptyTenderHtml = [
    '<div class="jumbotron">',
    '<h3 class="display-6">还没有标段数据</h3>',
    '</div>'
];
// 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 = [];
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('<div class="form-group" cate-id="' + cate.id + '">');
        html.push('<lable>', cate.name, '</lable>');
        html.push('<select class="form-control">');
        for (const v of cate.value) {
            html.push('<option value="' + v.id + '">', v.value, '</option>');
        }
        html.push('</select>');
        html.push('</div>');
        return html.join('');
    }
    function getRadioCategoryHtml (cate) {
        const html = [];
        html.push('<div class="form-group" cate-id="' + cate.id + '">');
        html.push('<lable>', cate.name, '</lable>');
        html.push('<div>');
        for (const iV in cate.value) {
            const v = cate.value[iV];
            html.push('<div class="form-check-inline">');
            html.push('<input class="form-check-input" type="radio"', 'name="' + cate.name + '" ', 'value="' , v.id, (iV == 0 ? '" checked="' : ''),  '">');
            html.push('<label class="form-check-label">', v.value, '</label>');
            html.push('</div>');
        }
        html.push('</div>');
        html.push('</div>');
        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) {
        const array = parent ?  parent.children : tenderTree;
        let cate = findCategoryNode(category.id, value, array);
        if (!cate) {
            const cateValue = findNode('id', value, category.value);
            cate = {
                cid: category.id,
                vid: value,
                name: cateValue.value,
                children: [],
                level: category.level,
            };
            array.push(cate);
        }
        return cate;
    }
    function loadTenderCategory (tender) {
        let tenderCategory = null;
        for (const lc of levelCategory) {
            const tenderCate = findNode('cid', lc.id, tender.category);
            if (tenderCate) {
                tenderCategory = getCategoryNode(lc, tenderCate.value, tenderCategory);
            } else {
                return tenderCategory;
            }
        }
        return tenderCategory;
    }
    tenderTree.splice(0, tenderTree.length);
    for (const t of tenders) {
        t.valid = true;
        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) {
    const html = [];
    html.push('<tr>');
    // 名称
    html.push('<td class="in-' + node.level + '">');
    if (node.cid) {
        html.push('<i class="fa fa-folder-o"></i> ', node.name);
    } else {
        html.push('<span class="text-muted mr-2">');
        html.push(arr.indexOf(node) === arr.length - 1 ? '└' : '├');
        html.push('</span>');
        html.push('<a href="javascript: void(0)" name="name" id="' + node.id + '">', node.name, '</a>');
    }
    html.push('</td>');
    // 完成期数
    html.push('<td>');
    if (!node.cid) {
        html.push(node.completeStage && node.completeStage > 0 ? '第' + node.completeStage + '期' : '第0期');
    }
    html.push('</td>');
    // 管理
    html.push('<td tid="' + node.id + '">');
    if (!node.cid) {
        html.push('<a href="#javascript: void(0)" name="edit" class="btn btn-outline-primary btn-sm">编辑</a>');
        if (node.ledger_status === auditConst.status.uncheck) {
            html.push('<a href="javascript: void(0)" name="del" class="btn btn-outline-danger btn-sm">删除</a>');
        }
    }
    html.push('</td>');
    html.push('</tr>');
    if (node.children) {
        for (const c of node.children) {
            html.push(recursiveGetTenderNodeHtml(c, node.children));
        }
    }
    return html.join('');
}
function getTenderTreeHeaderHtml() {
    const html = [];
    html.push('<thead>', '<tr>');
    html.push('<th>', '名称', '</th>');
    html.push('<th>', '完成期数', '</th>');
    html.push('<th>', '管理', '</th>');
    html.push('</tr>', '</thead>');
}
// 根据TenderTree数据获取Html代码
function getTenderTreeHtml () {
    if (tenderTree.length > 0) {
        const html = [];
        html.push('<table class="table table-bordered">');
        html.push(getTenderTreeHeaderHtml());
        for (const t of tenderTree) {
            html.push(recursiveGetTenderNodeHtml(t, tenderTree));
        }
        html.push('</table>');
        return html.join('');
    } else {
        return EmptyTenderHtml.join('');
    }
}
function bindTenderUrl() {
    // 打开标段
    $('a[name=name]', '.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');
        }
    });
    // 编辑
    $('a[name=edit]', '.c-body').bind('click', function () {
        const tid = parseInt($(this).parent().attr('tid'));
        const tender = _.find(tenders, {id: tid});
        $('[name=name]', '#edit-bd').val(tender.name);
        for (const c of tender.category) {
            $('input[value=' + c.value + ']', '#edit-bd').attr('checked', 'checked');
            $('option[value=' + c.value + ']', '#edit-bd').attr('selected', true);
        }
        $('#edit-bd-ok').attr('tid', tid);
        $('#edit-bd').modal('show');
    });
    // 删除
    $('a[name=del]', '.c-body').bind('click', function () {
        $('#del-bd-ok').attr('tid', $(this).parent().attr('tid'));
        $('#del-bd').modal('show');
    });
}

$(document).ready(() => {
    sortCategory();
    // 初始化分类数据
    initCategoryLevelNode();
    $('.modal-body', '#add-bd').append(getCategoryHtml());
    $('.modal-body', '#edit-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(),
            category: [],
        };
        if (!data.name || data.name === '') {
            // TODO 提示用户
            return;
        }
        for (const c of category) {
            const cate = {cid: c.id};
            const cateObj = $('[cate-id=' + c.id + ']', '#add-bd');
            if (c.type === categoryType.key.dropDown) {
                cate.value = parseInt($('select', cateObj).val());
            } else if (c.type === categoryType.key.radio) {
                cate.value = parseInt($('input:checked', cateObj).val());
            }
            data.category.push(cate);
        }
        postData('/list/add', data, function (result) {
            tenders.push(result);
            initTenderTree();
            $('.c-body').html(getTenderTreeHtml());
            bindTenderUrl();
            $('#add-bd').modal('hide');
            $('[name=name]', '#add-bd').val('');
        });
    });
    // 编辑标段
    $('#edit-bd-ok').click(function () {
        const data = {
            id: parseInt($(this).attr('tid')),
            name: $('[name=name]', '#edit-bd').val(),
            category: [],
        };
        if (!data.name || data.name === '') {
            // TODO 提示用户
            return;
        }
        for (const c of category) {
            const cate = {cid: c.id};
            const cateObj = $('[cate-id=' + c.id + ']', '#edit-bd');
            if (c.type === categoryType.key.dropDown) {
                cate.value = parseInt($('select', cateObj).val());
            } else if (c.type === categoryType.key.radio) {
                cate.value = parseInt($('input:checked', cateObj).val());
            }
            data.category.push(cate);
        }
        postData('/list/update', data, function (result) {
            const tender = _.find(tenders, {id: result.id});
            _.assign(tender, result);
            initTenderTree();
            $('.c-body').html(getTenderTreeHtml());
            bindTenderUrl();
            $('#edit-bd').modal('hide');
        });
    });
    // 删除标段
    $('#del-bd-ok').click(function () {
        const tid = parseInt($(this).attr('tid'));
        if (tid >= 0) {
            postData('/list/del', [tid], function (result) {
                function getCategory(arr, id) {
                    for (const a of arr) {
                        if (a.cid) {
                            const ac = getCategory(a.children, id);
                            if (ac) {
                                return ac;
                            }
                        } else if (a.id === id) {
                            return arr;
                        }
                    }
                    return null;
                }
                for (const rid of result) {
                    const tr = $('td[tid=' + rid + ']').parent();
                    const arr = getCategory(tenderTree, rid);
                    if (arr) {
                        const a = arr.find(function (x) {
                            return x.id === rid;
                        });
                        console.log(arr.indexOf(a));
                        console.log(arr.length - 1);
                        if (arr.length > 1 && arr.indexOf(a) === arr.length - 1) {
                            const span = $('span', tr.prev());
                            span.text('└');
                        }
                        arr.splice(arr.indexOf(a), 1);
                    }
                    _.remove(tenders, function (n) {
                        return n.id === rid;
                    });
                    tr.remove();
                    $('#del-bd').modal('hide');
                }
            });
        } else {
            $('#del-bd').modal('hide');
        }
    });
});