layui.config({
    base: '../../js/layuiModules/',   // 第三方模块所在目录
    version: 'v1.6.4' // 插件版本号
}).extend({
    soulTable: 'notice,layNotify',	// 模块
});
let form;
var tree;
var table;
var notice;
var layNotify;
let pers = checkPermission();
$("#addBt").click(function(){
    //layerOpenForm("新增","./untiTeamOpen.html");
    var index = layer.open({
        type: 2,
        title: '新增',
        content: 'subTeamOpen.html',
        area: ['90%', '95%'],
        maxmin: false,
        closeBtn: true,
        btn: ['确定', '取消'],
        yes: function(index, layero){
            var formSubmit = layer.getChildFrame('form', index);
            var submited = formSubmit.find('button')[0];
            submited.click();
            return false;
        },
        btn2: function(index, layero){
            // 用户点击了取消按钮
            layer.close(index);
            return false;
        },
        end: function(){
            query();
        }
    });
});

layui.use(['table', 'form','notice', 'layNotify'], function () {
    table = layui.table;
    form = layui.form;
    tree = layui.tree;
    notice = layui.notice;
    layNotify = layui.layNotify;
    if ($.inArray('sysSubTeamSet:add', pers) < 0) {
        document.getElementById('addDiv').remove();
    }
    getTowerType(form, "");
    $("#searchBt").click(function(){
        query();
    });
    $("#resetBt").click(function(){
        table.reload('menuTable', {
            url: ctxPath + '/teamSet/getTeamSetByType'
            , method: 'post' //方式默认是get
            , page: true
            , where: {
                resourceType:'1'
            } //设定异步数据接口的额外参数
        });
        $("#keyWord").val("");
        getTowerType(form, "");
    })
    //渲染表格
    table.render({
        elem: '#demo'
        , url: ctxPath + '/teamSet/getTeamSetByType' //数据接口

        , method: 'post' //方式默认是get
        , toolbar: 'default' //开启工具栏，此处显示默认图标，可以自定义模板，详见文档
        , where: {'resourceType':'1'} //post请求必须加where ，post请求需要的参数
        , cellMinWidth: 80
        , cols: [[ //表头
            {
                field: 'number', width:80,title: '序号', align: 'center', type: 'numbers'
            }
            , {field: 'resourceName', align: 'center', title: '标准班组名称'}
            , {field: 'groupType', align: 'center', title: '团队类型'}
            , {field: 'managePersonName', align: 'center', title: '团队配置'}
            , {field: 'isEnable', width: 200, align: 'center', title: '状态', id:'statusSwitch', templet: '#switchTpl'}
            , {
                fixed: 'right', width:180, title: '操作', align: 'center', templet: d => {
                    let text = "";
                    if ($.inArray('sysSubTeamSet:update', pers) > 0) {
                        text +='<a lay-event="update" style="color: #009688;cursor: pointer;font-size: 15px"  id="updateBtn">修改</a>';
                        text +='<span lay-event="com" style="font-size: 15px;"> | </span>';
                    }
                    if ($.inArray('sysSubTeamSet:del', pers) >= 0) {
                        text +='<a lay-event="del" style="color: #009688;cursor: pointer;font-size: 15px">删除</a>';
                    }
                    return text;
                }
            }
        ]]
        , id: 'menuTable'
        , page: true //开启分页
        , loading: true //数据加载中。。。
        , limits: [5, 10, 20]  //一页选择显示3,5或10条数据
        , limit: 10  //一页显示5条数据
        , response: {
            statusCode: 200 //规定成功的状态码，默认：0
        }, parseData: function (res) { //将原始数据解析成 table 组件所规定的数据，res为从url中get到的数据
            let result;
            if (res.data !== '' && res.data != null && res.data !== "null") {
                if (this.page.curr) {
                    result = res.data.slice(this.limit * (this.page.curr - 1), this.limit * this.page.curr);
                } else {
                    result = res.data.slice(0, this.limit);
                }
            }
            return {
                "code": res.code, //解析接口状态
                "msg": res.msg, //解析提示文本
                "count": res.count, //解析数据长度
                "data": result, //解析数据列表
            };
        },
        toolbar: "#toolbar"
    });
    form.on('switch(statusSwitch)', function(data){
        var isChecked = data.elem.checked; // 获取复选框的当前状态
        var value = data.value; // 获取复选框的值
        let status = isChecked ? 1 : 0;
        // alert("value="+value+" ,status="+status);
        // 发送请求到后端更新数据库中的状态字段
        $.ajax({
            url: ctxPath + '/teamSet/updateTeamSetStatus',
            type: 'POST',
            data: { resourceSetId: value, isEnable: status },
            success: function(res) {
                layer.msg('状态更新成功');
            },
            error: function() {
                layer.msg('更新状态失败');
            }
        });
    });
    //监听工具条
    table.on('tool(test)', function (obj) {
        var data = obj.data; //当前行数据
        var rowIndex = obj.index;
        var layEvent = obj.event; //当前点击的事件名
        var resourceSetId = data.resourceSetId;
        var resourceName = data.resourceName;
        var teamType = data.groupTypeId;
        var resourceNotes = data.resourceNotes

        localStorage.setItem("subResourceSetId",resourceSetId);
        localStorage.setItem("subTeamType",teamType);
        localStorage.setItem("subResourceNotes",resourceNotes);
        localStorage.setItem("subResourceName",resourceName);

        if (layEvent === 'update') {
            var index = layer.open({
                type: 2,
                title: '修改',
                content: './subTeamModify.html',
                area: ['90%', '95%'],
                maxmin: false,
                closeBtn: true,
                btn: ['确定', '取消'],
                yes: function(index, layero){
                    var formSubmit = layer.getChildFrame('form', index);
                    var submited = formSubmit.find('button')[0];
                    submited.click();
                    return false;
                },
                btn2: function(index, layero){
                    localStorage.removeItem("subResourceSetId");
                    localStorage.removeItem("subTeamType");
                    localStorage.removeItem("subResourceNotes");
                    localStorage.removeItem("subResourceName");

                    // 用户点击了取消按钮
                    layer.close(index);
                    return false;
                },
                end: function(){
                    localStorage.removeItem("subResourceSetId");
                    localStorage.removeItem("subTeamType");
                    localStorage.removeItem("subResourceNotes");
                    localStorage.removeItem("subResourceName");
                    query();
                }
            });
            //layerOpenForm("修改","./proManageTeamForm.html");
        }
        if (layEvent === 'del') {
            layer.confirm('确定要删除吗？', {
                btn : [ '确定', '取消' ]
            }, function() {
                $.ajax({
                    type: 'POST',
                    async: false, // 默认异步true,false表示同步
                    url: ctxPath + '/teamSet/delTeamSet',// 请求地址
                    contentType: "application/x-www-form-urlencoded",
                    dataType: 'json', // 服务器返回数据类型
                    data: {'resourceSetId': resourceSetId,'deleteType':'2'}, //获取提交的表单字段
                    success: function (data) {
                        var resMsg = data.resMsg;
                        if ("数据获取成功" == resMsg) {
                            reloadTip("删除","删除成功",'success',layNotify);
                            setTimeout(function(){
                                layer.closeAll();
                                query();
                            }, 2000);
                        }else if("已在使用" ==resMsg ){
                            reloadTip("删除","不可删除,已有分公司团推使用此设置",'error',layNotify);
                            layer.closeAll();
                        }else {
                            reloadTip("删除","删除失败",'error',layNotify);
                            setTimeout(function(){
                                layer.closeAll();
                            }, 2000);
                        }
                    }
                });
            });
        }
    });

// 单元格编辑事件
    table.on('edit(test)', function (obj) {
        var field = obj.field; // 得到字段
        var value = obj.value; // 得到修改后的值
        var oldValue = obj.oldValue;
        var data = obj.data; // 得到所在行所有键值
        var update = {};

        //layer.msg('编辑成功', {icon: 1});
    });
});


function query(){
    let keyWord = $("#keyWord").val();
    let teamType = $("#teamType").find("option:selected").val();//获取选中文本
    table.reload('menuTable', {
        url: ctxPath + '/teamSet/getTeamSetByType'
        , method: 'post' //方式默认是get
        , page: true
        , where: {
            resourceType:'1',
            keyWord: keyWord,
            groupType: teamType,
        } //设定异步数据接口的额外参数
    });
}