<?php
defined('PP_PATH') or exit;
class golds_control extends user_control{
	public function post() {
		$oid = htmlspecialchars(trim(R('oid', 'P')));
		$gold = intval(R('gold', 'P'));
		$content = htmlspecialchars(trim(R('content', 'P')));
		empty($content) && E(1, '内容不能为空！');
		strlen($content)>800 && E(1, '内容太长了！');

		$this->cms_content_book->table = 'cms_book';
		$bookdata = $this->cms_content_book->get_by_oid($oid);
		
		$mgolds = &$this->models->cms_content_golds;
		$mgolds->table = 'cms_products_golds';
		$data = $mgolds->get($bookdata['pid']);

		$data['gold'] 	= number_format(($data['gold'] * $data['golder'] + $gold)/($data['golder'] + 1),1);
		$data['golder'] = $data['golder'] + 1;

		if(!$mgolds->update($data)){
			E(1, '写入评分出错');
		};
		//更新订单已评论状态
		$bookdata['is_comments'] = 1 ;
		if(!$this->cms_content_book->update($bookdata)){
			E(1, '订单状态更新出错');
		};
		
		//添加评论内容
		$mid = $this->category->get_mid_by_cid($bookdata['cid']);
		$maxid = $this->cms_comment->create(array(
			'id' 		=> $bookdata['pid'],
			'mid' 		=> $mid,
			'uid' 		=> $this->_uid,
			'author' 	=> $this->_user['username'],
			'content' 	=> $content,
			'ip' 		=> ip2long(ip()),
			'dateline' => $_ENV['_time'],
			'status' => $this->_cfg['comment_status'],
		));
		if(!$maxid) {
			E(1, '写入评论表出错！');
		}
		if($this->_cfg['comment_status'] < 1){ //如果不需要审核，内容的评论数量+1
			$this->cms_content->table = 'cms_products';
			$prodata = $this->cms_content->get($bookdata['pid']);
			$prodata['comments']++;
			if(!$this->cms_content->update($prodata)) {
				E(1, '写入内容表出错！');
			}
		}
		if($this->_uid){
			$user = $this->user->read($this->_uid);
			$user['comments'] += 1;
			if(!$this->user->update($user)){
				E(1, '更新用户评论数出错！');
			};
		}
		E(0, '发布成功！感谢您的评价！');
	}
}
