<?php
include("../includes/common.php");

if(isset($_GET['act'])) {
    @header('Content-Type: application/json; charset=UTF-8');
    if(!$islogin)exit(json_encode(['code'=>-1,'msg'=>'未登录']));
    $act=daddslashes($_GET['act']);

    if($act=='add'){
        $name = trim($_POST['name']);
        $sort = intval($_POST['sort']);
        if(!$name) exit(json_encode(['code'=>-1,'msg'=>'分类名称不能为空']));
        if($DB->exec("INSERT INTO `pre_parent_class` (`name`,`sort`,`addtime`) VALUES (:name,:sort,NOW())", [':name'=>$name,':sort'=>$sort]) !== false)
            exit(json_encode(['code'=>0,'msg'=>'添加一级分类成功']));
        else
            exit(json_encode(['code'=>-1,'msg'=>'添加一级分类失败'.$DB->error()]));
    }
    elseif($act=='edit'){
        $cid = intval($_POST['cid']);
        $name = trim($_POST['name']);
        $sort = intval($_POST['sort']);
        if(!$name) exit(json_encode(['code'=>-1,'msg'=>'分类名称不能为空']));
        if($DB->exec("UPDATE `pre_parent_class` SET `name`=:name,`sort`=:sort WHERE `cid`=:cid", [':name'=>$name,':sort'=>$sort,':cid'=>$cid]) !== false)
            exit(json_encode(['code'=>0,'msg'=>'修改一级分类成功']));
        else
            exit(json_encode(['code'=>-1,'msg'=>'修改一级分类失败'.$DB->error()]));
    }
    elseif($act=='del'){
        $cid = intval($_POST['cid']);
        // 检查是否有二级分类关联
        $rows = $DB->getColumn("SELECT count(*) FROM `pre_class` WHERE `parent_cid`=:cid", [':cid'=>$cid]);
        if($rows>0) exit(json_encode(['code'=>-1,'msg'=>'该一级分类下还有二级分类，请先删除二级分类']));
        if($DB->exec("DELETE FROM `pre_parent_class` WHERE `cid`=:cid", [':cid'=>$cid]) !== false)
            exit(json_encode(['code'=>0,'msg'=>'删除一级分类成功']));
        else
            exit(json_encode(['code'=>-1,'msg'=>'删除一级分类失败'.$DB->error()]));
    }
    elseif($act=='sort'){
        $ids = $_POST['ids'];
        if(!is_array($ids))exit(json_encode(['code'=>-1,'msg'=>'参数错误']));
        foreach($ids as $k=>$v){
            $k = intval($k);
            $v = intval($v);
            $DB->exec("UPDATE `pre_parent_class` SET `sort`=:sort WHERE `cid`=:cid", [':sort'=>$k,':cid'=>$v]);
        }
        exit(json_encode(['code'=>0,'msg'=>'排序保存成功']));
    }
    elseif($act=='batch_move'){
        $pcid = intval($_POST['pcid']);
        $cids = $_POST['cids'];
        if(!$pcid)exit(json_encode(['code'=>-1,'msg'=>'请选择目标一级分类']));
        if(!is_array($cids))exit(json_encode(['code'=>-1,'msg'=>'请选择要移动的二级分类']));
        
        foreach($cids as $cid){
            $DB->exec("UPDATE `pre_class` SET `parent_cid`=:pcid WHERE `cid`=:cid", [':pcid'=>$pcid,':cid'=>$cid]);
        }
        exit(json_encode(['code'=>0,'msg'=>'批量移动成功']));
    }
    exit(json_encode(['code'=>-4,'msg'=>'No Act']));
}

$title='一级分类管理';
include './head.php';
if($islogin==1){}else exit("<script language='javascript'>window.location.href='./login.php';</script>");

$list = $DB->getAll("SELECT * FROM `pre_parent_class` ORDER BY `sort` ASC,`cid` ASC");

// 获取所有二级分类
$class_list = $DB->getAll("SELECT * FROM `pre_class` ORDER BY `sort` ASC");
?>
<div class="col-sm-12 col-md-10 col-lg-8 center-block" style="float: none;">
<div class="block">
<div class="block-title">
    <h3 class="panel-title">一级分类列表</h3>
    <div class="alert alert-info" style="margin-top: 10px;">
        <i class="fa fa-info-circle"></i> 温馨提示：一级分类功能仅在首页模板设置中启用storenews模板后生效。
    </div>
</div>
<div class="">
  <div class="table-responsive">
    <table class="table table-striped">
      <thead><tr><th>分类名称</th><th>排序</th><th>添加时间</th><th>操作</th></tr></thead>
      <tbody id="sortable">
