<?php
namespace Cas\Controller;
use Cas\Dao\LotteryData;

use Cas\Dao\LotteryPrize;

use KIF\Core\Request;
use KIF\Verify;
use Cas\Module\LotteryEventsTypeInvitation;
use KIF\Core\Config;
use KIF\String\String;
use KIF\String\Filter;
use Cas\Dao\LotteryEventsForms;
use Cas\Dao\UserInfo;
use Cas\Module\Count;
use Cas\Dao\Platform;
use Cas\Module\Lottery;
/**
 * 
 * 邀请函
 */
class EventsInvitation extends EventsController {
	
	public function doDefault() {
		//$events_id = Request::g('events_id');
		$events_id = $this->getEventsCreateTimeToId();
		if (!Verify::unsignedInt($events_id)) {
			self::fail_exit('无效id');
		}
		
		# 获取用户信息
		$objUserData = new UserInfo();
		$uid = $this->getRunTimeUid();
		$userData = $objUserData -> get($uid);
		$this->setOutput('userData', $userData);
		
		# 获取邀请函信息
 		$objLotteryEventsTypeInvitation = new LotteryEventsTypeInvitation($uid, $events_id);
		$info = $objLotteryEventsTypeInvitation->getEventsData();
		
		# 检查是否移动端
		$title = $info['weixinShare']['title'] ? $info['weixinShare']['title']: $info['events_name'];
		$this->checkIsFromMobile($title);
		
		# 获取登录地址
		$url = Request::g('url');
		$plat_form_id = $this->getPlatFormId();
		$objMLottery  = new Lottery();
		$thisUrl  = $objMLottery -> getEventsUrl($info['type'],$info['create_time'],$url);
		$loginUrl = $this -> getLoginUrl($thisUrl);
		$this->setOutput('loginUrl', $loginUrl);

		# 判断是否需要登录
		$ckLogin = $this->ckLogin();
		$this->setOutput('ckLogin', $ckLogin);
		
		
		
		# 检查当前活动是否需要登录
		$authorize = $info['authorize'];
		if ($authorize && $loginUrl) {
				if($ckLogin==true){
					self::redirect($loginUrl);
				}
		}
		
		# 活动状态
		$TIME = time();
		$eventsStatus = false;
		if($TIME < $info['begin_time'] ){
			$eventsStatus = 'STATUS_NOT_START';
			
		} elseif ($TIME > $info['end_time']){
			$eventsStatus = 'STATUS_HAS_END';
			
		} elseif ($info['display'] == \Cas\Dao\LotteryEvents::EVENT_DISPLAY_HIDE) {
			//$eventsStatus = 'STATUS_HIDE'; //先注释了。此隐藏 之印象列表
		}

		$this->info($info);
		# 记录PV UV日志 访问
		$objCount = new Count();
		$objCount->setPassLog( $events_id,$plat_form_id);
		
		# 视频播放
		preg_match_all('/<embed\s{1}src=\"([^\"]+)\"[^>]+>/i', $info['events_tips'], $matches);
		if ($matches) foreach ($matches[0] as $key => $tmpMatch) {
			$tmp_new_video_html = '<iframe class="video_iframe" height=498 width=510 src="'.$matches[1][$key].'" frameborder=0 allowfullscreen></iframe>';
			$info['events_tips'] = str_replace($tmpMatch, $tmp_new_video_html, $info['events_tips']);
		}
		
		$this->tpl = 'events_invitation';
		$this->setOutput('display', $info['list_display']);
		$this->setOutput('title', $info['weixinShare']['title'] ? $info['weixinShare']['title'] : $info['events_name']);
		$this->setOutput('infos', $info);
		$this->setOutput('forms', $info['forms']);
		$this->setOutput('weixinShare', $info['weixinShare']);
		$this->setOutput('eventsStatus', $eventsStatus);
	}
	
