<?php

/**

 * 分类管理

**/

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

$title='二级分类管理';

include './head.php';

if($islogin==1){}else exit("<script language='javascript'>window.location.href='./login.php';</script>");

$my=isset($_GET['my'])?$_GET['my']:null;

?>

<style>

#classlist tbody tr>td:nth-child(2){max-width:50px}

.ui-state-highlight { height: 50px; background: #f0f0f0; border: 1px dashed #ccc; }

</style>


    <div class="col-sm-12 col-md-10 center-block" style="float: none;">

<?php

adminpermission('shop', 1);



$my=isset($_GET['my'])?$_GET['my']:null;



if($my=='qk2')

{

$DB->exec("DELETE FROM pre_tools WHERE 1");

$sql="TRUNCATE TABLE `pre_class`";

if($DB->exec($sql)!==false)

	exit("<script language='javascript'>alert('清空成功！');window.location.href='classlist.php';</script>");

else

	exit("<script language='javascript'>alert('清空失败！".$DB->error()."');history.go(-1);</script>");

}

elseif($my=='classimg'){

$numrows=$DB->getColumn("SELECT count(*) from pre_class");

?>

<div class="block">

	<div class="block-title">

		<h2>修改分类图片&nbsp;[<a href="./classlist.php">返回</a>]</h2>

	</div>

      <div class="table-responsive">

        <table class="table table-striped">

          <thead><tr><th>分类名称</th><th style="min-width:220px">图片URL</th></tr></thead>

          <tbody><form id="classlist">

<?php



$rs=$DB->query("SELECT a.*,b.name as parent_name FROM pre_class a LEFT JOIN pre_parent_class b ON a.parent_cid=b.cid WHERE 1 order by sort asc");

while($res = $rs->fetch())

{

	echo '<tr><td>'.($res['parent_name']?'['.$res['parent_name'].'] ':'').$res['name'].'</td><td><div class="input-group"><input type="file" id="file'.$res['cid'].'" onchange="fileUpload('.$res['cid'].')" style="display:none;"/><input type="text" class="form-control input-sm" name="img['.$res['cid'].']" value="'.$res['shopimg'].'" placeholder="填写图片URL" required><span class="input-group-btn"><a href="javascript:fileSelect('.$res['cid'].')" class="btn btn-success btn-sm" title="上传图片"><i class="glyphicon glyphicon-upload"></i></a><a href="javascript:getImage('.$res['cid'].')" class="btn btn-info btn-sm" title="自动获取图片"><i class="glyphicon glyphicon-search"></i></a><a href="javascript:fileView('.$res['cid'].')" class="btn btn-warning btn-sm" title="查看图片"><i class="glyphicon glyphicon-picture"></i></a></span></div></td></tr>';

}

echo '</form><tr><td></td><td><span class="btn btn-primary btn-sm btn-block" onclick="saveAllImages()">保存全部</span></td></tr>';

?>

			</form>

          </tbody>

        </table>

      </div>

	  <div class="panel-footer">

	  <span class="glyphicon glyphicon-info-sign"></span>当前图片仅适用于部分首页模板

	  </div>

	</div>

<?php

}else{

?>

<div class="block">

	<div class="block-title">

	<div class="block-options pull-right">

		<a href="javascript:listTable()" class="btn btn-default" title="刷新分类列表"><i class="fa fa-refresh"></i></a>

	</div>

		<h2>二级分类列表 <a href="javascript:clearClass()" class="btn btn-danger btn-sm" title="清空分类"><i class="fa fa-trash"></i> 清空分类</a></h2>

	</div>

      <div id="listTable"></div>

	</div>

<?php }?>

  </div>

</div>

<script src="<?php echo $cdnpublic?>layer/3.1.1/layer.js"></script>


<script>

function listTable(){

	var ii = layer.load(2, {shade:[0.1,'#fff']});

	$.ajax({

		type : 'GET',

		url : 'ajax_class.php?act=get',

		dataType : 'json',

		success : function(data) {

			layer.close(ii);

			if(data.code == 0){

				var html = '<div class="table-responsive"><table class="table table-striped"><thead><tr><th><input type="checkbox" onclick="checkAll(this)"></th><th>一级分类</th><th>分类名称</th><th>排序</th><th>操作</th></tr></thead><tbody id="sortable">';

				for(var i=0;i<data.data.length;i++){

					html+='<tr data-id="'+data.data[i].cid+'"><td><input type="checkbox" name="classid" value="'+data.data[i].cid+'"></td><td>'+(data.data[i].parent_name ? data.data[i].parent_name : '<span class="text-muted">暂未设置</span>')+'</td><td>'+data.data[i].name+'</td><td>'+data.data[i].sort+'</td><td>';

					html+='<a href="javascript:editClass('+data.data[i].cid+')" class="btn btn-xs btn-info">编辑</a>&nbsp;';

					html+='<a href="javascript:delClass('+data.data[i].cid+')" class="btn btn-xs btn-danger">删除</a>&nbsp;';

					html+='<a href="./shoplist.php?cid='+data.data[i].cid+'" class="btn btn-xs btn-success">商品</a>';

					if(isMobile()){

						html+='&nbsp;<a href="javascript:void(0)" class="btn btn-xs btn-default" onclick="moveUp(this)"><i class="fa fa-arrow-up"></i></a>';

						html+='&nbsp;<a href="javascript:void(0)" class="btn btn-xs btn-default" onclick="moveDown(this)"><i class="fa fa-arrow-down"></i></a>';

					}

					html+='</td></tr>';

				}

				html+='</tbody></table></div>';

				html+='<div class="panel-footer">';
				html+='<div class="btn-group btn-group-sm">';
				html+='<a href="javascript:addClass()" class="btn btn-success"><i class="fa fa-plus"></i> 添加分类</a>';
				html+='<a href="./classlist.php?my=classimg" class="btn btn-default"><i class="fa fa-image"></i> 修改图片</a>';
				html+='<button class="btn btn-danger" onclick="delSelected()"><i class="fa fa-trash"></i> 删除选中</button>';
				html+='<button class="btn btn-info" onclick="moveSelected()"><i class="fa fa-exchange"></i> 移动选中</button>';
				html+='</div>';
				html+='</div>';
				$('#listTable').html(html);
				
				$("#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: 'ajax_class.php?act=sort',

							data: {ids: ids},

							dataType: 'json',

							success: function(data) {

								if(data.code == 0){

									layer.msg('排序保存成功！');

								}else{

									layer.alert(data.msg);

								}

							},

							error:function(data){

								layer.msg('服务器错误');

							}

						});

					}

				});

				$("#sortable").disableSelection();

			}else{

				layer.alert(data.msg, {icon: 2})

			}

		},

		error:function(data){

			layer.msg('服务器错误');

			return false;

		}

	});

}

