<?php

namespace Cas\Controller;

use KIF\Core\Request;
use KIF\Cookie;
use Cas\Module\User;
use KIF\Core\Config;
use KIF\String\String;
use Cas\Dao\Platform;
use Cas\Dao\LotteryEvents;
use KIF\Math\Math;
use Cas\Module\Lottery;

use Cas\Module\LotteryLog;
use Cas\Dao\LotteryUserFeedback;
use Cas\Dao\LotteryData;
use Cas\Dao\UserInfo;
use KIF\Dao\SqlHelper;
use Cas\Dao\Focus;
use Cas\Dao\LotteryUserExpress;

use Cas\Dao\LotteryUserHelp;
use Cas\Dao\LotteryUserHelpLog;

/**
 * 活动页面的控制器
 *
 * @author lihuanchun
 *        
 */
class EventsController extends Controller {
	private $userCookieName = "USER_INFO";
	private $key;
	public function __construct() {
		$this->key = Config::getInstance ()->get ( 'passport_sign_key' );
		// 初始化一个本站用户
		$cookieInfo = Cookie::get ( $this->userCookieName );
		
		if (! $cookieInfo) {
			$objMUser = new User ();
			$uid = $objMUser->initUser ();
			$userinfo = $objMUser->get ( $uid );
			$userinfo ['sign'] = $this->createSign ( $userinfo );
			$json_data = json_encode ( $userinfo, true );
			Cookie::set ( $this->userCookieName, $json_data, 60 * 60 * 24 * 29, '.' . $_SERVER ['HTTP_HOST'] );
		}
		
		// 平台信息
		$objPlatform = new Platform ();
		$plat_form_id = $this->getPlatFormId ();
		$platform = $objPlatform->get ( $plat_form_id );
		$this->setOutput ( 'platform', $platform );
		// 列表页URL
		$this->setOutput ( 'listUrl', Request::schemeDomain () . '/list/' . $platform ['url'] );
		// 我的礼品URL
		$this->setOutput ( 'giftsUrl', Request::schemeDomain () . '/list/' . $platform ['url'] . '/member/gifts' );
	}
	
	/**
	 * 获取当前用户
	 */
	public function getRunTimeUid() {
		$cookieInfo = html_entity_decode ( Cookie::get ( $this->userCookieName ) );
		$cookieInfo = json_decode ( $cookieInfo, true );
		return $cookieInfo ['id'];
	}

