<?php
defined('PP_PATH') or exit;
class book_control extends user_control{
	public $_navgroup = 'book';
	private $_table = 'cms_book';
	private $_protable = 'cms_products';
	
	// public function __construct(){
		// parent::__construct();
		// $topcid = $this->category->get_smallid_upid(2,10);
		// $this->assign('topcid', $topcid);
	// }
	
	//订单列表
	public function index(){
		$this->assign_value('navkey', 'book-index');

		// 初始模型表名
		$this->cms_content_book->table = $this->_table;
		
		// 初始分页
		$where['uid'] 				= $this->_uid;
		$pagenum = 5;

		$total = $this->cms_content_book->find_count($where);
		
		$maxpage = max(1, ceil($total/$pagenum));
		$page = min($maxpage, max(1, intval(R('page'))));
		$pages = pp_pages($page, $maxpage, 'index.php?u=book-index-page-{page}');
		$this->assign('total', $total);
		$this->assign('pages', $pages);

		$cms_arr = $this->cms_content_book->list_arr($where, 'id', -1, ($page-1)*$pagenum, $pagenum, $total);
		foreach($cms_arr as &$v) {
			$this->cms_content_book->formatbook($v);
		}
		$this->assign('lists', $cms_arr);
		$this->display('book.htm');
	}
	//处理3天后默认好评
	public function auto_comment(){
		$oid = htmlspecialchars(trim(R('oid', 'P')));
		$bookdata = $this->cms_content_book->get_by_oid($oid);
		if(empty($bookdata['is_comments'])){
			$threetime = $bookdata['dateline']  + 86400 * 3 ;
			if($threetime < time()){
				$this->cms_content_book->auto_comments($bookdata);
			}
		}
	}
	//提交订单
	public function test(){
		$test  = $this->cms_content_book->tuan_ok(5,15,'test');
		//print_R(order_number());
	}
	public function add_ajax(){
		if(empty($_POST) ){
			E(1, 'error');
		}else{
			$data = R('book','P');

			//读取资源参数
			$this->cms_content->table = $this->_protable;
			$pro = $this->cms_content->get($data['pid']);
			if(empty($pro)) E(1, '非法参数！此资源不存在');

			$_viprice = $pro['price'] ;

			if($pro['zk_end'] > time() && $pro['zk_start']<time()){//限时优惠期
				$_price = $pro['zk_price'] ;
			}else{
				$_price = $pro['price'] ;
			}
			
			$notice = '';
			//VIP价格
			if($this->_group['percent']){
				$notice	= ' '.$this->_group['groupname'].$this->_group['percent'].'折优惠';
				//$_viprice = intval($_viprice * $this->_group['percent'] / 10) ;	//原价基础上打折
				$_viprice = number_format($_viprice * $this->_group['percent'] / 10, 2, ".", "") ;
				//$_viprice = intval($_price * $this->_group['percent'] / 10) ;	//限时折扣基础上再打折－折上折
			}
			$_price = min($_price,$_viprice); //始终取一个最小价格
			//E(1, $_price);

			$_totalprice = $_price * 1 ;
			if($_totalprice > $this->_user['money']){ //余额不足
				E(1, '你的余额不足！请先充值');
			}
			
			//扣除用户余额
			$userdate = array(
				'uid' 			=> $this->_user['uid'],
				'money' 		=> $this->_user['money'] - $_totalprice,
				'mobile_staus' 	=> $this->_user['mobile_staus'], //must
				'mobile' 		=> $this->_user['mobile'],
			);

			if(!$this->user->update($userdate)){
				E(1, '用户余额更新失败');
			}
		
			$comment = '下单成功'.$notice;
			
			//生成订单号
			$orderid = order_number();

			//订单入库
			$info = array(
				'cid' 			=> intval($data['cid']),
				'pid' 			=> intval($data['pid']),
				'order_id' 		=> $orderid,
				'uid' 			=> $this->_uid,
				'price' 		=> floatval($_price),
				'totalprice' 	=> floatval($_totalprice),
				'ordernum' 		=> 1,
				'dateline' 		=> $_ENV['_time'],
			);
			
			$this->cms_content_book->table = $this->_table;
			$id = $this->cms_content_book->create($info);
			$record 	= &$this->record;
			if(!$id) {
				E(1, '写入订单表出错');
			}else{
				//写入消费记录
				if($_totalprice>0){
					$recordata 	= array(
						'uid'		=> $this->_uid,
						'username'	=> $this->_user['username'],
						'money'		=> $_totalprice,
						'gold'		=> 0,
						'type'		=> 2,
						'order_id'	=> $orderid,
						'created'	=> $_ENV['_time'],
						'status'	=> 0,
						'comment'	=> $comment,
					);
					if(!$record->create($recordata)){
						E(1, '交易记录写入失败');
					}
				}
				//更新上线提成
				if($this->_user['upid'] && $this->_cfg['user']['open_sem']){
					$upuser = $this->user->get($this->_user['upid']);
					$user_group 	= &$this->user_group;
					$upuser_group = $user_group->get($upuser['groupid']);
					$user_group->format($upuser_group);
					
					if(!empty($upuser_group['sem'])){
						//$_sem = intval($_totalprice * $upuser_group['sem'] / 100);
						$_sem = number_format($_totalprice * $upuser_group['sem'] / 100, 2, ".", "") ;
						if($_sem > 0){
							$upuser['money']	= $upuser['money'] + $_sem ;
							$this->user->update($upuser) ;

							$_recordata 	= array(
								'uid'		=> $upuser['uid'],
								'username'	=> $upuser['username'],
								'money'		=> $_sem,
								'gold'		=> 0,
								'type'		=> 4,	//1 充值 2消费 3提现　4提成
								'order_id'	=> $orderid,
								'created'	=> $_ENV['_time'],
								'status'	=> 0,
								'comment'	=> '下线“'.$this->_user['username'].'消费提成(￥'.$_totalprice.')”',
							);
							$record->create($_recordata);
						}
					}
				}
			}
			//更新资源销量
			$pro['sells'] 	= $pro['sells'] + $data['ordernum'] ;
			if(!$this->cms_content->update($pro)) {
				E(1, '更新资源销售数量失败');
			}
			E(0, '成功');
		}
	}
	//下载
	public function down(){
		$pid 		= (int)R('pid','P');
		$aid 		= (int)R('aid','P');

		$this->cms_content_book->table = $this->_table;

		$this->cms_content->table = $this->_protable;
		$pro = $this->cms_content->get($pid);
		empty($pro) && $this->message(0,'找不到对应的资源数据');
		
		$attch 		= $this->cms_attach->get($aid);
		$downurl	= 'upload/products/'.$attch['filepath'];

		if($this->cms_content_book->isBuyed($pid) || ($pro['price'] == 0 && $pro['need_groupid'] <= $this->_group['groupid']) || !empty($this->_group['issuper'])){
			if(file_exists(PP_PATH.$downurl)) {
				//$attch['downloads']++;
				//$this->cms_attach->update($attch);
				
				$fileInfo = pathinfo(PP_PATH.$downurl);
				$mimeTypes = array (
					'zip' => 'application/zip'
				);
				
				if(isset($mimeTypes[$fileInfo['extension']])) {
					header('Content-Type: '.$mimeTypes[$fileInfo['extension']]);
				} else {
					header('Content-Type: application/octet-stream');
				}
				
				header('Content-Disposition: attachment; filename="'.$attch['filename'].'"');
				header("Content-Length:".filesize(PP_PATH.$downurl));
				header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
				header('Pragma: public');
				header("Content-Transfer-Encoding: binary");
				header('Expires: 0');
				header('Content-Description: '.' Download');
				@ob_clean();
				@flush();
				
				readfile(PP_PATH.$downurl) or $this->message(0,'ERROR');;
				die();
			}
		}else{
			$this->message(0,'下载出错了');
			//header("HTTP/1.0 404 Not Found");
			//header("Location: http://". DOMAIN ."/error");
		}
	}
	public function del(){
		$order_id 	= htmlspecialchars(trim(R('oid', 'P')));

		$where['order_id'] 	= $order_id;
		$where['uid'] 		= $this->_uid;
		
		$this->cms_content_book->table = $this->_table;
		$book 	= $this->cms_content_book->get_by_oid($order_id);
		
		empty($book) && E(1, '找不到此订单');
		
		$status = $this->cms_content_book->find_delete($where);
		if($status){
			E(0, '删除成功');
		}else{
			E(1, '删除失败！');
		}
	}
}