<?php
namespace Home\Controller;
use Think\Controller;
class ContentController extends CommonController {

	// 首页
	public function index(){
		// 读取栏目信息
		$category_id = I('id','','intval');
		$_where = array();
		$_where['status'] = array('eq',1);
		$_where['id'] = array('eq',$category_id);
		if (!$category = D('Contentcate','ViewModel') -> where($_where) -> find()) {
			$this -> error('对不起，你所访问的栏目不存在！');
		}
		if ($category['recursion'] != 0) {
			$_where = array();
			$_where['status'] = array('eq',1);
			switch ($category['recursion']) {
				case 1:
					$_where['category_id'] = array('eq',$category_id);
					break;
				case 2:
					$category_ids = M('Contentcate') -> where('status=1 and pid='.$category_id) -> getField('id',true);
					$category_ids[] = $category_id;
					$_where['category_id'] = array('in',$category_ids);
					break;
				case 3:
					$category_ids = subtreeid(M('Contentcate') -> where('status=1') -> select(),$category_id);
					$category_ids[] = $category_id;
					$_where['category_id'] = array('in',$category_ids);
					break;
				case 4:
					# code...
					break;
				
				default:
					$_where['category_id'] = array('eq',$category_id);
					break;
			}
			$m = D('Content','ViewModel');
			$count = $m -> where($_where) -> count();
			$Page = new \Common\Vendor\Page($count,$category['pagenum']?:20);
			$this -> lists = $m -> where($_where) -> limit($Page->firstRow.','.$Page->listRows) -> order('id desc') -> select();
			$this -> pages = $Page->show();
		}
		$this -> category = $category;
		$this -> SEO = array(
			'title'	=>	$category['text'],
			'keywords'	=>	$category['keywords'],
			'description'	=>	$category['description'],
			);
		$this -> display($category['tpl']);
	}

	// 内容详细页面
	public function detail(){
		// 读取内容
		$id = I('id','','intval');
		if (!$id) {
			$this -> error('参数错误！');
		}
		if (I('to')) {
			if ($nexttoid = nexttoid($id)) {
				redirect(U('detail', array('id' => $nexttoid)));
			}else{
				$this -> error('没有了');
			}
		}
		$where = array(
			'id'	=>	array('eq',$id),
			'status'	=>	array('eq',1),
			'Category.status'	=>	array('eq',1),
			);
		if (!$data = D('Content','ViewModel') -> where($where) -> find()) {
			$this -> error('对不起，你所访问的内容不存在！');
		}
		// 分配变量
		$data['ext'] = json_decode($data['ext'],true);
		$this -> assign($data);
		$this -> SEO = array(
			'title'	=>	$data['title'],
			'keywords'	=>	$data['keywords'],
			'description'	=>	$data['description'],
			);
		// 获取模板并显示
		if (!empty($data['tpl'])) {
			$tpl = $data['tpl'];
		}elseif (!empty($data['category_tpl_detail'])) {
			$tpl = $data['category_tpl_detail'];
		}else{
			$tpl = '';
		}
		$this -> display($tpl);
	}
}