<?php
//控制器：ReviewAction
class ReviewAction extends Action{
	//方法：index
	public function index(){

	}


	public function add(){
		header("Content-Type:text/html; charset=utf-8");
		if (!IS_AJAX ||  !IS_POST) {
			//exit(json_encode( array('status' => 0, 'info' => '非法請求' ) ));
			$this->error('非法請求');
		}
		//M驗證
		$data['postid'] = I('post_id', 0, 'intval');
		$data['modelid'] = I('model_id', 0, 'intval');
		$data['pid'] = I('review_id', 0, 'intval');
		$data['title'] = I('title', '');
		$data['content']  = I('content', '');
		$data['posttime'] =time();
		$data['ip'] = get_client_ip();		
		$data['agent'] = $_SERVER['HTTP_USER_AGENT'];

		
		$verify = I('vcode','','md5');
		if (C('cfg_verify_review') == 1 && $_SESSION['verify'] != $verify) {
			$this->error('驗證碼不正確');
		}

		$uid = get_cookie('uid');//不能用empty(get_cookie('uid')),empty不能用於函數返回值
		if (!empty($uid)) {
			$data['userid'] = $uid;
			$data['email'] = get_cookie('email'); 
			/*
			if(get_cookie('nickname') != '') {
				$data['username'] = get_cookie('nickname');
			} else {
				$data['username'] = preg_replace('/(\w+)\@(\w+)\.(\w+)/is',"$1@*.$3",get_cookie('email'));
			}
			*/
			$data['username'] = get_cookie('nickname');
					
		}else {
			$data['userid'] = 0;			
			$data['username'] = I('nickname', '遊客');		
			$data['email'] =I('email', '', 'htmlspecialchars,trim');
		}
		if ($data['userid'] == 0 &&  !C('cfg_feedback_guest')) {//允許匿名評論
			$this->error('請登錄後評論');
		}

		if(empty($data['postid']) || empty($data['modelid'])) {
			$this->error('參數錯誤');
		}

		if(empty($data['title'])) {
			$this->error('文章不正確，請刷新再評論');
		}
		
		if(empty($data['content']) || mb_strlen($data['content'], 'utf-8')<3) {
			$this->error('請填寫評論內容，內容太短');
		}

		if (checkBadWord($data['content'])) {
			$this->error('評論內容包含非法信息，請認真填寫！');
		}

	

		if($id = M('comment')->add($data)) {
			//$this->success('添加成功',U(GROUP_NAME. '/Guestbook/index'));
			$list= array(
				//'status' => 1,
				'id' => $id,
				'user_id' => $data['userid'],				
				'review_id' => $data['pid'],
				'username' => $data['username'],
				'ico' => '',
				'avatar' => get_avatar(get_cookie('face'),30),
				'content' => $data['content'],
				'posttime' => date('Y-m-d H:i:s', time())
			);
			$furl = $_SERVER['HTTP_REFERER'];
			//exit(json_encode($list));
			$this->success('添加成功', $furl, $list);
		}else {			
			$this->error('添加失敗'.M('comment')->getError());
		}
	
	}


	public function getlist() {

		header("Content-Type:text/html; charset=utf-8");//不然返回中文亂碼
		if (!IS_AJAX) {
			//exit('非法請求');
		}

		$postid = I('post_id', 0, 'intval');
		$modelid = I('model_id', 0, 'intval');
		$pageSize = I('num', 2, 'intval');
		$page = I('page', 1, 'intval');
		$avatar = I('avatar', 'middle');
		$userid = get_cookie('uid');
		$userid = empty($userid) ? '0' : get_cookie('uid');

		$count = D('CommentView')->where(array('pid' => 0, 'postid' => $postid , 'modelid' => $modelid ))->count();
		if($count % $pageSize) {
			$pageCount = (int)($count / $pageSize) + 1;//如果有餘數，則頁數等於總數據量除以每頁數的結果取整再加一
		}else {
			$pageCount =$count / $pageSize;
		}
		$page = $page > $pageCount ? $pageCount : $page;
		$page = $page < 1 ? 1 : $page;

		$data = D('CommentView')->where(array('pid' => 0, 'postid' => $postid , 'modelid' => $modelid ))->order('comment.id DESC')->limit(($page - 1)* $pageSize ,$pageSize)->select();
		if (empty($data )) {
			$data = array();
		}
		$list = array(
			'count' => $count,
			'avatar' => get_avatar(get_cookie('face'),30),
			'user_id' => $userid,
			'guest' => intval(C('cfg_feedback_guest')),
			//'sql' => M('comment')->getlastsql(),
			//'review' => ''
		);
		$list['list'] = array();
		$ids = array();//所有id為下面的查詢的pid

		foreach ($data as $k => $v) {
			$list['list'][] = array(
				'id' => $v['id'],
				'user_id' => $v['userid'],
				'username' => $v['username'],
				'ico' => '',
				'avatar' => get_avatar($v['face'],30),
				'content' => $v['content'],
				'posttime' => date('Y-m-d H:i:s', $v['posttime']),
				'child' => array(),//後面就不用初始化
			);
			$ids[] = $v['id'];
		}

		//評論回復
		
		if (!empty($ids)) {
			$data = D('CommentView')->where(array('pid' => array('in', $ids), 'postid' => $postid , 'modelid' => $modelid ))->order('comment.id')->select();
	
		
			if (!empty($data)) {
				foreach ($list['list'] as $k => $v) {					
					foreach ($data as $k2 => $v2) {
						if ($v['id'] == $v2['pid']) {
							$list['list'][$k]['child'][] = array(
								'id' => $v2['id'],
								'user_id' => $v2['userid'],
								'review_id' => $v2['pid'],
								'username' => $v2['username'],
								'ico' => '',
								'avatar' => get_avatar($v2['face'],30),
								'content' => $v2['content'],
								'posttime' => date('Y-m-d H:i:s', $v2['posttime'])
							);

							unset($data[$k2]); //刪除已經認領元素,減少內循環
						}
					}
				}
			}
		}

		
		unset($data);
		exit(json_encode($list));

	}




}

?>