<?php
/*
 +----------------------------------------------------------------------
 | TEMMOKUMVC [ NO BEST , ONLY BETTER ]
 +----------------------------------------------------------------------
 | Copyright (c) 2018~2019 https://www.temmoku.cn All rights reserved.
 +----------------------------------------------------------------------
 | Author: 张宗强 Email:webmaster@temmoku.cn QQ:158726877 516669373 TEL:17895221001 微信:temmokumvc
 +---------------------------------------------------------------------- 
*/
namespace plugin\advertisement\user\controller;
use \temmoku\controller;
use \temmoku\db;
use \temmoku\lib\pages;
use \plugin\advertisement\public_class\cache;
use \plugin\advertisement\init;
class index extends controller{

	
	
	public function index(){
		!isset($_GET['page']) && $_GET['page']=1;
		$rows='20';
		$data=db::select('*')->from(init::$table."list")->where("is_sell='1'")->calcFoundRows()->orderByDESC(['id'])->setPaging($rows)->page($_GET['page'])->query();
		$getlistNUM=db::row(' SELECT FOUND_ROWS() AS allNUM');
		$Get_Page=(new pages)->pages('','',user_plugin_url."/index/index/",$rows,$_GET['page'],$getlistNUM['allNUM'],'/');
		
		
		$this->assign('data', $data);
		$this->assign('Get_Page',$Get_Page);
		$this->display(tpl('index/index'));
	}
	
	public function buy(){
		
		$data=C(init::$dir.'|ad_list.'.$_GET['tag']);
		if(!$data){
			$this->err('不存在的广告位置');
		}
		$data=\unserialize($data);
		if(!$data['is_sell']){
			$this->err('此广告位置禁止购买');
		}
		$row=db::select('bid,count(bid) As num')->from(init::$table.'buy_list ')->where("bid= '{$data['id']}' AND endtime >  ".NOWTIME)->row();
		
		if($row['num'] >= $data['sellnum']){
			$this->err('你需要购买的广告位已经没有位置可以提供，请联系客服操作');
		}
		
		$data['price']=\unserialize($data['price']);
		$data['msg']=str_replace ( PHP_EOL ,'<br />' , $data['msg'] );
		//获取支付配置
		$payment_path=APP_PATH_PLUG."payment/conf";
		load_conf($payment_path);
		$this->assign('data',$data);
		$this->display(tpl('index/buy'));
	}
	
	public function create_order(){
		$data=C(init::$dir.'|ad_list.'.$_POST['tag']);
		$data=\unserialize($data);
		if(!$data){
			exit(json_encode(['code'=>999,'text'=>'不存在的广告位']));
		}
		
		if(!$data['is_sell']){
			exit(json_encode(['code'=>999,'text'=>'此广告位不在出售之列']));
		}
		
		
		$row=db::select('bid,count(bid) As num')->from(init::$table.'buy_list ')->where("bid= '{$data['id']}' AND endtime >  ".NOWTIME)->row();
		
		if($row['num'] >= $data['sellnum']){
			exit(json_encode(['code'=>999,'text'=>'你来晚了一步，你需要购买的广告位已经没有位置可以提供']));
		}
		
		
		
		if((!C('advertisement|setting.is_integral') || !$data['integral']) && $_POST['integral']){
			exit(json_encode(['code'=>999,'text'=>'后台没有开启积分兑换，或者此广告位不支持积分兑换']));
		}
		
		if($_POST['integral'] && $_POST['integral'] > C('MYDB.integral')){
			exit(json_encode(['code'=>999,'text'=>'抵扣积分大于所拥有积分']));
		}
		$price=\unserialize($data['price']);
		$time=intval($_POST['time']);
		if(!$price['time'][$time]){
			exit(json_encode(['code'=>999,'text'=>'购买的时间不存在']));
		}
		$transaction_code=NOWTIME.rand(1000,9999);
		$array=[
			'uid'=>C('MYDB.uid'),
			'tag'=>$data['tag'],
			'username'=>C('MYDB.username'),
			'integral'=>intval($_POST['integral']),
			'buytime' =>$time,
			
			'rmb' =>$price['price'][$time],
			'transaction_code'=>$transaction_code,
			'posttime'=>NOWTIME
		];
		$id=db::insert(init::$table.'pay_log')->cols($array)->query();
		$rmb=$array['rmb'] - ( $array['integral']/C('advertisement|setting.integral') );
		
		if($array['integral']){
			(new \temmoku\lib\integral)->add(C('MYDB.uid'),-$array['integral'],'购买广告兑换人民币');
		}
		
		exit(json_encode([
			'code'=>0,
			'text'=>'订单创建成功',
			'data'=>[
				'transaction_code'=>$array['transaction_code'],
				'rmb'=>round ($rmb,2),
				'id'=>$id
			]
		]));
	}
	