function addClass(){

	var ii = layer.load(2, {shade:[0.1,'#fff']});

	$.ajax({

		type : 'GET',

		url : 'ajax_class.php?act=getParentClass',

		dataType : 'json',

		success : function(data) {

			layer.close(ii);

			if(data.code == 0){

				var options = '<option value="0">不选择</option>';

				for(var i=0;i<data.data.length;i++){

					options+='<option value="'+data.data[i].cid+'">'+data.data[i].name+'</option>';

				}

				var html = '<div class="form-group"><div class="input-group"><div class="input-group-addon">一级分类</div><select id="parent_cid" class="form-control">'+options+'</select></div></div>';

				html += '<div class="form-group"><div class="input-group"><div class="input-group-addon">分类名称</div><input type="text" id="name" value="" 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="10" class="form-control" required/></div></div>';

				layer.open({

					area: ['360px'],

					title: '添加分类',

					content: html,

					btn: ['确定', '取消'],

					yes: function(){

						var parent_cid = $("#parent_cid").val();

						var name = $("#name").val();

						var sort = $("#sort").val();

						if(name==''){layer.alert('请确保各项不能为空！');return false;}

						var ii = layer.load(2, {shade:[0.1,'#fff']});

						$.ajax({

							type : 'POST',

							url : 'ajax_class.php?act=add',

							data : {parent_cid:parent_cid,name:name,sort:sort},

							dataType : 'json',

							success : function(data) {

								layer.close(ii);

								if(data.code == 0){

									layer.alert(data.msg,{

										icon: 1,

										closeBtn: false

									}, function(){

										listTable();

										layer.closeAll();

									});

								}else{

									layer.alert(data.msg, {icon: 2})

								}

							},

							error:function(data){

								layer.msg('服务器错误');

								return false;

							}

						});

					}

				});

			}else{

				layer.alert(data.msg, {icon: 2})

			}

		},

		error:function(data){

			layer.msg('服务器错误');

			return false;

		}

	});

}