	/**
	 * 获取活动基本信息
	 */
	public function info($info) {

		$this->objMLottery  = new Lottery();

		# 剩余天数
		$TIME = time();
		$rday = ($info['end_time'] - $TIME) / (24 * 60 * 60);
		$info['rday'] = ceil($rday);
		# 参与人数
		$objMLotteryLog = new LotteryLog ( null, $info['id'] );
		$info['user_total'] = $objMLotteryLog->getUserParticipateLogNumGroupByUid ();

		# 阅读人数


		# 获取登录地址
		$url = Request::g('url');
		$plat_form_id = $this->getPlatFormId();
		$thisUrl  = $this->objMLottery -> getEventsUrl($info['type'],$info['create_time'],$url);
		$loginUrl = $this -> getLoginUrl($thisUrl);
		$info['thisUrl'] = $thisUrl;
		$this->setOutput('loginUrl', $loginUrl);

		# 判断是否需要登录
		$ckLogin = $this->ckLogin();
		$this->setOutput('ckLogin', $ckLogin);

		
		# 获取用户信息
		$objUserData = new UserInfo();
		$uid = $this->getRunTimeUid();
		$userData = $objUserData -> get($uid);
		$userData['headimgurl'] = $this->getUserHead($userData);
		$this->setOutput('uid', $uid);
		$this->setOutput('userInfo', $userData);

		$source_user = Request::g('source_user');
		if (!$source_user) {
			$source_user = $uid;
		}
		$this->setOutput('source_user', $source_user);
		if ($source_user != $uid) {
			$userData = $objUserData -> get($source_user);

			$userData['headimgurl'] = $this->getUserHead($userData);
		}
		if (!$userData['nickname']) {
			$userData['nickname'] = '福利社网友';
		}
		$this->setOutput('userSourceInfo', $userData);

		$info['end'] = 1; //未过期
		if ($TIME > $info['end_time']) {
			$info['end'] = 2;//已过期
		}

		# 抽奖、优惠券、邀请、试用
		$type = array(1,4,6,7);
		if (in_array($info['type'], $type)) {
			$info['prize'] = 1;
			//$info['authorize'] = true; //强制登录
		} else {
			$info['top_data'] = 1;
		}

		# 检查当前活动是否需要登录
		$info['login'] = 1;
		$authorize = $info['authorize'];
		if ($authorize) {
				if($ckLogin==true){
					$info['login'] = 2;//需要登录
					//self::redirect($loginUrl);
				}
		}

		# 如果是试用,判断评价
		$condition = array('events_id' => $info['id'],'audit' => 2, 'uid' => $uid,'scratch_receive' => LotteryData::EVENT_SCRATCH_RECEIVE_TRUE);
		$offset = 0;
		$size = 1;
		$order = 'id desc';
		$userData = $this->objMLottery->getOnesLotteryData($condition);
		if ($userData) {
			$userData['feedback'] = 1;//不需要填写反馈
			$userData['url'] = base64_encode($info['thisUrl']);
		}

		if ($info['type'] == 4) {
			$info['feedback'] = 1;
			if ($userData) {
				$objLotteryUserFeedback = new LotteryUserFeedback();

				if (isset($userData['express']) && $userData['express']) {
					$userData['feedback'] = 2;//未填写反馈
					$where = array();
					$where['uid'] = $userData['uid'];
					$where['events_id'] = $userData['run_time_data']['events']['id'];
					$where['status'] = 1;
					
					$ids = $objLotteryUserFeedback->findIdsBy ( $where, 1, $order = ' id desc');
					if ($ids) {
						$userData['feedback'] = 3;//已填写反馈
					}
				} else {
					$userData['feedback'] = 4;//未填写收货地址
				}
			}
			
		}

		$order = '`index` desc, id desc';
		$limit = '0,5';
		$condition = array ('platform_id' => $plat_form_id);
		$objFocus = new Focus ();
		$ids = $objFocus->findIdsBy ( $condition, $limit, $order );
		$focusData = $objFocus->gets ( $ids );

		$ad = false;
		if (isset($this->platform['ad'])) {
			$ad = $this->platform['ad'];
		}

		$this->setOutput('ad', $ad);
		$this->setOutput('focusData', $focusData);
		$this->setOutput('userData', $userData);
		$this->setOutput('info', $info);

		$type = Request::g('type');

		if ($type == 'share') {
			# 分享
			$this->share($info, $plat_form_id, $source_user);
		} elseif ($type == 'prize') {
			# 获得福利
			$this->prize($info, $plat_form_id, 10, false);
		} elseif ($type == 'feedback') {
			# 获得评价信息
			$this->feedback($info, $plat_form_id, 10, false);
		}

		$this->setOutput('type', $type);
		$ajax = Request::g('ajax');
		if ($ajax == 'ajax') {
			$this->tpl = 'ajax_events';
			$this->ajax_success_exit($this->render(true));
			die;
		}
	}

	public function share($eventsData, $plat_form_id, $uid)
	{
		$events_id = $eventsData['id'];
		$condition = array (
			'events_id' => $events_id,
			'uid' => $uid,
		);
		$objLotteryUserHelp = new LotteryUserHelp();
		$info = $objLotteryUserHelp->fetchOne ( $condition);
		if (!$info) {
			$id = $objLotteryUserHelp->add ( $condition);
		} else {
			$id = $info['id'];
		}
		if ($id) {
			$objLotteryUserHelpLog = new LotteryUserHelpLog();

			$condition = array (
				'events_id' => $events_id,
				'help_id' => $id,
			);

			$total_num = $objLotteryUserHelpLog->totals ( $condition );

			$ids = $objLotteryUserHelpLog->findIdsBy ( $condition, '0,50', 'id desc' );
			$helpData = $objLotteryUserHelpLog->gets ( $ids );

			if ($helpData) {
				foreach ($helpData as $k => $v) {
					$helpData[$k]['headimgurl'] = $this->getUserHead($v['uid']);
				}
			}

			$session = $this->shareSession($id, $uid);
			$this->setOutput('help_session', $session);
			$this->setOutput('help_id', $id);
			$this->setOutput('helpData', $helpData);
			$this->setOutput('helpDataTotal', $total_num);
		}
	}

