<?php
namespace Admin\Controller;
use Think\Controller;

class PcategoryController extends BasicController {

    public function index() {
    	header('Location: /admin/Pcategory/pcategoryList');
    }
	
	//分类列表
	public function pcategoryList() {
		$where = "1=1 and is_del=0";
		$search_param = array();
		$pCategory = M('pcategory');
		$p = I('get.p','1','htmlspecialchars');
		
		$count = $pCategory->where($where)->count();// 查询满足要求的总记录数
		$Page = new \Think\Page($count,20,$search_param);// 实例化分页类 传入总记录数和每页显示的记录数(25)
		$show = $Page->show();// 分页显示输出
		$categoryList = $pCategory->field("pcategory.id,category,count(program_category.cid) as count")->join("left join program_category on pcategory.id=program_category.cid")->where($where)->group("pcategory.id")->page($p.',20')->select();
		$this->assign('categoryList',$categoryList);
		$this->assign('page',$show);
		$this->assign('roleid',session('role'));
		$this->assign('title','分类列表');
        
    	$this->display('pcategoryList');
	}
	
	//删除分类
	public function delCategory() {
		$id = I('id','','htmlspecialchars');
		$pCategory = M('pcategory');
		$program_category = M('program_category');
		$data['is_del'] = 1;
		
		$pCategory->where("id='$id'")->save($data);
		
		$programList = $program_category->where("cid='$id'")->select();	
		$program_category->where("cid=$id")->delete();
		$i=0;
		foreach($programList as $k=>$v){
			$info = $program_category->where("pid='".$v['pid']."' and cid!=1")->find();
			if($info<=0){
				$arr[$i]['pid'] = $v['pid'];
				$arr[$i]['cid'] = 1;
				$i++;
			}
		}
		$program_category->addAll($arr);
		echo 1;
	}
	
	//添加分类
	public function paddCategory() {
		if(IS_POST) {
			$pCategory = M('pcategory');
			$data['category'] = I('post.category','','htmlspecialchars');
			$pCategory->add($data);

			echo 1;
			exit();
		}
			
		$this->assign('title','添加分类');
    	$this->display('paddCategory');
	}
	
	//编辑分类
	public function peditCategory() {
		$id = I('id','','htmlspecialchars');
		$pCategory = M('pcategory');
		
		if(IS_POST) {
			$data['category'] = I('post.category','','htmlspecialchars');
			$id = I('id','','htmlspecialchars');
			$pCategory->where("id='$id'")->save($data);
			echo 1;
			exit();
		}
		
		$categoryInfo = $pCategory->where("id='$id'")->find();
		$this->assign('categoryInfo',$categoryInfo);
		$this->assign('id',$id);
		$this->assign('title','编辑分类');
		$this->assign('action_name','pcategoryList');
		$this->display();
	}

}