	public function pay_order(){
		
		$row=db::select('*')->from(init::$table.'pay_log')->where("id= '{$_POST['id']}'")->row();
		
		$data=C(init::$dir.'|ad_list.'.$row['tag']);
		$data=\unserialize($data);
		$_row=db::select('bid,count(bid) As num')->from(init::$table.'buy_list ')->where("bid= '{$data['id']}' AND endtime >  ".NOWTIME)->row();
		
		if($_row['num'] >= $data['sellnum']){
			exit(json_encode(['code'=>999,'text'=>'你来晚了一步，你需要购买的广告位已经没有位置可以提供']));
		}
		
		if(!$row){
			exit(json_encode([
				'code'=>999,
				'text'=>'不存在的订单',
			]));
		}
		
		if($row['state']){
			exit(json_encode([
				'code'=>999,
				'text'=>'此订单已经支付',
			]));
		}
		
		$need_rmb=$row['rmb'] - ( $row['integral']/C('advertisement|setting.integral') );
		
		
		if($_POST['payment']=='rmb'){
			if(!C('Plugin_Route')){
				$Plugin_Route_file=APP_PATH.'plugin_route.php';
				load_conf($Plugin_Route_file);
			}
			if(!in_array('rmb',C('Plugin_Route'))){
				exit(json_encode([
					'code'=>999,
					'text'=>'没有安装rmb插件',
				]));
			}
			$rmb_handle=new \plugin\rmb\public_class\put;
			$rmb_password=$rmb_handle->password(C('MYDB.uid'),$_POST['rmbpassword']);
			if($rmb_password['code'] != 0){
				exit(json_encode($rmb_password));
			}else{
				if(C('mydb.rmb') < $need_rmb){
					exit(json_encode([
						'code'=>999,
						'text'=>'余额不足以支付此次订单',
					]));
				}else{
					$rmb_handle->add(C('mydb.uid'),-$need_rmb,'广告位购买，广告订单为:'.$row['transaction_code']);
					$array=[
						'state'=>1,
						'payment'=>'rmb'
					];
					$id=(new \plugin\advertisement\public_class\payment)->order($row,$array);
					exit(json_encode(['code'=>0,'text'=>'广告位购买成功','id'=>$id]));
				}
			}
		}else{
			$array=[
				'payment'=>$_POST['payment']
			];
			db::update(init::$table.'pay_log')->cols($array)->where("id='{$row['id']}'")->query();
			exit(json_encode(['code'=>0,'text'=>'更改支付方式成功']));
		}
	}
	
	//生成二维码，供PC使用
	public function qrcode(){
		vendor('phpqrcode.phpqrcode');
		error_reporting(E_ERROR);
		$url = WEBURL.'/advertisement/index/pay/id/'.$_GET['id'].C('html');
		\QRcode::png($url,false,'L','6','2');
	}
	
	public function test_pay_state(){
		$row=db::select('*')->from(init::$table.'pay_log')->where("id= '$_GET[id]' ")->row();

		echo $row['state'] ? $row['bid'] : 0;
	}
	