	public function shareSession($id, $uid, $source_session = false)
	{
		$key = 'onepage2999';
		$session = md5($id . '_' . $key . '_' . $uid);
		if ($source_session) {
			if ($source_session == $session) {
				return true;
			} else {
				return false;
			}
		} else {
			return $session;
		}
	}

	public function feedback($eventsData, $plat_form_id, $limit = 10, $uid = false)
	{
		$objFeedBack = new LotteryUserFeedback ();
		$page = Request::varGetInt ( 'page', 1 );
		$size = $limit;
		$offset = ($page - 1) * $size;
		$limit = "{$offset},{$size}";
		$order = ' id desc';

		$condition = array (
				'events_id' => $eventsData['id'],
				'status' => 1,
		);
		$ids = $objFeedBack->findIdsBy ( $condition, $limit, $order );
		$data = $objFeedBack->gets ( $ids );
		$total_num = $objFeedBack->totals ( $condition );

		$uids = array();
		if ($data) {
			foreach ($data as $k => $v) {
				$uids[] = $v['uid'];
			}
			# 通过UIDs 获取用户信息
			$objMUser = new User();
			$users = $objMUser -> gets($uids);
		}
		
		if ($data) {
			$data = $this->userData($data, $eventsData);
		}

		$this->setOutput('fdData', $data);
		$this->setOutput('fdDataTotals', $total_num);
	}

	public function prize($eventsData, $plat_form_id, $limit = 10, $uid = false)
	{
		$condition = array('audit' => 2, 'platform_id' => SqlHelper::addCompareOperator('&', $plat_form_id), 'scratch_receive' => LotteryData::EVENT_SCRATCH_RECEIVE_TRUE);

		if (isset($eventsData['id'])) {
			$condition['events_id'] = $eventsData['id'];
		}
		if ($uid) {
			$condition['uid'] = $uid;
		}
		$totals = $this->objMLottery -> getLotteryDataListNum($condition);

		$page = Request::varGetInt ( 'page', 1 );
		$size = $limit;
		$offset = ($page - 1) * $size;
		$order = 'update_time desc';
		$data = $this->objMLottery->getLotteryDataList($condition,  "{$offset},{$size}", $order);

		if ($data) {
			$data = $this->userData($data, $eventsData);

			$this->setOutput('userEventsData', $data);
			$this->setOutput('userEventsDataTotals', $totals);
		}
	}

	public function userData($data, $eventsData)
	{
		$uids = array();
		foreach ($data as $k => $v) {
			$uids[] = $v['uid'];
		}
		# 通过UIDs 获取用户信息
		$objMUser = new User();
		$users = $objMUser -> gets($uids);

		$objLotteryUserExpress = new LotteryUserExpress();
		$condition = array(
			'uid' => $uids
		);
		$tmpUserExpIds = $objLotteryUserExpress->findIdsBy($condition);
		$userExpData = $objLotteryUserExpress -> gets($tmpUserExpIds);
		$newUserExpData = array();
		foreach($userExpData as $k => $v){
			$newUserExpData[$v['uid']] = $v;
		}
		$this->setOutput('newUserExpData', $newUserExpData);

		//138****1234 的用户 2018.4.20 15:10 获得 某某某某活动 奖品。
		foreach ($data as $k => $v) {

			if (isset($v['pic'])) {
				$data[$k]['pic'] = explode(',', $v['pic']);
			}

			$type = isset($eventsData['type']) ? $eventsData['type'] : $eventsData[$v['events_id']]['type'];
			
			$data[$k]['user'] = array();
			$data[$k]['user']['cdate'] = date('Y.m.d H:i', isset($v['winners_time']) ? $v['winners_time'] : $v['create_time']);
			$data[$k]['user']['events'] = isset($eventsData['events_name']) ? $eventsData['events_name'] : $eventsData[$v['events_id']]['events_name'];

			$data[$k]['user']['headimgurl'] = $this->getUserHead($users[$v['uid']]);


			$data[$k]['user']['ext'] = '';
			if ($type == 6) {
				$data[$k]['user']['ext'] = '邀请';
			} elseif ($type == 4) {
				$data[$k]['user']['ext'] = '试用资格';
			} elseif ($type == 7) {
				$data[$k]['user']['ext'] = '优惠券';
			} elseif ($type == 1) {
				$data[$k]['user']['ext'] = '奖品';
			}


			if (isset($v['express']['phone']) && $v['express']['phone']) {
				$data[$k]['user']['mobile'] = substr_replace($v['express']['phone'],'****',3,4);
			} elseif (isset($newUserExpData[$v['uid']]['phone']) && $newUserExpData[$v['uid']]['phone']) {
				$data[$k]['user']['mobile'] = substr_replace($newUserExpData[$v['uid']]['phone'],'****',3,4);
			} else {
				unset($data[$k]);
			}
		}

		return $data;
	}