function editClass(cid){

	var ii = layer.load(2, {shade:[0.1,'#fff']});

	$.ajax({

		type : 'GET',

		url : 'ajax_class.php?act=get_class&cid='+cid,

		dataType : 'json',

		success : function(data) {

			layer.close(ii);

			if(data.code == 0){

				var options = '<option value="0">不选择</option>';

				for(var i=0;i<data.parent_class.length;i++){

					options+='<option value="'+data.parent_class[i].cid+'" '+(data.parent_class[i].cid==data.data.parent_cid?'selected':'')+'>'+data.parent_class[i].name+'</option>';

				}

				var html = '<div class="form-group"><div class="input-group"><div class="input-group-addon">一级分类</div><select id="parent_cid" class="form-control">'+options+'</select></div></div>';

				html += '<div class="form-group"><div class="input-group"><div class="input-group-addon">分类名称</div><input type="text" id="name" value="'+data.data.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="'+data.data.sort+'" class="form-control" required/></div></div>';

				layer.open({

					area: ['360px'],

					title: '修改分类信息',

					content: html,

					btn: ['确定', '取消'],

					yes: function(){

						var parent_cid = $("#parent_cid").val();

						var name = $("#name").val();

						var sort = $("#sort").val();

						if(name==''){layer.alert('请确保各项不能为空！');return false;}

						var ii = layer.load(2, {shade:[0.1,'#fff']});

						$.ajax({

							type : 'POST',

							url : 'ajax_class.php?act=edit',

							data : {cid:cid,parent_cid:parent_cid,name:name,sort:sort},

							dataType : 'json',

							success : function(data) {

								layer.close(ii);

								if(data.code == 0){

									layer.alert(data.msg,{

										icon: 1,

										closeBtn: false

									}, function(){

										listTable();

										layer.closeAll();

									});

								}else{

									layer.alert(data.msg, {icon: 2})

								}

							},

							error:function(data){

								layer.msg('服务器错误');

								return false;

							}

						});

					}

				});

			}else{

				layer.alert(data.msg, {icon: 2})

			}

		},

		error:function(data){

			layer.msg('服务器错误');

			return false;

		}

	});

}

function delClass(cid) {

	var confirmobj = layer.confirm('你确实要删除此分类吗？', {

	  btn: ['确定','取消']

	}, function(){

	  $.ajax({

		type : 'GET',

		url : 'ajax_class.php?act=delete&cid='+cid,

		dataType : 'json',

		success : function(data) {

			if(data.code == 0){

				layer.alert(data.msg,{

					icon: 1,

					closeBtn: false

				}, function(){

					listTable();

					layer.closeAll();

				});

			}else{

				layer.alert(data.msg, {icon: 2});

			}

		},

		error:function(data){

			layer.msg('服务器错误');

			return false;

		}

	  });

	});

}

function clearClass(){

	var confirmobj = layer.confirm('你确实要清空所有分类吗？', {

	  btn: ['确定','取消']

	}, function(){

		window.location.href='./classlist.php?my=qk2';

	});

}

$(document).ready(function(){

	listTable();

	if(!isMobile()){

		$("#sortable").sortable({

			items: "tr",

			placeholder: "ui-state-highlight",

			update: function() {

				updateSort();

			}

		}).disableSelection();

	}

})

function fileSelect(cid) {
    $('#file'+cid).click();
}

function fileUpload(cid) {
    var fileObj = document.getElementById('file'+cid).files[0];
    if (fileObj == undefined) return;
    
    var formData = new FormData();
    formData.append('file', fileObj);
    formData.append('cid', cid);
    
    var ii = layer.load(2, {shade:[0.1,'#fff']});
    $.ajax({
        url: 'cx-ajax.php?act=upload_classimg',
        data: formData,
        type: 'POST',
        cache: false,
        processData: false,
        contentType: false,
        dataType: 'json',
        success: function(data){
            layer.close(ii);
            if(data.code == 0){
                $("input[name='img["+cid+"]']").val(data.url);
                layer.msg('上传成功');
            }else{
                layer.alert(data.msg);
            }
        },
        error: function(){
            layer.close(ii);
            layer.msg('服务器错误');
        }
    });
}

function fileView(cid) {
    var imgurl = $("input[name='img["+cid+"]']").val();
    if(imgurl=='') {
        layer.msg('请先上传图片或填写图片地址');
        return false;
    }
    if(imgurl.indexOf('http') == -1) imgurl = '../'+imgurl;
    layer.open({
        type: 1,
        area: ['360px', '400px'],
        title: '查看分类图片',
        shade: 0.3,
        anim: 1,
        shadeClose: true,
        content: '<center><img width="300px" src="'+imgurl+'"></center>'
    });
}

function getImage(cid) {
    layer.prompt({title: '请输入图片地址'}, function(value, index){
        $("input[name='img["+cid+"]']").val(value);
        layer.close(index);
    });
}

