<div class="layui-fluid">
    <div class="layui-card">
        <div class="layui-card-header">
            <form class="layui-form render">
                <div class="layui-form-item">
                    <div class="layui-inline" style="width:72px;">
                        <select name="fields">
                            <option value="">属性</option>
                            <option value="0">名称</option>
                            <option value="1">标识</option>
                            <option value="2">控制</option>
                        </select>
                    </div>
                    <div class="layui-inline" style="width:120px;"><input type="text" name="kw" placeholder="关键词" autocomplete="off" class="layui-input" lay-affix="clear"/></div>
                    <div class="layui-inline" style="width:200px;"><input type="text" name="sotime" date-render placeholder="发布时间" class="layui-input" lay-affix="clear"/></div>
                    <div class="layui-inline" style="width:72px;">
                        <select name="state">
                            <option value="">状态</option>
                            <option value="1">启用</option>
                            <option value="0">停用</option>
                        </select>
                    </div>
                    <div class="layui-inline">
                        <div class="layui-btn-group">
                            <button class="layui-btn" lay-submit lay-filter="search-vtool"><i class="layui-icon layui-icon-search layuiadmin-button-btn"></i> 搜索</button>
                            <a class="layui-btn" lay-submit lay-filter="search-vtool-all"><i class="layui-icon layui-icon-light"></i>全部</a>
                        </div>
                    </div>
                </div>
            </form>
        </div>
        <div class="layui-card-body">
            <div class="layui-card-box">
                <div class="layui-btn-group">
                    <a class="layui-btn" id="top-vtool-add"><i class="layui-icon layui-icon-add-circle"></i> 添加</a>
                    <a class="layui-btn" id="top-vtool-del"><i class="layui-icon layui-icon-delete"></i> 删除</a>
                    <a class="layui-btn" id="top-vtool-user"><i class="layui-icon layui-icon-username"></i> 会员信息</a>
                </div>
            </div>
            <table id="vtool"></table>
        </div>
    </div>