	/**
	 * 获取头像
	 */
	public function getUserHead($user)
	{
		if (!is_array($user)) {
			$objUserData = new UserInfo();
			$user = $objUserData -> get($user);
		}
		if (isset($user['headimgurl']) && $user['headimgurl']) {
			$result = $user['headimgurl'];
		} else {
			$result = 'http://news.mydrivers.com/Img/20110518/04481549.png';
		}

		return $result;
	}
	
	/**
	 * 判断当前用户是否已经登录
	 * true 需要
	 * false 不需要
	 */
	public function ckLogin() {
		$cookieInfo = Cookie::get ( $this->userCookieName );
		$cookieInfo = html_entity_decode ( $cookieInfo );
		$userInfo = json_decode ( $cookieInfo, true );
		/*
		 * if(!$this->checkSign($userInfo['sign'] , $userInfo)){ return true; }
		 */
		
		if ($userInfo ['is_new'] == 0) {
			return true;
		}
		return false;
	}
	
	/**
	 * 获取登录地址
	 * $thisUrl : 活动URL地址
	 */
	public function getLoginUrl($thisUrl) {
		
		// 1.拼接一个 referer 地址 
		$cookieInfo = html_entity_decode ( Cookie::get ( $this->userCookieName ) );
		$cookieInfo = json_decode ( $cookieInfo, true );
		$uid = $cookieInfo ['id'];
		$args = array (
				'cas_uid' => $uid,
				'cas_return_url' => urlencode ( $thisUrl )  // 绑定用户后的跳转地址
				);
		$args ['sign'] = $this->createSign ( $args );
		
		$refererUrl = urlencode ( String::jointUrl ( Request::schemeDomain () . '/SetUser/', $args ) ); // passport 返回统一着陆页
		                                                                                         
		// 2. 拼接passport请求地址
		$passport_url = Config::getInstance ()->get ( 'passport_url' );
		$passport_url .= '&referer=' . $refererUrl;
		$arr = $this->convertUrlQuery ( $passport_url );
		$arr ['sign'] = $this->createSign ( $arr );
		$passport_url .= '&sign=' . $arr ['sign'];
		$passport_url .= '&cas_uid=' . $uid;

		$this->setOutput('applogin', 2);
		$weixin = $this->checkIsFromWeixin();
		if (!$weixin) {
			$tokenid = Request::g('tokenid');
			if (!$tokenid) {
				$tokenid = Request::g('tokenId');
			}
			if ($tokenid) {
				# app中已登陆
				$passport_url .= '&tokenid=' . $tokenid;
			} else {
				# app中未登陆
				$this->setOutput('applogin', 1);
			}
		}
		
		return $passport_url;
	}
	public function convertUrlQuery($url) {
		$arr = parse_url ( $url );
		$query = $arr ['query'];
		$queryParts = explode ( '&', $query );
		
		$params = array ();
		foreach ( $queryParts as $param ) {
			$item = explode ( '=', $param );
			$params [$item [0]] = $item [1];
		}
		
		return $params;
	}
	
