<?php
/**
 * Created by PhpStorm.
 * User: xmy 280564871@qq.com
 * Date: 2017/4/24
 * Time: 9:20
 */

namespace Open\Model;

use Admin\Model\SpendModel;

class GameModel extends BaseModel{


	protected $_validate = [
		['game_name',  'require', '游戏名称不能为空',         self::MUST_VALIDATE,  'regex',  self::MODEL_INSERT],
		['game_name', 'checkGame', '游戏名称已存在', 1, 'callback', 1],
		['game_name',  '1,30',    '游戏名称不能超过30个字符', self::VALUE_VALIDATE, 'length', self::MODEL_BOTH],
		['game_type_id',  'require', '游戏类型称不能为空',         self::MUST_VALIDATE,  'regex',  self::MODEL_INSERT],
		['category',  'require', '游戏开放类型不能为空',         self::MUST_VALIDATE,  'regex',  self::MODEL_BOTH],
		['sdk_version',  'require', '游戏版本不能为空',         self::MUST_VALIDATE,  'regex',  self::MODEL_INSERT],
		['introduction',  'require', '游戏介绍不能为空',         self::MUST_VALIDATE,  'regex',  self::MODEL_BOTH],
		['features',  'require', '游戏简介不能为空',         self::MUST_VALIDATE,  'regex',  self::MODEL_BOTH],
		['icon',  'checkRequire', '游戏ICON不能为空',         self::MUST_VALIDATE,  'callback',  self::MODEL_BOTH],
		['cover',  'checkRequire', '游戏推荐图不能为空',         self::MUST_VALIDATE,  'callback',  self::MODEL_BOTH],
		['screenshot',  'checkRequire', '游戏截图不能为空',         self::MUST_VALIDATE,  'callback',  self::MODEL_BOTH],
	];

	protected $_auto = [
		['create_time',       'time',         self::MODEL_INSERT,  'function'],
		['game_status',       '1',         self::MODEL_INSERT],
		['game_score',       '0',         self::MODEL_INSERT],
		['game_name',       'disposeGameName',         self::MODEL_INSERT,'callback'],
		['short',       'pinyin',         self::MODEL_INSERT,'callback'],
	];

	public function checkRequire($data){
		if(empty($data)){
			return false;
		}
		return true;

	}

	/**
	 * 获取数据列表
	 * @param $map
	 * @param $p
	 * @param string $order
	 * @param int $row
	 * @return mixed
	 * author: xmy 280564871@qq.com
	 */
	public function getDataLists($map,$p,$order="create_time desc",$row=10){
		$page = $this->dealPage($p);
		$data = $this->alias("g")
			->field("g.id,g.game_name,g.sdk_version,g.apply_status,g.create_time,g.material_url,g.icon,game_type_name,s.id as source_id,g.game_status,g.online_time")
			->join("left join tab_game_source s on s.game_id = g.id")
			->where($map)
			->order($order)
			->page($page,$row)
			->select();
		$count = $this->alias("g")->join("left join tab_game_source s on s.game_id = g.id")->where($map)->count();
		$result['data'] = $data;
		$result['count'] = $count;
		return $result;
	}


	/**
	 * 游戏信息保存、更新
	 * @return bool|mixed
	 * author: xmy 280564871@qq.com
	 */
	public function upDate($user_id,$game_id=""){
		$data = $this->create();
		if(!$data){
			return false;
		}
		$data['apply_status'] = 0;
		if(empty($game_id)){//添加
			
			$data['appstatus'] = 1;
			if($data['sdk_version'] == 3){//双平台
				for ($i = 1; $i < 3; $i++){
					$data['sdk_version'] = $i;
					$data['game_appid'] = generate_game_appid(uniqid());
					$data['developers'] = $user_id;
					$data['game_name'] = $this->disposeGameName(I('game_name'),$i);
					$result = $this->add($data);
				}
			}else{
				$data['game_appid'] = generate_game_appid();
				$data['developers'] = $user_id;
				$result = $this->add($data);
			}
		}else{//编辑
			$map['id'] = $game_id;
			$map['developers'] = $user_id;
			$result = $this->where($map)->save($data);
		}
		return $result;
	}


	/**
	 * 插入数据后处理游戏设置信息
	 * @param $data
	 * @param $options
	 * author: xmy 280564871@qq.com
	 */
	public function _after_insert($data, $options)
	{
		//关联游戏
		$game = $this->where(['relation_game_name'=>I('post.game_name')])->order("id asc")->find();
		$data['relation_game_name'] = I("post.game_name");
		$data['relation_game_id'] = isset($game['id']) ? $game['id'] : $data['id'];
		$this->save($data);
		//增加游戏设置信息
		$GameSet = new GameSetModel();
		$GameSet->addSet($data['id']);
		//增加合同信息
		$Contract = new ContractModel();
		$Contract->addContract($data['id'],$data['developers']);
		parent::_after_insert($data, $options); // TODO: Change the autogenerated stub
	}


	/**
	 * 处理游戏名
	 * @param $name
	 * @return string
	 * author: xmy 280564871@qq.com
	 */
	public function disposeGameName($name,$sdk_version=""){
		$sdk_version = empty($sdk_version) ? I("sdk_version") : $sdk_version;
		if($sdk_version == 1){
			return $name."(安卓版)";
		}elseif ($sdk_version == 2){
			return $name."(苹果版)";
		}
	}

	protected function checkGame($game_name){
		$map['relation_game_name'] = $game_name;
		$map['sdk_version'] = I("sdk_version");
		$data = $this->where($map)->find();
		if(empty($data)){
            $map1['relation_game_name'] = $game_name;
            $map1['developers'] = 0;
            $data1 = $this->where($map1)->find();
            if($data1){
                return false;
            }else{
                return true;
            }
		}else{
			return false;
		}
	}