</div>
<!--JS部分-->
<script type="text/javascript">
layui.use(['buildItems'], function(){
    var app_api  = "{:config('veitool.api_url')}/";
    var map_root = 'vtool/', app_root = map_root + 'index/';
    var $=layui.$,table=layui.table,form=layui.form,admin=layui.admin;
    /*渲染数据*/
    table.render({
        elem: '#vtool',
        url: app_root + "index?do=json",
        cols: [[
            {type:'checkbox',fixed:'left'},
            {field:'id',fixed:"left",width:50,align:'center',title:'ID',sort:!0},
            {field:"title",width:150,align:'center',toolbar:'<div><a style="cursor:pointer" title="查看详细" lay-event="info">{{d.title}}</a></div>',title:'模块名称'},
            {field:"name",width:150,align:'center',title:'模块标识'},
            {field:'table',align:'center',toolbar:'<div>{{- d.table ? \'<a class="layui-btn layui-btn-xs layui-bg-blue" title="点击设置" lay-event="table">\'+d.table+\'</a>\' : \'-\' }}</div>',title: '数据表名'},
            {field:'appdir',align:'center',toolbar:'<div>{{d.appdir}}{{ d.subdir ? "/" + d.subdir : ""}}</div>',title:'应用目录'},
            {field:'controller',align:'center',title:'控制器名',templet:function(d){return d.controller.replace(/^\w/, c => c.toUpperCase()) + '.php';}},
            {field:'times',width:90,align:'center',title:'生成次数'},
            {field:'addtime',width:160,align:'center',sort:!0,templet:function(d){return layui.util.toDateString(d.addtime*1000);},title:'创建时间'},
            {field:'runtime',width:160,align:'center',sort:!0,templet:function(d){return d.runtime ? layui.util.toDateString(d.runtime*1000) : '-';},title:'最后生成'},
            {field:'state',width:68,align:'center',templet:function(d){return '<input type="checkbox" name="state" lay-skin="switch" lay-text="是|否" lay-filter="vtoolState-chang" value="'+d.state+'" data-json="'+encodeURIComponent(JSON.stringify(d))+'"'+(d.state==1 ? ' checked' : '')+'>';},unresize:true,title:'启用'},
            {fixed:'right',width:200,align:'center',toolbar:'<div><a class="layui-btn layui-btn-xs" lay-event="edit">编辑&生成</a><a class="layui-btn layui-btn-xs layui-bg-blue" lay-event="copy">复制</a><a class="layui-btn layui-btn-warm layui-btn-xs" lay-event="del">删除</a><a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="uninstall">卸载</a></div>',title:'操作'}
        ]],
        page: true,
        limit:{$limit}
    });/**/
    /*顶部添加按钮*/
    $('#top-vtool-add').on('click',function(){open();});
    /*顶部删除按钮*/
    $('#top-vtool-del').on('click', function(){
        var checkRows = table.checkStatus('vtool').data;
        if(checkRows.length === 0){return layer.msg('请选择需删除的模块');}
        var ids = checkRows.map(function(d){return d.id;});
        del(ids);
    });/**/
    /*工具条监听*/
    table.on('tool(vtool)', function(obj){
        var data = obj.data;
        if(obj.event === 'copy'){
            data.id = '';
            open(data);
        }else if(obj.event === 'edit'){
            open(data);
        }else if(obj.event === 'del'){
            del(data.id);
        }else if(obj.event === 'info'){
            admin.open({
                type: 1,
                tpl: true,
                data: data,
                title: '模块详细',
                area: ['1000px','80%'],
                btn: ['编辑', '关闭'],
                content:'<style>.KH_info td{color:#009688;}.layui-table img{max-width:inherit;}.KH_info td li a{color:#999;}.KH_info td li a:last-child{color:#3ea;}</style><div style="padding:10px 20px;">'+
                        '<table class="layui-table KH_info" lay-skin="line"><tbody>'+
                        '<tr><th width="100">模块名称</th><td>{{ d.title }}</td></tr>'+
                        '<tr><th>控制器名</th><td>{{ d.controller }}</td></tr>'+
                        '<tr><th>数据表名</th><td>{{- d.table ? \'<font color="red">\'+d.table+\'</font>\' : "-" }}</td></tr>'+
                        '<tr><th>主表引擎</th><td>{{ d.table_engine }}</td></tr>'+
                        '<tr><th>主表编码</th><td>{{ d.table_charset }}</font></td></tr>'+
                        '<tr><th>关联表名</th><td>{{ d.tables ? d.tables : "-" }}</td></tr>'+
                        '<tr><th>应用目录</th><td>{{ d.appdir }}{{ d.subdir ? \' / \'+d.subdir : \'\' }}</td></tr>'+
                        '<tr><th>详细地址</th><td>{{ d.address ? d.address : "-" }}</td></tr>'+
                        '<tr><th>创建时间</th><td>{{ layui.util.toDateString(d.addtime*1000) }}（创建者: {{ d.add }}）</td></tr>'+
                        '<tr><th>编辑时间</th><td>{{ d.edittime ? layui.util.toDateString(d.edittime*1000) + "（编辑者: " + d.edit + "）" : "-" }}</td></tr>'+
                        '<tr><th>生成时间</th><td>{{ d.runtime ? layui.util.toDateString(d.runtime*1000) + "（生成者: " + d.run + ", 生成次数: "+ d.times +"次）" : "-" }}</td></tr>'+
                        '<tr><th>备注信息</th><td>{{- d.note ? "<ul class=\'layui-textarea layui-bg-black\' style=\'border-width:0;font-size:12px;\'>"+d.note+"</ul>" : "-" }}</td></tr>'+
                        '</tbody></table></div>',
                btn1: function(index){
                    layer.close(index);
                    open(data);
                }
            });
        }else if(obj.event === 'table'){
            var Index = admin.open({
                id: 'tableFieldsOpen', //方便子页获取弹窗序号:$('#tableFieldsOpen').parent().attr('times')
                type: 2,
                offset: 'rb',
                data: data.table_fields ? $.parseJSON(data.table_fields) : [], //传递ID给弹窗子页(解析为JSON数据)
                title: data.title + ' - 数据表【' + data.table +'】字段设置',
                area: ["100%", "100%"],
                btn: ['保存', '关闭'],
                skin: 'layui-anim layui-anim-rl layui-layer-Right',
                url: app_root + 'index?do=table',
                end: function(){
                    delete admin.layerData['d'+Index]; //销毁弹层传递的数据
                },
                btn1: function(index){
                    var newData = JSON.stringify(table.getData('tableFields')); //转为字符串形式
                    admin.req(app_root+"edit?do=up",{id:data.id,av:newData,af:'table_fields'},function(res){
                        layer.msg(res.msg,{shade:[0.4,'#000'],time:1000},function(){
                            table.cache['vtool'][obj.index].table_fields = newData; //更新父页表格数据
                            if(res.code==2) layer.close(index);
                        });
                    },'post',{headersToken:true});
                }
            });
        }else if(obj.event === 'build'){ //构建生成
            buildOpen(data);
        }else if(obj.event === 'uninstall'){ //卸载模块
            layer.confirm('确定要卸载该模块吗？卸载后数据不可恢复！',function(){
                var loadIndex = layer.load(2);
                admin.req(app_root + "uninstall",{name:data.name},function(res){
                    layer.close(loadIndex);
                    layer.msg(res.msg,{shade:[0.4,'#000'],time:1000},function(){
                        if(res.code==1){
                            loadLeftMenu();
                            table.reloadData('vtool');
                        }
                    });
                },'post',{headersToken:true});
            });
        }
    });/**/
    /*状态控制*/
    form.on('switch(vtoolState-chang)',function(obj){
        var json = JSON.parse(decodeURIComponent($(this).data('json')));
        var av = obj.elem.checked ? 1 : 0;
        admin.req(app_root+"edit?do=up",{id:json.id,av:av,af:obj.elem.name},function(res){
            layer.tips(res.msg,obj.othis,{time:1000});
            if(res.code === 0) obj.elem.checked = parseInt(obj.value);
        },'post',{headersToken:true});
    });/**/
    /*删除*/
    function del(ids){
        layer.confirm('确定要删除所选记录吗？删除后所构建模块将不可一键卸载！', function(index){
            layer.close(index);
            admin.req(app_root+"del",{id:ids},function(res){
                layer.msg(res.msg,{shade:[0.4,'#000'],time:1500},function(){
                    if(res.code==1) table.reloadData('vtool');
                });
            },'post',{headersToken:true});
        });
    }/**/
    /*设置弹窗*/
    function open(Dt){
        var action = '';
        admin.open({
            type: 1,
            bid: 'vtool_items',
            btn: Dt && Dt.id ? ['保存', '保存&生成', '取消'] : ['保存','取消'],
            area: ['900px', '95%'],
            title: Dt && Dt.id ? '编辑模块' : '添加模块',
            success: function(l,index){
                layui.buildItems.build({
                    bid: 'vtool_items',
                    space: 'layui-col-space10',
                    data: [
                        {name:"id",type:"hidden"},
                        {name:"name",title:"模块标识",type:"text",value:'',placeholder:"请输入模块标识",verify:'required',itemCol:'layui-col-md6',must:true},
                        {name:"title",title:"模块名称",type:"text",value:'主称|简称',placeholder:"请输入模块名称(主称|简称)",verify:'required',itemCol:'layui-col-md6',must:true},
                        {name:"appdir",title:"应用目录",type:"text",value:'admin',placeholder:"请输入应用名称（常规应用:admin 插件应用:@插件标识）",verify:'required',itemCol:'layui-col-md6',must:true},
                        {name:"subdir",title:"子级目录",type:"text",value:'',placeholder:"请输入子级目录（选填）",itemCol:'layui-col-md6'},
                        {name:"controller",title:"控制器名",type:"text",value:'',id:'c_name',placeholder:"请输入控制器名称",verify:'required',itemCol:'layui-col-md6',must:true},
                        {name:"table",title:"数据表名",type:"text",value:'',id:'t_name',placeholder:"请输入数据表名（可含下划线）",verify:'required',itemCol:'layui-col-md6',must:true},
                        {name:"table_engine",title:"数据引擎",type:"text",value:'InnoDB',id:'table_engine',placeholder:"请输入表引擎",verify:'required',itemCol:'layui-col-md6',must:true},
                        {name:"table_charset",title:"表字符集",type:"text",value:'utf8',id:'table_charset',placeholder:"请输入字符集",verify:'required',itemCol:'layui-col-md6',must:true},
                        {name:"open_size",title:"弹窗尺寸",type:"text",value:'900px,95%',placeholder:"请输入弹窗尺寸 如:宽900px,高95%",verify:'required',tips:'弹窗尺寸如:宽900px,高95%',itemCol:'layui-col-md6',must:true},
                        {name:"menu_pid",title:"上级菜单",type:"text",value:'0',placeholder:"请输入上级菜单ID",tips:'上级菜单ID，0:表示顶级',itemCol:'layui-col-md6',must:true},
                        {name:"type",title:"主题类型",type:"radio",value:'0',options:{0:'不带表头工具表',1:'带表头工具表'},tips:'渲染的数据表格是否带表头工具',itemCol:'layui-col-md6',must:true},
                        {name:"repeat",title:"检查冲突",type:"radio",value:'0',options:{0:'不检查冲突文件',1:'检查冲突文件'},tips:'存在冲突文件则中断并提示文件位置',itemCol:'layui-col-md6',must:true},
                        {name:"excelout",title:"开启导出",type:"radio",value:'0',options:{0:'关闭',1:'开启'},tips:'是否开启导出Execl数据功能',itemCol:'layui-col-md6',must:true},
                        {name:"reback",title:"备份冲突",type:"radio",value:'0',options:{0:'不备份冲突文件',1:'备份冲突文件'},tips:'存在冲突文件则备份有差异的同名文件',itemCol:'layui-col-md6',must:true},
                        {name:"excelup",title:"开启导入",type:"radio",value:'0',options:{0:'关闭',1:'开启'},tips:'是否开启导入Execl数据功能',itemCol:'layui-col-md6',must:true},
                        {name:"dict_load",title:"字典更新",type:"radio",options:{0:"不更新",1:"重载更新"},value:'0',tips:'数据变化时是否更新前端字典数据缓存',itemCol:'layui-col-md6',must:true},
                        {name:"form_type",title:"表单排列",type:"radio",options:{1:"水平",2:"垂直"},value:'1',tips:'表单标题与元素的排列方式',itemCol:'layui-col-md6',must:true},
                        {name:"table_size",title:"表格尺寸",type:"radio",options:{0:"小",1:"中",2:"大"},value:'1',tips:'数据表格呈现的尺寸',itemCol:'layui-col-md6',must:true},
                        {name:"do_build",title:"数据生成",type:"radio",value:'3',options:{0:'仅代码',1:'代码+数据表',2:'代码+菜单',3:'全部生成'},must:true},
                    ]
                });
                $("#c_name").on("input",function(e){
                    $("#t_name").val(e.delegateTarget.value);
                });
                form.val('vtool_items_form',Dt);
                layui.dropdown.render({
                    elem: '#table_engine',
                    data: [{title:'InnoDB',id:'InnoDB'},{title:'MyISAM',id:'MyISAM'}],
                    click: function(obj){
                        $('#table_engine').val(obj.id);
                    }
                });
                layui.dropdown.render({
                    elem: '#table_charset',
                    data: [{title:'utf8',id:'utf8'},{title:'utf8mb4',id:'utf8mb4'}],
                    click: function(obj){
                        $('#table_charset').val(obj.id);
                    }
                });
                form.on('submit(vtool_items)',function(data){
                    // if(action == 'build'){
                    //     var userInfo = getUser();
                    //     if(!userInfo){
                    //         layer.msg('请先登录Veitool会员后再进行操作！',{shade:[0.4,'#000'],time:2000},function(){
                    //             $("#top-vtool-user").trigger("click");
                    //         });
                    //         return false;
                    //     }
                    //     data.field.uid = userInfo.uid;
                    //     data.field.token = userInfo.token;
                    // }
                    //复制开启可复制字段配置
                    if(Dt && !Dt.id) data.field.table_fields = Dt.table_fields;
                    //用于判断是否点击了 保存&生成 按钮
                    if(Dt && Dt.id) data.field.action = action;
                    
                    var btn = $(this);
                    if (btn.attr('stop')){return false;}else{btn.attr('stop',1);}
                    var load = layer.msg('系统构建中，请勿关闭窗口...',{icon:16,shade:0.3,time:false});
                    admin.req(app_root + (data.field.id ? 'edit' : 'add'),data.field,function(res){
                        layer.close(load);
                        layer.msg(res.msg,{shade:[0.4,'#000'],time:1500},function(){
                            if(res.code==1){
                                layer.close(index);
                                table.reloadData('vtool');
                                if(action == 'build' && data.field.do_build > 1) loadLeftMenu();
                            }else if(res.code==5){
                                admin.removeToken();
                                $("#top-vtool-user").trigger("click");
                            }
                            btn.removeAttr('stop');
                        });
                    },'post',{headersToken:true});
                    return false;
                });
            },
            btn2: function(i,lay){
                if(Dt && Dt.id){
                    action = 'build';
                    lay.find("[lay-submit]").trigger('click');
                    return false;
                }
            }
        });
    }/**/
    /*会员信息*/
    $('#top-vtool-user').on("click",function(){
        var userInfo = getUser();
        if(userInfo){
            layer.load();
            $.getJSON(app_api + 'api/addon/user', userInfo, function(res){
                layer.close(layer.index);
                if(res.code==1){
                    admin.open({
                        type: 1,
                        tpl: true,
                        data: res.data,
                        btn: ['退出登录', '取消'],
                        yes: function(id,lay){lay.find("[lay-submit]").trigger('click');},
                        area: ['450px', '300px'],
                        title: '会员信息',
                        content: [
                            '<div style="padding:20px 20px 0 20px;">',
                            '<p style="background:#009688;padding:15px 10px;color:#fff;margin-bottom:20px;border-radius:3px;line-height:28px;position:relative;"><b style="font-size:16px;">您好，{{ d.nickname }}</b><br/>您的帐号：{{ d.username }} 当前已经登录<br/>Veitool 平台提供免费和收费的构建模块</p>',
                            '<p style="margin-bottom:20px;"><i class="layui-icon" style="color:#009688">&#xe67b;</i> <a href="#" id="my-addon-url" target="_blank" style="color:#009688">我的余额</a></p>',
                            '<input type="submit" style="display:none;" id="vtool_logout_submit" lay-submit></div>'
                        ].join(''),
                        success: function(l,index){
                            $('#my-addon-url').on('click',function(){
                                return $(this).attr('href',app_api + 'member.index');
                            });
                            $('#vtool_logout_submit').on("click",function(){
                                $.getJSON(app_api + 'api/addon/logout',userInfo,function(res){
                                    layer.msg(res.msg,{shade:[0.4,'#000'],time:1000},function(){
                                        layer.close(index);
                                        if(res.code==1){
                                            admin.removeToken();
                                        }
                                    });
                                });
                            });
                        }
                    });
                }else{
                    layer.msg(res.msg,{shade:[0.4,'#000'],time:1000},function(){
                        admin.removeToken();
                        $("#top-vtool-user").trigger("click");
                    });
                }
            });
        }else{
            admin.open({
                type: 1,
                area: ['450px', '300px'],
                btn: ['立即登录', '注册帐号'],
                yes: function(id,lay){lay.find("[lay-submit]").trigger('click');},
                btn2: function(){window.open(app_api + 'member.register/index', "_blank");return false;},
                title: '会员登录',
                content: [
                    '<form class="layui-form model-form">',
                    '<h2 style="margin:10px 0 30px 30px;color:#009688;text-align:center;"><fieldset class="layui-elem-field layui-field-title"><legend style="font-size:16px;margin-left:0px;">温馨提示：此处登录帐号为 <a href="'+ app_api +'" style="color:#dd4b39" target="_blank">Veitool官网账号</a></legend></fieldset></h2>',
                    '<div class="layui-form-item"><label class="layui-form-label layui-form-required">登录帐号:</label><div class="layui-input-block"><input type="text" name="username" id="username" class="layui-input" lay-verify="required|user" lay-verType="tips" lay-reqText="请输入登录帐号" placeholder="您的用户名、手机号或邮箱" autocomplete="off"/></div></div>',
                    '<div class="layui-form-item"><label class="layui-form-label layui-form-required">登录密码:</label><div class="layui-input-block"><input type="password" name="password" id="password" class="layui-input" lay-verify="required|pass" lay-verType="tips" lay-reqText="请输入登录密码" placeholder="请输入登录密码" autocomplete="off"/></div></div>',
                    '<input type="submit" style="display:none;" lay-filter="vtool_userlogin_submit" lay-submit></form>'
                ].join(''),
                success: function(l,index){
                    form.verify({
                        user: function(v){if(!/^[\S]{4,20}$/.test(v)){return '请输入4-20位登录帐号';}},
                        pass: function(v){if(!/^[\S]{6,12}$/.test(v)){return '请输入6-12位登录密码';}}
                    });
                    form.on('submit(vtool_userlogin_submit)',function(data){
                        var btn = $(this);
                        if (btn.attr('stop')){return false;}else{btn.attr('stop',1);}
                        admin.req(app_api + 'api/addon/login',data.field,function(res){
                            layer.msg(res.msg,{shade:[0.4,'#000'],time:1500},function(){
                                if(res.code==1){
                                    layer.close(index);
                                    admin.putToken(res.data);
                                }
                                btn.removeAttr('stop');
                            });
                        },'post');
                        return false;
                    });
                }
            });
        }
    });/**/
    /*获取token*/
    function getUser(t){
        var UT = admin.getToken();
        if(t=='uid'){
            return UT ? UT.uid : '';
        }else if(t=='uids'){
            return UT ? '?uid='+UT.uid : '';
        }else if(t=='token'){
            return UT ? UT.token : '';
        }
        return UT ? UT : '';
    }/**/
    /*重载左侧主菜单*/
    var loadLeftMenu = function(){
        admin.req(layui.cache.maps + 'index/json',function(res){
            layui.index.buildLeftMenus(res.menus);
        });
    }/**/
});
</script>