	/**
	 * 通过活动创建时间,返回活动ID
	 */
	public function getEventsCreateTimeToId() {
		$create_time = Request::g ( 'create_time' );
		$create_time = strtotime ( $create_time );
		$objEvents = new LotteryEvents ();
		$ids = $objEvents->findIdsBy ( array (
				'create_time' => $create_time 
		) );
		return array_pop ( $ids );
	}
	
	/**
	 * 活动相关页面获取 plat_form_id 方法
	 */
	public function getPlatFormId() {
		$url = Request::g ( 'url' );
		$objDPlatform = new Platform ();
		$data = $objDPlatform->getsAll ();
		foreach ( $data as $key => $d ) {
			if ($d ['url'] == $url) {
				$plat_form_id = $key;
				$this->platform = $d;
			}
		}
		
		if (empty ( $plat_form_id )) {
			$plat_form_id = Cookie::get ( 'plat_form_id' );
		} else {
			Cookie::set ( 'plat_form_id', $plat_form_id, 60 * 60 * 24 * 29, '.' . $_SERVER ['HTTP_HOST'] );
		}
		return $plat_form_id;
	}
	
	/**
	 * 生成请求参数的sign
	 *
	 * @param array $params        	
	 * @return String
	 */
	public function createSign(array $params) {
		if ($params && is_array ( $params )) {
			ksort ( $params );
			$str = $this->key;
			foreach ( $params as $key => $value ) {
				if ($key != 'sign') {
					$str .= $key . $value;
				}
			}
			return strtoupper ( md5 ( $str ) );
		}
		return '';
	}
	
	/**
	 * 指定的sign值是否正确
	 *
	 * @param String $sign
	 *        	给定需要验证的sign值
	 * @param Array $params
	 *        	用来计算sign值的参数集合
	 * @return Boolean
	 */
	public function checkSign($sign, $params = null) {
		$sign2 = $this->createSign ( $params );
		return ($sign2 == $sign);
	}

	public function checkIsFromWeixin($title) {
		$state = false;
		$user_agent = $_SERVER ['HTTP_USER_AGENT'];
		if (preg_match ( '/MicroMessenger/i', $user_agent )) {
			$state = true;
		}

		return $state;
	}
	
	/**
	 *
	 * @param string $title        	
	 */
	public function checkIsFromMobile($title) {
		return true;
		if (Request::get ( 'debugs' ) == 'rabin') {
			return true;
		}
		
		// PC 端显示二维码页
		$isMobile = false;
		$user_agent = $_SERVER ['HTTP_USER_AGENT'];
		/*
		if (preg_match ( '/MicroMessenger|Mobile/i', $user_agent )) {
			$isMobile = true;
		}
		*/
		if (preg_match ( '/MicroMessenger/i', $user_agent )) {
			$isMobile = true;
		}
		
		if (! $isMobile) {
			include_once Config::getInstance ()->get ( 'App_Path' ) . DS . 'include/phpqrcode/phpqrcode.php';
			$IMG_UPLOAD_PATH = Config::getInstance ()->get ( 'upload.path' ) . DS . 'qrcode';
			$IMG_UPLOAD_URL = Config::getInstance ()->get ( 'upload.url' ) . DS . 'qrcode';
			if (! file_exists ( $IMG_UPLOAD_PATH )) {
				if (! mkdir ( $IMG_UPLOAD_PATH, 0775, true )) {
					self::fail_exit ( '创建二维码失败,原因:图片目录不存在' );
				}
			}
			
			$url = Request::url ();
			$fileName = Math::md5_16 ( $url ) . '.png';
			$save_path = $IMG_UPLOAD_PATH . DS . $fileName;
			$save_url = $IMG_UPLOAD_URL . DS . $fileName;
			
			if (! file_exists ( $save_path )) {
				\QRcode::png ( $url, $save_path, 3, 6 );
			}
			
			$this->tpl = 'pc_qrcode';
			$this->setOutput ( 'qrcode', $save_url );
			$this->setOutput ( 'title', $title );
			$this->setOutput('user_agent', $user_agent);
			exit ( $this->render () );
		}
	}
}