	public function doSub() {
		
		# 1.必要参数验证
		$uid = $this->getRunTimeUid();
		if (!Verify::unsignedInt($uid)) {
			self::ajax_fail_exit('无效用户id');
		}
		$events_id = Request::g('events_id');
		if (!Verify::unsignedInt($events_id)) {
			self::ajax_fail_exit('无效活动id');
		}
		
		$objLotteryEventsTypeInvitation = new LotteryEventsTypeInvitation($uid, $events_id);
		$eventsData = $objLotteryEventsTypeInvitation->getEventsData();
		
		# 获取登录地址
		$plat_form_id = $this->getPlatFormId();
		$objPlatForm  = new Platform();
		$form = $objPlatForm -> get($plat_form_id);
		$url = $form['url'];
		$objMLottery  = new Lottery();
		$thisUrl  = $objMLottery -> getEventsUrl($eventsData['type'],$eventsData['create_time'],$url);
		$loginUrl = $this -> getLoginUrl($thisUrl);
		
		# 判断是否登录
		$authorize = $eventsData['authorize'];
		if ($authorize && $loginUrl) {
			$ckLogin = $this->ckLogin();
			if($ckLogin==true){
				self::ajax_fail_exit(array('url' =>$loginUrl));
			}
		}
		
		# 3.活动信息&用户行为验证
		$tmpData = $objLotteryEventsTypeInvitation -> submitUser();
		if (!$tmpData->isSuccess()) {
			self::ajax_fail_exit($tmpData->getData());
		}
		
		# 4.用户表单验证
		$info = $objLotteryEventsTypeInvitation->getEventsData();
		$eventData = $info;
		$forms = $info['forms'];
		$formData = Filter::arrayfilter($_POST, true);
		
		$objLotteryEventsForms = new LotteryEventsForms();
		$tmpVerifyResult = $objLotteryEventsForms->verifyFormData($forms, $formData);
		if (!$tmpVerifyResult->isSuccess()) {
			self::ajax_fail_exit($tmpVerifyResult->getData());
		}
		
		# 5.记录用户提交表单
		$info = array_merge($formData, array('uid' => $uid, 'events_id' => $events_id));
		$formId = $objLotteryEventsForms->add($info);
		if (!$formId) {
			self::ajax_fail_exit('数据库操作失败');
		}
		
		# 6.记录用户“我的奖品”
		$objDLotteryData = new LotteryData();
		$thisTime = time();
		$info  = array(
				'events_id' => $events_id,
				'prize_id' => 0,
				'uid' => $uid,
				'audit' => 1,//未审核
				'winners_time' => $thisTime,
				'winning_time' => $thisTime,
				'run_time_data' => array(
					'events' => $eventData,
					'prize' => array(
						0 => array(
							'events_id' => $this->eventsId,
							'prize_name'  =>$eventData['events_name'],
							'img_url' => '/public/static/img/qricon.png',
							'type' => LotteryPrize::TYPE_ENTITY,
						)
					),
				),
				'virtual_data' => "/?c=EventsInvitation&a=Qrcode&events_id={$events_id}&formsId={$formId}",
		);
		$objDLotteryData -> add($info);
		
		# 7.记录用户参与行为
		$objLotteryEventsTypeInvitation -> setLimitations();
		
		self::ajax_success_exit($formId);
	}
	
	public function doQrcode() {
		$App_Path = Config::getInstance()->get('App_Path');
		include_once $App_Path . DS . 'include/phpqrcode/phpqrcode.php';
		
		$uploadConfig = Config::getInstance()->get('upload');
		$IMG_UPLOAD_PATH = $uploadConfig['path'] . DS . 'qrcode';
		$IMG_UPLOAD_URL = $uploadConfig['url'] . DS . 'qrcode';
		
		if (!file_exists($IMG_UPLOAD_PATH)) {
			if (!mkdir($IMG_UPLOAD_PATH, 0775, true)) {
				self::fail_exit('创建二维码失败,原因:图片目录不存在');
			}
		}
		
		$TIME = time();
		$filename =  $TIME . 'png';
		
		$uid = $this->getRunTimeUid();
		$events_id = Request::g('events_id');
		$formsId = Request::g('formsId');
		
		$objLotteryEventsTypeInvitation = new LotteryEventsTypeInvitation($uid, $events_id);
		$token = $objLotteryEventsTypeInvitation->getQrcodeUrlToken();
		$data = String::jointUrl(Request::schemeDomain(), array(
			'c'		=> 'QrcodeData',
			'a'		=> 'Invitation',
			'uid'	=> $uid,
			'events_id'	=> $events_id,
			'formsId'	=> $formsId,
			'token'	=> $token,
		));
		
		\QRcode::png($data, $IMG_UPLOAD_PATH . DS . $filename, 3, 6);
		$imgUrl = $IMG_UPLOAD_URL . DS . $filename;
		
		$info = $objLotteryEventsTypeInvitation->getEventsData();
		
		# 获取登录地址
		$plat_form_id = $this->getPlatFormId();
		$objPlatForm  = new Platform();
		$form = $objPlatForm -> get($plat_form_id);
		$url = $form['url'];
		
		# 列表页URL
		$this->setOutput('listUrl', Request::schemeDomain().'/list/'.$url);
		# 我的礼品URL
		$this->setOutput('giftsUrl', Request::schemeDomain().'/list/'.$url.'/member/gifts');
		
		
		
		$this->tpl = 'save_qrcode';
		$this->setOutput('title', '保存二维码');
		$this->setOutput('imgUrl', $imgUrl);
		$this->setOutput('info', $info);
	}
	
	public function display() {
		return $this->render();
	}
	
}