	public function mylist(){
		!isset($_GET['page']) && $_GET['page']=1;
		$rows='20';
		$data=db::select('*')->from(init::$table."buy_list")->where("uid=".C('MYDB.uid'))->calcFoundRows()->orderByDESC(['id'])->setPaging($rows)->page($_GET['page'])->query();
		$getlistNUM=db::row(' SELECT FOUND_ROWS() AS allNUM');
		$datadb=[];
		foreach($data as $row){
			$row['info']=db::select('*')->from(init::$table."list ")->where("id=".$row['bid'])->row();
			if($row['ad_type']=="images"){
				$row['ad_type']="图片类型";
			}elseif($row['ad_type']=="text"){
				$row['ad_type']="文字类型";
			}else{
				$row['ad_type']="代码类型";
			}
			$datadb[]=$row;
		}
		$Get_Page=(new pages)->pages('','',user_plugin_url."/index/mylist/",$rows,$_GET['page'],$getlistNUM['allNUM'],'/');
		$this->assign('getlist', $datadb);
		$this->assign('Get_Page',$Get_Page);
		$this->display(tpl('index/mylist'));
	}
	
	public function edit(){
		$data=db::select('*')->from(init::$table."buy_list")->where("id= '{$_GET['id']}' AND uid=".C('MYDB.uid'))->row();
		if(!$data){
			$this->err('不存的订单数据');
		}
		
		if($data['endtime'] < NOWTIME){
			$this->err('你的广告订单已经过期无法进行关联');
		}
		$data['content']=\unserialize($data['content']);
		if($_POST['step']=='post'){
			
			if($data['ad_type']=='images'){
				if(!$_POST['ad']['imgurl']){
					$this->err('请上传广告图片');
				}
				if( $data['content']['imgurl'] && $_POST['ad']['imgurl'] != $data['content']['imgurl']){
					$oldfile=Temmoku_PATH.C('UPFILES_CATALOG').DS.$data['content']['imgurl'];
					@unlink($oldfile);//删除这个文件
				}
				$_POST['ad']['imgurl']= UploadFiles_MOVE($_POST['ad']['imgurl'],"ad");
			}
			
			$content=\serialize($_POST['ad']);
			db::update(init::$table."buy_list")->cols(['content'=>$content])->where("id='$data[id]'")->query();
			\plugin\advertisement\public_class\cache::ad_cache();
			$this->success('广告修改成功');
		}
		
		
		$data['info']=db::select('*')->from(init::$table."list ")->where("id=".$data['bid'])->row();
		
		$this->assign('data',$data);
		$this->display(tpl('index/edit'));
		
	}
	
	
	public  function cache(){
		$data=db::select('*')->from(init::$table."list")->query();
		
		$datadb=[];
		foreach((array)$data AS $key=>$row){
			$row['setting']=\unserialize($row['setting']);
			//print_r($row);
			if($row['ad_type']=='images' || $row['ad_type']=='text'){
				$buy_list=db::select('*')->from(init::$table."buy_list")->where("bid= '{$row['id']}' AND endtime > '".NOWTIME."'")->query();
				
				$row['adlist']=[];
				foreach($buy_list as $_row){
					$row['adlist'][]=\unserialize($_row['content']);
				}
				
				$buy_list_num=count($buy_list);
				$balance=$row['sellnum'] - $buy_list_num;
				
				if($balance){
					for($i=0;$i<$balance;$i++){
						if($row['ad_type']=='images'){
							$row['adlist'][]=[
								"imgurl"=>$row['setting']['images']['imgurl'][$buy_list_num+$i],
								"weburl"=>$row['setting']['images']['weburl'][$buy_list_num+$i],
							];
						}else{
							$row['adlist'][]=[
								"title"=>$row['setting']['text']['title'][$buy_list_num+$i],
								"weburl"=>$row['setting']['text']['weburl'][$buy_list_num+$i],
							];
						}
					}
				}
			}
			$datadb[$row['tag']]=serialize($row);
		}
		$array=['ad_list'=>$datadb];
		
		createconf($array,'ad',init::$dir,true);
	}
}
?>
