let layer, treeTable, tableIns, table;
const token = localStorage.getItem("token");


layui.use(['layer', 'treeTable', 'table'], function () {
    layer = layui.layer;
    treeTable = layui.treeTable;
    table = layui.table;
    initTreeTable()
    var roleName = localStorage.getItem("roleName");
    table.on('tool(test)', function (obj) {
        var data = obj.data; //当前行数据
        var rowIndex = obj.index;
        var layEvent = obj.event; //当前点击的事件名
        if (layEvent === 'add') {
            if (Number(data.level) === 1) { // 新增事业部/职能部门
                if(roleName == "项目经理"){
                    layer.msg("您没有权限新增事业部/职能部门", {icon: 2});
                    return;
                }
                addForm(4, data);
            }
            if (Number(data.level) === 2) { // 新增项目
                if(roleName == "项目经理"){
                    layer.msg("您没有权限新增项目", {icon: 2});
                    return;
                }
                addForm(0, data);
            }
            if (Number(data.level) === 3) { // 新增外包商
                if(roleName == "项目经理"){
                    layer.msg("您没有权限新增外包商", {icon: 2});
                    return;
                }
                addForm(1, data);
            }
            if (Number(data.level) === 4) { // 新增班组
                addForm(2, data);
            }
        }
        if (layEvent === 'changeTheTeamLeader') {
            addForm(3, data);
        }
        if (layEvent === 'backField') {
            back(2, data)
        }
    });
});

// 搜索/重置
function searchTable(type) {
    if (type === 1) {

    } else if (type === 2) {
        $('#keyWord').val('')
    }
    treeTable.reload('ID-treeTable-demo', {})
}

function reloadTreeTable() {
    treeTable.reload('ID-treeTable-demo', {});
}

// 初始化树表格
function initTreeTable() {
    let loginUser = localStorage.getItem("loginUser");
    let user = JSON.parse(loginUser);
    tableIns = treeTable.render({
        elem: '#ID-treeTable-demo',
        id: 'ID-treeTable-demo',
        url: `${ctxPath}/organizational/getTreeList`,
        type: 'GET',
        tree: {
            enable: true,
            view: {expandAllDefault: true},
            async: {}
        },
        parseData: function (res) {
            let list = res.obj;
            let newList = filterTree($('#keyWord').val(), list);
            return {
                "code": 0,
                "msg": '获取成功',
                "data": newList
            };
        },
        height: 'full-200px',
        search: true,
        cols: [[
            {field: 'name', title: '名称', width: '40%', unresize: true, align: "left"},
            {
                field: 'level', title: '属性', width: '19.9%', unresize: true, align: "center",
                templet: function (d) {
                    switch (d.level) {
                        case 1:
                            return '总公司';
                        case 2:
                            return Number(d.orgType) === 1 ? '事业部' : '职能部门';
                        case 3:
                            return '项目';
                        case 4:
                            return '外包商';
                        case 5:
                            return '班组';
                        default:
                            return '';
                    }
                }
            },
            {
                field: 'userName', title: '负责人', width: '20%', unresize: true, align: "center",
                templet: function (d) {
                    return d.userName || '/';
                }
            },
            {
                fixed: 'right', width: '20%', title: '操作', align: 'center', templet: d => {
                    let html = "";

                    if ([1, 2, 3, 4].includes(d.level)) {
                        if(user.roleId == 6 || user.roleId == 5){
                            html += '<a lay-event="add" style="color: #009688;cursor: pointer;font-size: 15px" id="add">新增</a>';
                        }
                        if(user.roleId == 7 && d.level == 4 &&(d.userName == user.nickname ||  d.parentUserName==user.nickname)   ){
                            html += '<a lay-event="add" style="color: #009688;cursor: pointer;font-size: 15px" id="add">新增</a>';
                        }
                        if(user.roleId == 7 && d.level == 3 && d.userName == user.nickname){
                            html += '<a lay-event="add" style="color: #009688;cursor: pointer;font-size: 15px" id="add">新增</a>';
                        }




                    }
                    if (d.level === 5) {
                        if(user.roleId == 6 || user.roleId == 5){
                            html += '<a lay-event="changeTheTeamLeader" style="color: #009688;cursor: pointer;font-size: 15px" id="changeTheTeamLeader">更换班长</a>';
                        }
                        if (user.roleId == 7 && d.userName == user.nickname) {
                            html += '<a lay-event="changeTheTeamLeader" style="color: #009688;cursor: pointer;font-size: 15px" id="changeTheTeamLeader">更换班长</a>';
                        }
                        let tableData = treeTable.getData('ID-treeTable-demo');
                        let parentNode = getParentNode(d, tableData);
                        parentNode = getParentNode(parentNode, tableData);
                        if (parentNode && parentNode.userName === user.nickname) {
                            if(user.roleId == 7){
                                html += '<a lay-event="backField" style="color: #009688;cursor: pointer;font-size: 15px;margin-left: 10px" id="backField">退场</a>';
                            }
                        }
                    }
                    return html;
                }
            },
        ]],
        page: false,
    });
}