<?php
foreach($list as $res){
    echo '<tr data-id="'.$res['cid'].'"><td><b>'.$res['name'].'</b></td><td>'.$res['sort'].'</td><td>'.$res['addtime'].'</td><td><a href="javascript:edit('.$res['cid'].',\''.$res['name'].'\','.$res['sort'].')" class="btn btn-info btn-xs">编辑</a>&nbsp;<a href="javascript:batch_move('.$res['cid'].')" class="btn btn-warning btn-xs">批量管理</a>&nbsp;<a href="javascript:del('.$res['cid'].')" class="btn btn-xs btn-danger">删除</a></td></tr>';
}
?>
      </tbody>
    </table>
  </div>
  <div class="panel-footer">
    <span class="glyphicon glyphicon-plus"></span><a href="javascript:add()" class="btn btn-default btn-sm">添加一级分类</a>
  </div>
</div>
</div>
</div>
<script src="<?php echo $cdnpublic?>layer/3.1.1/layer.js"></script>
<script>
$(function() {
    $("#sortable").sortable({
        items: "tr",
        placeholder: "ui-state-highlight",
        update: function() {
            var ids = {};
            $("#sortable tr").each(function(index,item){
                ids[index] = $(item).attr('data-id');
            });
            $.ajax({
                type: 'POST',
                url: 'parentclass.php?act=sort',
                data: {ids: ids},
                dataType: 'json',
                success: function(data) {
                    if(data.code == 0){
                        layer.msg('排序保存成功！');
                    }else{
                        layer.alert(data.msg);
                    }
                },
                error: function(){
                    layer.msg('服务器错误');
                }
            });
        }
    });
    $("#sortable").disableSelection();
});

function add(){
    layer.prompt({title: '请输入一级分类名称',value: '',formType: 0}, function(text, index){
        layer.close(index);
        $.ajax({
            type : 'POST',
            url : 'parentclass.php?act=add',
            data : {name:text,sort:0},
            dataType : 'json',
            success : function(data) {
                if(data.code == 0){
                    layer.msg('添加成功！', {icon:1,time:1500},function(){
                        window.location.reload();
                    });
                }else{
                    layer.alert(data.msg, {icon: 2});
                }
            },
            error:function(xhr, status, error){
                layer.msg('请求失败：' + error);
            }
        });
    });
}
function edit(cid,name,sort){
    var html = '<div class="form-group"><div class="input-group"><div class="input-group-addon">分类名称</div><input type="text" id="name" value="'+name+'" class="form-control" required/></div></div>';
    html += '<div class="form-group"><div class="input-group"><div class="input-group-addon">显示排序</div><input type="number" id="sort" value="'+sort+'" class="form-control" required/></div></div>';
    layer.open({
        area: ['360px'],
        title: '修改一级分类信息',
        content: html,
        btn: ['确定', '取消'],
        yes: function(){
            var name = $("#name").val();
            var sort = $("#sort").val();
            if(name == ''){
                layer.alert('请确保各项不能为空！');return false;
            }
            $.ajax({
                type : 'POST',
                url : 'parentclass.php?act=edit',
                data : {cid:cid,name:name,sort:sort},
                dataType : 'json',
                success : function(data) {
                    if(data.code == 0){
                        layer.msg('修改成功！', {icon:1,time:1500},function(){
                            window.location.reload();
                        });
                    }else{
                        layer.alert(data.msg, {icon: 2});
                    }
                },
                error:function(xhr, status, error){
                    layer.msg('请求失败：' + error);
                }
            });
        }
    });
}
function del(cid) {
    var confirmobj = layer.confirm('你确实要删除此一级分类吗？', {
      btn: ['确定','取消']
    }, function(){
      $.ajax({
        type : 'POST',
        url : 'parentclass.php?act=del',
        data : {cid:cid},
        dataType : 'json',
        success : function(data) {
            if(data.code == 0){
                layer.msg('删除成功！', {icon:1,time:1500},function(){
                    window.location.reload();
                });
            }else{
                layer.alert(data.msg, {icon: 2});
            }
        },
        error:function(xhr, status, error){
            layer.msg('请求失败：' + error);
        }
      });
    });
}
function batch_move(pcid) {
    var html = '<div class="form-group">';
    html += '<select id="class_ids" class="form-control" multiple style="height:200px;">';
<?php
foreach($class_list as $res){
    echo 'html += \'<option value="'.$res['cid'].'">'.$res['name'].'</option>\';';
}
?>
    html += '</select>';
    html += '<small class="help-block">按住Ctrl键可以多选</small>';
    html += '</div>';
    
    layer.open({
        area: ['360px'],
        title: '批量移动二级分类',
        content: html,
        btn: ['确定移动', '取消'],
        yes: function(){
            var cids = $('#class_ids').val();
            if(!cids || cids.length == 0){
                layer.alert('请选择要移动的二级分类！');
                return;
            }
            $.ajax({
                type : 'POST',
                url : 'parentclass.php?act=batch_move',
                data : {pcid:pcid, cids:cids},
                dataType : 'json',
                success : function(data) {
                    if(data.code == 0){
                        layer.msg('批量移动成功！', {icon:1});
                    }else{
                        layer.alert(data.msg, {icon: 2});
                    }
                },
                error:function(data){
                    layer.msg('服务器错误');
                }
            });
        }
    });
}
</script>
<?php include './foot.php';?> 