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

class IndexController extends Controller {
	private $User;
	private $uid; //用户id，作为主要的检索参数使用
	private $arr; //返回页面的数据
	private $sql_one   = '000'; //首页要显示的文章内容公共部分
	private $sql_muilt = '000';

	public function verify() {
		$config = array(
			'fontSize' => 15, // 验证码字体大小
			'length'   => 4, // 验证码位数
			'useNoise' => false, // 关闭验证码杂点
			'expire'   => 180, // 有效期
			'imageW'   => 120, // 宽度
			'imageH'   => 30, // 高度
		);

		$Verify = new \Think\Verify($config);
		ob_clean();
		//$Verify->useZh=true;
		$Verify->entry();
	}
	function check_verify($code, $id = '') {
		$verify = new \Think\Verify();
		return $verify->check($code, $id);
	}
	public function getBlogSetting($array) {
		$this->uid                    = $array['id'];
		$this->arr['User']            = $array['username'];
		$this->arr['blogname']        = $array['blogname'];
		$this->arr['email']           = $array['email'];
		$this->arr['blogdescription'] = $array['blogdescription'];
		$this->arr['uid']             = $this->uid;
		if (isMobile()) {set_theme('mobile');} else {set_theme($array['theme']);}

	}
	public function getCategory($id) //列出分类
	{
		$model = M('categories');
		$array = $model->where('userid=' . $this->uid)->select();
		return $array;
	}
	public function getTops() {
		$model                     = M('archives');
		$this->arr['LastArchives'] = $model->where($this->sql_one)->order('writetime desc')->limit(0, 5)->field('id,title')->select();
		$this->arr['HotArchives']  = $model->where($this->sql_one)->order('views desc')->limit(0, 5)->field('id,title')->select();
		$this->arr['RandArchives'] = $model->where($this->sql_one)->order('Rand()')->limit(0, 5)->select();
		$model                     = M('comments');
		$this->arr['LastComments'] = $model->table(C('DB_PREFIX') . 'comments c,' . C('DB_PREFIX') . 'archives a')->where('c.userid=' . $this->uid . ' and c.archive=a.id')->order('c.commtime desc')->field('c.*,a.title')->limit(0, 5)->select();
		//$this->arr['LastComments']=$model->where('userid='.$this->uid)->order('commtime desc')->limit(0,5)->select();

	}
	public function getTags() //列出tag
	{
		$model                 = M('tags');
		$this->arr['TagsList'] = $model->where('userid=' . $this->uid)->select();
		//var_dump($this->arr['Tags']);
	}
	public function getGroupByDate() {
		$model      = M('archives');
		return $arr = $model->where($this->sql_one)->field('count(*) AS `counts`,DATE_FORMAT(writetime,"%Y%m") AS `Ym`,DATE_FORMAT(writetime,"%Y年%m月") AS `YmFormat`')->group('DATE_FORMAT(writetime,"%Y%m")')->select();
	}
	public function getComments($id) {
		$model                 = M('comments');
		$array['Parent']       = $model->where('reply=0 and archive=' . $id)->select();
		$array['Children']     = $model->where('reply<>0 and archive=' . $id)->select();
		$array['CommentCount'] = sizeof($array['Parent']) + sizeof($array['Children']);
		return $array;
	}
	public function getArchive($id) //显示文章
	{
		$model = M('archives');
		$model->where('id=' . $id)->setInc('views', 1);
		$array = $model->table(C('DB_PREFIX') . 'archives a,' . C('DB_PREFIX') . 'categories c')->where('a.id=' . $id)->order('a.id desc')->field('a.*,c.catename')->find();
		if ('1' == $array['ispublish'] || '-1' != $array['showid']) {
			$this->error('文章不予显示');
		}

		$array['Next'] = $model->where($this->sql_one . ' and id>' . $id)->order('id desc')->field('id,title')->limit(1)->find();
		$array['Prev'] = $model->where($this->sql_one . ' and id<' . $id)->order('id desc')->field('id,title')->limit(1)->find();
		return $array;
	}
	public function getArchivies($id = null, $type = null) //根据不同功能列出文章
	{
		$model = M();
		$page  = 0;
		$count = 0;
		if (null == $_GET['page']) {
			$page = 1;
		} else {
			$page = $_GET['page'];
		}

		$start = ($page - 1) * 10;

		if (!isset($id) || !isset($type)) {

			$count = $model->table(C('DB_PREFIX') . 'archives')->where($this->sql_one)->count();
			$array = $model->table(C('DB_PREFIX') . 'archives a,' . C('DB_PREFIX') . 'categories c')->where('a.category=c.id and ' . $this->sql_muilt)->order('a.id desc')->field('a.*,c.catename')->limit($start, 10)->select();
		} elseif ('tag' == $type) {

		} elseif ('ml' == $type) {
			$count = $model->table(C('DB_PREFIX') . 'archives')->where($this->sql_one . ' and DATE_FORMAT(writetime,"%Y%m") like "%' . $id . '%"')->count();
			$array = $model->table(C('DB_PREFIX') . 'archives a,' . C('DB_PREFIX') . 'categories c')->where($this->sql_muilt . ' and a.category=c.id and DATE_FORMAT(writetime,"%Y%m") like "%' . $id . '%"')->order('a.id desc')->field('a.*,c.catename')->limit($start, 10)->select();
		} elseif ('cat' == $type) {
			$count = $model->table(C('DB_PREFIX') . 'archives')->where($this->sql_one . ' and category=' . $id)->count();
			$array = $model->table(C('DB_PREFIX') . 'archives a,' . C('DB_PREFIX') . 'categories c')->where($this->sql_muilt . ' and a.category=c.id and a.category=' . $id)->order('a.id desc')->field('a.*,c.catename')->limit($start, 10)->select();
		} elseif ($type = 's') {
			$count = $model->table(C('DB_PREFIX') . 'archives')->where($this->sql_one . ' and (content like "%' . $id . '%" or title like "%' . $id . '%")')->count();
			$array = $model->table(C('DB_PREFIX') . 'archives a,' . C('DB_PREFIX') . 'categories c')->where($this->sql_muilt . ' and a.category=c.id and (a.content like "%' . $id . '%" or a.title like "%' . $id . '%")')->order('a.id desc')->field('a.*,c.catename')->limit($start, 10)->select(); # code...
			foreach ($array as $k => $val) {
				$array[$k]['content'] = hightLightSearch($val['content'], $id);
				//var_dump(hightLightSearch($val['content'],$id));
				$array[$k]['title'] = hightLightSearch($val['title'], $id);
			}
			//var_dump($array);
		}
		if ($count % 10 != 0) {
			$this->arr['Pages'] = floor($count / 10) + 1;
		} else {
			$this->arr['Pages'] = floor($count / 10);
		}

		$this->arr['CurrentPage'] = $page;
		return $array;
	}
	public function setComment() {
		if ($this->check_verify($_POST['verify'])) {
			if (null != $_POST['email'] && null != $_POST['comment'] && $_GET['p']) {
				$model            = M('Comments');
				$data['author']   = $_POST['author'];
				$data['email']    = $_POST['email'];
				$data['comment']  = $_POST['comment'];
				$data['archive']  = $_GET['p'];
				$data['url']      = $_POST['url'];
				$data['commtime'] = date('Y-m-d H:i:s', time());
				$data['userid']   = $_POST['uid'];
				$data['reply']    = $_POST['comment_parent'];
				$data['ip']       = get_client_ip();
				if (($lastid = $model->data($data)->add()) != 0) {
					cookie('author', $_POST['author']);
					cookie('email', $_POST['email']);
					cookie('url', $_POST['url']);
					//echo $model->getLastSql();
					//var_dump($_POST);
					echo json_encode($model->where('id=' . $lastid)->find());
					//$this->success('保存成功');
				} else {
					//var_dump($_POST);
					$arr['reply'] = -1;
					$arr['error'] = '失败';
					echo json_encode($arr);
				}
			} else {
				//var_dump($_POST);
				$arr['reply'] = -1;
				$arr['error'] = '有空信息';
				echo json_encode($arr);
			}
		} else {
			$arr['reply'] = -1;
			$arr['error'] = '验证码错误';
			echo json_encode($arr);
		}
	}
	//public function setComment()
	//{}
	public function showArchives($tpl = 'index') {
		if (!isset($_GET['json'])) {
			$this->assign('data', $this->arr);
			//var_dump($this->arr);
			$this->display('tpl/' . $tpl);
		} else {
			echo json_encode($this->arr);
		}

	}
	public function index() {
		$u = M('Users');
		if (isset($_GET['uid'])) {
			$check = $u->where("id=" . $_GET['uid'])->find();
		} else if (isset($_GET['u'])) {
			$check = $u->where("username='" . $_GET['u'] . "'")->find();
		}

		if (sizeof($check) == 0) {
			$this->error('没有找到对应的用户');
		} else {

			$this->getBlogSetting($check);

			$this->sql_one   = 'ispublish=0 and showid=-1 and userid=' . $this->uid;
			$this->sql_muilt = 'a.ispublish=0 and a.showid=-1 and a.userid=' . $this->uid;
			//定义数据库中 ispublish字段 1为草稿 0为发布；showid字段 -1为全部可见 0为好友可见 1为本人可见；
			$this->getTops();
			$this->getTags();
			$this->arr['YearM']    = $this->getGroupByDate();
			$this->arr['Category'] = $this->getCategory();

			if (isset($_GET['cat'])) {
				$this->arr['Archive']  = $this->getArchivies($_GET['cat'], 'cat');
				$this->arr['PageType'] = '/cat/' . $_GET['cat'];
				$this->showArchives();
			} elseif (isset($_GET['p'])) {
				$this->arr['Archive']      = $this->getArchive($_GET['p']);
				$this->arr['Comments']     = $this->getComments($_GET['p']);
				$this->arr['CommentCount'] = sizeof($this->arr['Comments']);
				$this->showArchives('archive');
			} elseif (isset($_GET['ml'])) {
				$this->arr['PageType'] = '/ml/' . $_GET['ml'];
				$this->arr['Archive']  = $this->getArchivies($_GET['ml'], 'ml');
				$this->showArchives();
			} elseif (isset($_GET['s'])) {
				$this->arr['Archive'] = $this->getArchivies($_GET['s'], 's');
				$this->showArchives();
			} else {
				$this->arr['PageType'] = '';
				$this->arr['Archive']  = $this->getArchivies();
				$this->showArchives();
			}

		}
	}
}