function saveAllImages() {
    var imgs = {};
    var count = 0;
    $("input[name^='img[']").each(function(){
        var cid = $(this).attr('name').match(/\[(\d+)\]/)[1];
        var val = $(this).val();
        if(val) {
            imgs[cid] = val;
            count++;
        }
    });
    
    if(count == 0) {
        layer.msg('没有找到需要保存的图片');
        return;
    }
    
    var ii = layer.load(2, {shade:[0.1,'#fff']});
    $.ajax({
        type : 'POST',
        url : 'cx-ajax.php?act=save_all_classimg',
        data : {imgs: JSON.stringify(imgs)},
        dataType : 'json',
        success : function(data) {
            layer.close(ii);
            if(data.code == 0){
                layer.alert(data.msg, {icon:1}, function(){
                    layer.closeAll();
                });
            }else{
                var errorMsg = data.msg;
                if(data.debug && data.debug.errors) {
                    errorMsg += '<br><br>详细错误：<br>' + data.debug.errors.join('<br>');
                }
                layer.alert(errorMsg, {icon:2});
            }
        },
        error:function(xhr, status, error){
            layer.close(ii);
            var errorMsg = '服务器错误';
            if(xhr.responseText) {
                try {
                    var response = JSON.parse(xhr.responseText);
                    if(response.msg) {
                        errorMsg = response.msg;
                    }
                } catch(e) {
                    errorMsg = '服务器返回数据解析失败：' + xhr.responseText;
                }
            }
            layer.alert(errorMsg, {icon:2});
        }
    });
}

function checkAll(obj){
	$("input[name='classid']").prop('checked', $(obj).prop('checked'));
}

function getSelectedIds(){
	var selected = [];
	$("input[name='classid']:checked").each(function(){
		selected.push($(this).val());
	});
	return selected;
}

function delSelected(){
	var selected = getSelectedIds();
	if(selected.length == 0){
		layer.msg('请至少选择一个分类');
		return;
	}
	var confirmobj = layer.confirm('你确实要删除选中的'+selected.length+'个分类吗？', {
		btn: ['确定','取消']
	}, function(){
		var ii = layer.load(2, {shade:[0.1,'#fff']});
		$.ajax({
			type : 'POST',
			url : 'ajax_class.php?act=delete_batch',
			data : {ids: selected},
			dataType : 'json',
			success : function(data) {
				layer.close(ii);
				if(data.code == 0){
					layer.alert(data.msg,{
						icon: 1,
						closeBtn: false
					}, function(){
						listTable();
						layer.closeAll();
					});
				}else{
					layer.alert(data.msg, {icon: 2});
				}
			},
			error:function(data){
				layer.close(ii);
				layer.msg('服务器错误');
				return false;
			}
		});
	});
}

function moveSelected(){
	var selected = getSelectedIds();
	if(selected.length == 0){
		layer.msg('请至少选择一个分类');
		return;
	}
	var ii = layer.load(2, {shade:[0.1,'#fff']});
	$.ajax({
		type : 'GET',
		url : 'ajax_class.php?act=getParentClass',
		dataType : 'json',
		success : function(data) {
			layer.close(ii);
			if(data.code == 0){
				var options = '<option value="0">不选择</option>';
				for(var i=0;i<data.data.length;i++){
					options+='<option value="'+data.data[i].cid+'">'+data.data[i].name+'</option>';
				}
				var html = '<div class="form-group"><div class="input-group"><div class="input-group-addon">移动到</div><select id="target_parent_cid" class="form-control">'+options+'</select></div></div>';
				layer.open({
					area: ['360px'],
					title: '移动分类',
					content: html,
					btn: ['确定', '取消'],
					yes: function(){
						var parent_cid = $("#target_parent_cid").val();
						var ii = layer.load(2, {shade:[0.1,'#fff']});
						$.ajax({
							type : 'POST',
							url : 'ajax_class.php?act=move_batch',
							data : {ids: selected, parent_cid: parent_cid},
							dataType : 'json',
							success : function(data) {
								layer.close(ii);
								if(data.code == 0){
									layer.alert(data.msg,{
										icon: 1,
										closeBtn: false
									}, function(){
										listTable();
										layer.closeAll();
									});
								}else{
									layer.alert(data.msg, {icon: 2})
								}
							},
							error:function(data){
								layer.close(ii);
								layer.msg('服务器错误');
								return false;
							}
						});
					}
				});
			}else{
				layer.alert(data.msg, {icon: 2})
			}
		},
		error:function(data){
			layer.close(ii);
			layer.msg('服务器错误');
			return false;
		}
	});
}

function isMobile() {
	return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
}

function moveUp(obj) {
	var tr = $(obj).closest('tr');
	var prev = tr.prev();
	if(prev.length > 0) {
		tr.insertBefore(prev);
		updateSort();
	}
}

function moveDown(obj) {
	var tr = $(obj).closest('tr');
	var next = tr.next();
	if(next.length > 0) {
		tr.insertAfter(next);
		updateSort();
	}
}

function updateSort() {
	var ids = {};
	$("#sortable tr").each(function(index,item){
		ids[index] = $(item).attr('data-id');
	});
	$.ajax({
		type: 'POST',
		url: 'ajax_class.php?act=sort',
		data: {ids: ids},
		dataType: 'json',
		success: function(data) {
			if(data.code == 0){
				layer.msg('排序保存成功！');
			}else{
				layer.alert(data.msg);
			}
		},
		error:function(data){
			layer.msg('服务器错误');
		}
	});
}

</script>

</body>

</html>