function getParentNode(node, data) {
    for (let i = 0; i < data.length; i++) {
        if (node.parentId === data[i].id) {
            return data[i];
        } else {
            if (data[i].children && data[i].children.length) {
                let parentNode = getParentNode(node, data[i].children);
                if (parentNode) {
                    return parentNode;
                }
            }
        }
    }
    return undefined; // Explicitly return undefined if no parent node is found
}

// 新增项目/新增外包商/更换班长
let titleArr = ['新增项目', '新增外包商', "新增班组", '更换班长', '新增事业部/职能部门'];

function addForm(type, obj) {
    let area = ['50%', '70%'];
    if (type === 0) {
        area = ['70%', '80%'];
    } else if (type === 1) {
        area = ['50%', '50%'];
    } else if (type === 2){
        area = ['98%', '98%'];
    }else if (type === 3) {
        area = ['98%', '98%'];
    } else if (type === 4) {
        area = ['50%', '50%'];
    }
    obj.type = type;
    let layerIndex = layer.open({
        type: 2,
        title: titleArr[type],
        shade: [0],
        area: area,
        scrollbar: true,
        move: false,
        anim: 2,
        yes: function (index, layero) {
        },
        content: './addForm.html',
        success: function (layero, index) {
            let iframeWin = window["layui-layer-iframe" + layerIndex];
            iframeWin.setParams(JSON.stringify(obj));
        },
    });
}

// 退场 1.外包商退场 2.班组退场
function back(type, obj) {
    let layerIndex = layer.confirm('<h5>确定退场吗！</h5>', {title: '操作提示', move: false}, function () {
        layer.close(layerIndex);
        backAjax(obj);
    });
}

function backAjax(obj) {
    let loadingMsg = layer.msg('正在提交保存,请稍等...', {icon: 16, shade: 0.01, time: '0'});
    $.ajax({
        url: `${ctxPath}` + '/organizational/userOutData',
        type: 'POST',
        data: {
            id: obj.id
        },
        dataType: 'json',
        success: function (result) {
            layer.close(loadingMsg); // 关闭提示层
            console.error(result)
            if (result.res === 1) {
                openEvaluatePage(result.obj)
            } else {
                layer.msg(result.resMsg, {icon: 2});
            }
        },
        error: function (result) {
            layer.close(loadingMsg); // 关闭提示层
            layer.msg('服务异常，请稍后重试', {icon: 16, scrollbar: false, time: 2000});
        }
    });
}

function openEvaluatePage(obj) {
    let title = '评价',
        content = '../../evaluate/team/evaluateTable.html';
    obj.type = 1;
    obj.operType = 'back';
    let layerIndex = layer.open({
        type: 2,
        title: title,
        shade: 0,
        area: ['80%', '90%'],
        scrollbar: true,
        move: false,
        anim: 2,
        yes: function (index, layero) {
        },
        content: content,
        success: function (layero, index) {
            let iframeWin = window["layui-layer-iframe" + layerIndex];
            iframeWin.setParams(JSON.stringify(obj));
        },
        end: function () {
            console.log("end")
        },
        cancel: function () {
            $.ajax({
                url: `${ctxPath}` + '/organizational/userOutDataFail',
                type: 'POST',
                data: {
                    id: obj.id
                },
                dataType: 'json',
                success: function (result) {
                    if (result.res === 1) {
                        layer.msg(result.obj, {icon: 2});
                        reloadTreeTable();
                    } else {
                        layer.msg(result.resMsg, {icon: 2});
                    }
                },
                error: function (result) {
                    layer.msg('服务异常，请稍后重试', {icon: 16, scrollbar: false, time: 2000});
                }
            });
        }
    });
}

function filterTree(val, tree, newArr = []) {
    if (!(tree.length && val)) {  // 如果搜索关键字为空直接返回源数据
        return tree
    }
    for (let item of tree) {
        if (item.name.indexOf(val) > -1) { // 匹配到关键字的逻辑
            newArr.push(item)  // 如果匹配到就在数值中添加记录
            continue  // 匹配到了就退出循环了此时如果有子集也会一并带着
        }

        if (item.children && item.children.length) { // 如果父级节点没有匹配到就看看是否有子集，然后做递归
            let subArr = filterTree(val, item.children) // 缓存递归后的子集数组
            if (subArr && subArr.length) {  // 如果子集数据有匹配到的节点
                let node = {...item, children: subArr}  // 关键逻辑，缓存父节点同时将递归后的子节点作为新值
                newArr.push(node)  // 添加进数组
            }
        }
    }
    return newArr
}