	public function getUserData($user_id,$id){
		$map['developers'] = $user_id;
		$map['id'] = $id;
		return $this->where($map)->find();
	}

	/**
	 * 上传素材包
	 * @param $user_id
	 * @param $id
	 * @return bool
	 * author: xmy 280564871@qq.com
	 */
	public function addMaterial($user_id,$id){
		if (empty(I("post.file_url"))){
			$this->error = "素材包不能为空";
			return false;
		}
		$map['developers'] = $user_id;
		$map['id'] = $id;
		return $this->where($map)->setField(["material_url"=>I("post.file_url"),"apply_status"=>0]);
	}


	/**
	 * 设置游戏显示状态
	 * @param $user_id
	 * @param $id
	 * @return bool
	 * author: xmy 280564871@qq.com
	 */
	public function setStatus($user_id,$id){
		$map['developers'] = $user_id;
		$map['id'] = $id;
		$data = $this->where($map)->find();
		if($data['apply_status'] != 1){
			$this->error = "请先通过审核";
			return false;
		}
		$status = $data['game_status'] == 1 ? 0 : 1;
		return $this->where($map)->setField("game_status",$status);

	}

	/**
	 * 获取游戏数量
	 * @param string $map
	 * @return mixed
	 * author: xmy 280564871@qq.com
	 */
	public function getGameNum($map=""){
		$data = $this->where($map)->count();
		return $data;
	}

	/**
	 * 获取游戏列表
	 * @param $develop_id
	 * author: xmy 280564871@qq.com
	 */
	public function getLists($develop_id){
		$map['developers'] = $develop_id;
		$map['apply_status'] = 1;
		return $this->field("id,game_name,sdk_version")->where($map)->select();
	}

	/**
	 * 开放平台 游戏数据模式
	 * @param $game_id
	 * @return mixed
	 * author: xmy 280564871@qq.com
	 */
	public function dataTable($game_id){
		$today = strtotime('today');
		$tomorrow = $today+86400;
		$today_str = date('Y-m-d',strtotime('today'));

		$Record = new UserLoginRecordModel();
		$Spend = new SpendModel();

		$tomorrow_str = date('Y-m-d',$tomorrow);
		//新增玩家
		$data['add_user'] = $Record->getAddPlayer($today_str,$tomorrow_str,UID,$game_id)[0]['num'];
		//活跃玩家
		$map['d.time'] = $today_str;
		$data['active_user'] = $Record->getActivePlayer($map,UID,$game_id)[0]['num'];
		//流水
		$data['spend'] = $Spend->getOpenSpend($map,UID)[0]['num'];
		//ARPU
		$data['ARPU'] = round($data['spend']/$data['active_user'],2);
		//付费玩家数
		$data['payer_num'] = $Spend->getPayerNum($map,UID)[0]['num'];
		//ARPPU
		$data['ARPPU'] = round($data['spend']/$data['payer_num'],2);
		//付费率
		$data['pay_rate'] = round($data['payer_num']/$data['active_user']*100,2);
		//累计流水
		$data['total_spend'] = $Spend->getTotalSpend(['game_id'=>$game_id])['num'];
		//累计玩家
		$data['total_user'] = $Record->getTotalUser(['game_id'=>$game_id])['num'];
		return $data;
	}
	
	/**
	 * 开放平台 游戏数据模式
	 * @param integer $game_id   游戏编号
	 * @return mixed
	 * author: 鹿文学
	 */
	public function data_table($game_id){
		$today = strtotime('today');
		$tomorrow = $today+86400;
		$today_str = date('Y-m-d',strtotime('today'));

		$Record = new UserLoginRecordModel();
		$Spend = new SpendModel();

		$tomorrow_str = date('Y-m-d',$tomorrow);
		
		//新增玩家
		$data['add_user'] = $Record->get_news_player($today_str,$tomorrow_str,UID,$game_id)[0]['num'];
		//活跃玩家
		$map['d.time'] = $today_str;
		$data['active_user'] = $Record->getActivePlayer($map,UID,$game_id)[0]['num'];
		//流水
		$data['spend'] = $Spend->getOpenSpend($map,UID,$game_id)[0]['num'];
		//ARPU
		$data['ARPU'] = round($data['spend']/$data['active_user'],2);
		//付费玩家数
		$data['payer_num'] = $Spend->getPayerNum($map,UID,$game_id)[0]['num'];
		//ARPPU
		$data['ARPPU'] = round($data['spend']/$data['payer_num'],2);
		//付费率
		$data['pay_rate'] = round($data['payer_num']/$data['active_user']*100,2);
		//累计流水
		$data['total_spend'] = $Spend->getTotalSpend(['game_id'=>$game_id])['num'];
		//累计玩家
		$data['total_user'] = $Record->getTotalUser(['game_id'=>$game_id])['num'];
		return $data;
	}

	/**
	 * 游戏上线
	 * @param $game_id
	 * @return bool
	 * author: xmy 280564871@qq.com
	 */
	public function setOnline($game_id){
		$game['online_time'] = time();
		$game['online_status'] = 1;
		$map['id'] = ['in',$game_id];
		return $this->where($map)->setField($game);
	}

	/**
	 * 游戏名转字母
	 * @param $game_name
	 * @return string
	 * author: xmy 280564871@qq.com
	 */
	public function pinyin(){
		$pinyin = new \Think\Pinyin();
		$game_name = I("game_name");
		$num=mb_strlen($game_name,'UTF8');
		$short = '';
		for ($i=0; $i <$num ; $i++) {
			$str=mb_substr( $game_name, $i, $i+1, 'UTF8');
			$short.=$pinyin->getFirstChar($str);
		}
		return $short;
	}
}