
layui.config({
    base: '../../lib/layui/lay/mymodules/'
    ,version: '101100'
}).use('eleTree');
layui.extend({
    admin: '{/}../../static/js/admin'
});
layui.use(['jquery','eleTree','table','laypage','admin'], function(){
    var $= layui.jquery,
        eleTree	= layui.eleTree,
        laypage	= layui.laypage,
        table	= layui.table;
    var addStateHtml = '../../pages/admin/addstate.html';
    var updateHtml = '../../pages/admin/updateState.html';
    // 部门
    var belpID = 'root';
    delpFun();
    sessionStorage.setItem("ztreeDepid",'root');
    function delpFun(){
        $.ajax({
            url:'http://apptest.jieweizhineng.com/api/section/getlist',
            method:'get',
            dataType: 'json',
            data: {

            },
            success:function (res) {
                if(res.code === 0){
                    var data = [res.data];
                    eleTree.render({
                        elem: '.ele1',
                        data:data ,
                        defaultExpandAll:true,
                        // showCheckbox: true,
                    });
                    eleTree.on("nodeClick(data)",function(d) {
                        belpID =  d.data.currentData.id;
                        sessionStorage.setItem("ztreeDepid",d.data.currentData.id);
                        $('.stetaName').val("");
                        var info={
                            statusContent: '',
                            departmentId: d.data.currentData.id,
                            deleteStatus: 'false',
                            pageNumber: '1',
                            pageSize: '1',
                        };
                        getStateList(info);
                    })
                }else{
                    layer.msg('请检查网路', {icon: 2});
                }
            },
            error:function (err) {
                layer.msg('请检查网路', {icon: 2});
            }
        })

    }
    var info={
        statusContent: $('.stetaName').val(),
        departmentId: belpID,
        deleteStatus: 'false',
        pageNumber: '1',
        pageSize: '1',
    };
    getStateList(info);
    function getStateList(res) {
        $.ajax({
            url: 'http://apptest.jieweizhineng.com/api/swagger/api/status/v1/getStatusList',
            method: 'get',
            dataType: 'json',
            data: res,
            success: function (data) {
                laypage.render({
                    elem: 'pageItem',
                    count: data.count,
                    limit: 10,
                    layout: ['count', 'prev', 'page', 'next', 'skip'],
                    jump: function(obj, first) {
                        var index = layer.load(2);
                        table.render({
                            elem: '#stateRemind',
                            url: 'http://apptest.jieweizhineng.com/api/swagger/api/status/v1/getStatusList',
                            id: 'idstetaTable',
                            method: 'get',
                            loading: true,
                            cols: [[
                                {field: 'statusContent', title: '状态名称', align: 'center'}
                                , {field: 'createDate', title: '创建日期', align: 'center'}
                                , {title: ' 操作', align: 'center', toolbar: '#barDemo'}
                            ]],
                            where: {
                                statusContent: res.statusContent,
                                departmentId: res.departmentId,
                                deleteStatus: res.deleteStatus,
                                pageNumber: obj.curr,
                                pageSize: obj.limit,
                            },

                            response: {
                                statusName: 'code'
                                , statusCode: 200,
                                countName: 'count',
                                dataName: 'data'
                            },
                            done: function (res, curr, count) {
                                layer.close(index);
                                if (res.code === '200') {
                                    $('.fr').html('共有数据：'+res.count+' 条')
                                }
                            }
                        });
                    }
                })
            }
        });
    }
    // 查询
    $(".seachSteta").click(function () {
        var checkbox = $("#checkboxT").prop('checked'),
            root='',
            info;
        if(checkbox == true){
            root = '';
            info={
                statusContent: $('.stetaName').val(),
                departmentId: root,
                deleteStatus: 'false',
                pageNumber: '1',
                pageSize: '1',
            };
        }else {
            info={
                statusContent: $('.stetaName').val(),
                departmentId: belpID,
                deleteStatus: 'false',
                pageNumber: '1',
                pageSize: '1',
            };
        }

        getStateList(info)
    });
    // 监听状态table
    table.on('tool(stateItme)', function(obj) {
        if( obj.event === "move"){
            sessionStorage.setItem("statusId",obj.data.id);
            moveDep('选择部门信息','http://apptest.jieweizhineng.com/api/swagger/api/status/v1/moveStatus/','400','500',table,'idstetaTable');
        } else if (obj.event === "copy"){
            var content ={
                _method:'put'
            };
            layer.alert('确认要复制记录模板吗？',{icon: 8}, function(index){
                $.ajax({
                    url: 'http://apptest.jieweizhineng.com/api/swagger/api/status/v1/copyStatus/'+obj.data.id,
                    method: 'post',
                    dataType: 'json',
                    data: content,
                    success: function (res) {
                        if (res.code === '200'){
                            layer.msg('复制成功', {icon: 1});
                            table.reload('idstetaTable');
                        } else{
                            layer.msg('复制失败', {icon: 2});
                            table.reload('idstetaTable');
                        }
                        layer.close(index);
                    },
                    error:function () {
                        layer.msg('请检查网络', {icon: 2});
                        layer.close(index);
                    }
                });
            });
        } else if (obj.event === "edit"){
            var objID =obj.data;
            var delobj=[];
            layer.open({
                type: 2,
                id: 'updateState',
                title:'修改状态和提醒设置',
                shadeClose: true,
                scrollbar:true,
                shade: 0.3,
                maxmin: true,
                skin: 'oaBtn',
                btn: ['确认', '取消'],
                area: ['500px', '500px'],
                content: updateHtml,
                success: function (layero, index) {
                    var body = layer.getChildFrame('body', index);
                    body.find('#stetaName').val(obj.data.statusContent);
                    $.ajax({
                        url: 'http://apptest.jieweizhineng.com/api/swagger/api/status/v1/getStatusItemList/'+obj.data.id,
                        method: 'get',
                        dataType: 'json',
                        success: function (res) {
                            for (var i=0;i<res.data.length;i++){
                                var str =`
                                        <div class="a_itme" id-data="${res.data[i].id}" delete-flay="true">
                                            <div class="a_colour">
                                           <span color_data="${res.data[i].statusColor}" style="background: ${res.data[i].statusColor}"></span>
                                            </div>
                                            <div class="a_modle">
                                                <i class="pointedSpan"></i>
                                                <b class="a_continue">继续</b>
                                                <b class="a_complete">完成</b>
                                                <span></span>
                                                <span></span>
                                            </div>
                                            <div class="a_delete">
                                                <i class="layui-icon layui-icon-delete"></i>
                                            </div>
                                      <input type="text" value="${res.data[i].statusContent}" placeholder="请输入状态名称" name="username" required="" lay-verify="required" autocomplete="off" class="layui-input a_steta ${i == 0?"a_steta1":""}">
                                  </div>`;
                                body.find(".a_itmes").append(str)
                            }
                        },
                        error:function () {
                            layer.msg('请检查网络', {icon: 2});
                        }
                    });
                    body.delegate('.a_delete','click',function () {
                        if (body.find(".a_itmes .a_itme").length === 1) {
                            return;
                        }else {
                            var id = $(this).parent().attr("id-data"),
                                deleteFlay = $(this).parent().attr("delete-flay");
                            var sonterm = {deleteFlag:deleteFlay,id:id,statusColor:'',statusContent:'',zIndex:''};
                            delobj.push(sonterm)
                        }

                    })
                },
                yes: function (index, layero) {
                    var body = layer.getChildFrame('body', index);
                    var reg = /\S/;
                    if (!reg.test(body.find("#stetaName").val())) {
                        layer.msg('请输入状态组名称', {icon: 8});
                        return false;
                    }
                    if (!reg.test(body.find(".a_steta1").val())) {
                        layer.msg('请输入状态组子项至少填一个', {icon: 8});
                        return false;
                    }
                    var item = body.find('.a_itmes .a_itme');
                    var a_colour = body.find('.a_colour');
                    var arr = [];
                    var ID = [];
                    var json =[];
                    var color =[];
                    var obj = {deleteFlag:'false',id:'',statusColor:'',statusContent:'',zIndex:''};
                    a_colour.each(function () {
                        var value = $(this).find('span').attr("color_data");
                        color.push(value);
                    });
                    item.each(function () {
                        var value = $(this).find('input').val();
                        var ids = $(this).attr("id-data");
                        if (reg.test(value)) {
                            arr.push(value);
                            ID.push(ids)
                        }
                    });
                    if (arr == "") {
                        layer.msg('请输入状态组子项至少填一个', {icon: 8});
                        return false;
                    }else {
                        for (var i = 0; i < arr.length; i++) {
                            obj = {};
                            obj.deleteFlag = false;
                            obj.id = ID[i];
                            obj.statusColor = color[i];
                            obj.statusContent = arr[i];
                            obj.zIndex = i+1;
                            delobj.push(obj)
                        }
                    }
                    var delobjs= [];
                    for (var k = 0; k < delobj.length; k++) {
                        if (delobj[k].id != undefined || delobj[k].statusContent != "") {
                            delobjs.push(delobj[k])
                        }
                    }
                    var updateStetaInfo = {
                        id:objID.id,
                        statusContent:body.find('#stetaName').val(),
                        statusItems:delobjs,
                        _method:'put'
                    };
                    $.ajax({
                        url:'http://apptest.jieweizhineng.com/api/swagger/api/status/v1/updateStatus',
                        method:'POST',
                        dataType: 'json',
                        data: updateStetaInfo,
                        success:function (res) {
                            if(res.code === '200'){
                                layer.msg('修改成功', {icon: 1});
                                table.reload('idstetaTable');
                                layer.close(index);
                            }else if (res.code == '422') {
                                layer.msg('状态内容不能为空', {icon: 2});
                                table.reload('idstetaTable');
                                layer.close(index);
                            }else{
                                layer.msg('修改失败,请检查信息', {icon: 2});
                                table.reload('idstetaTable');
                                layer.close(index);
                            }
                        },
                        error:function (err) {
                            layer.close(index);
                        }
                    })
                }
            })
        } else if (obj.event === "delete"){
            var content ={
                _method:'DELETE'
            };
            layer.alert('确认要删除吗？',{icon: 8}, function(index){
                $.ajax({
                    url: 'http://apptest.jieweizhineng.com/api/swagger/api/status/v1/reomveStatus/'+obj.data.id,
                    method: 'post',
                    dataType: 'json',
                    data: content,
                    success: function (res) {
                        if (res.code === '200'){
                            layer.msg('删除成功', {icon: 1});
                            table.reload('idstetaTable');
                        } else{
                            layer.msg('删除失败', {icon: 2});
                            table.reload('idstetaTable');
                        }
                        layer.close(index);
                    },
                    error:function () {
                        layer.msg('请检查网络', {icon: 2});
                        layer.close(index);
                    }
                });
            });
        }
    });
    // 添加状态
    // 打开添加弹窗
    $(".addState").click(function () {
        layer.open({
            type: 2,
            id: 'addState',
            title:'添加状态和提醒设置',
            shadeClose: true,
            scrollbar:true,
            shade: 0.3,
            maxmin: true,
            skin: 'oaBtn',
            btn: ['确认', '取消'],
            area: ['500px', '500px'],
            content: addStateHtml,
            success: function (layero, index) {
                var body = layer.getChildFrame('body', index);
            },
            yes: function (index, layero) {
                var body = layer.getChildFrame('body', index);
                var reg = /\S/;
                if (!reg.test(body.find("#stetaName").val())) {
                    layer.msg('请输入状态组名称', {icon: 8});
                    return false;
                }
                if (!reg.test(body.find(".a_steta1").val())) {

                    return false;
                }
                var item = body.find('.a_itmes .a_itme');
                var a_colour = body.find('.a_colour');
                var json =[];
                var arr = [];
                var color =[];
                var obj = {statusColor:'',statusContent:'',zIndex:''};
                a_colour.each(function () {
                    var value = $(this).find('span').attr("color_data");
                    color.push(value);
                });
                item.each(function () {
                    var value = $(this).find('input').val();
                    if (reg.test(value)) {
                        arr.push(value);
                    }
                });
                if (arr == "") {
                    layer.msg('请输入状态组子项至少填一个', {icon: 8});
                    return false;
                }else {
                    for (var j = 0; j < arr.length; j++) {
                        obj = {};
                        obj.statusColor = color[j];
                        obj.statusContent = arr[j];
                        obj.zIndex = j+1;
                        json.push(obj);
                    }
                }
                var addStetaInfo = {
                    departmentId:belpID,
                    statusContent:body.find('#stetaName').val(),
                    statusItems:json
                };
                $.ajax({
                    url:'http://apptest.jieweizhineng.com/api/swagger/api/status/v1/addStatus',
                    method:'POST',
                    dataType: 'json',
                    data: addStetaInfo,
                    success:function (res) {
                        if(res.code === '200'){
                            layer.msg('添加成功', {icon: 1});
                            table.reload('idstetaTable');
                            layer.close(index);
                        }else if (res.code == '422') {
                            layer.msg('状态内容不能为空', {icon: 2});
                            table.reload('idstetaTable');
                            layer.close(index);
                        } else{
                            layer.msg('添加失败，请检查信息或网络', {icon: 2});
                            table.reload('idstetaTable')
                        }
                    },
                    error:function (err) {
                        layer.msg('网络错误', {icon: 2});
                    }
                })
            }
        })
    })
});