<?php

namespace Mobile\Controller;
use Think\Controller;

use User\Api\SuserApi;

/**
 * 后台首页控制器
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
class AjaxDownController extends Controller {
    /**
     * 返回输出
     * @param int $status 状态
     * @param string $return_msg   错误信息
     * @param array $data           返回数据
     * author: xmy 280564871@qq.com
     */
    public function set_message($status, $return_msg = 0, $data = []){
        $msg = array(
            "status" => $status,
            "return_code" => $return_msg,
            "data" => $data
        );
        echo json_encode($msg);
        exit;
    }

    public function down_file($game_id = 0,$type=1){
        $host_name = $_SERVER['HTTP_NAME'];
        $promote_id = M('SiteApply','tab_')->where('site_url="$host_name"')->getField('promote_id');
        if(empty($promote_id)){
            $this->official_down_file($game_id,$type);
        }else{
            $this->promote_down_file($game_id,$promote_id,0,$type);
        }
    }

    /**
    *推广游戏下载
    *@param int $game_id [游戏关联id]
    *@param int $promote_id [推广员id]
    *@param int $system_type [系统环境] 0 win  1 苹果
    *@param int $sdk_version [sdk 类型] 1 安卓 2 苹果
    */
    public function promote_down_file($game_id=0,$promote_id=0,$system_type=0,$sdk_version=1){
        $applyModel = D('Apply');
        $map['status']        = 1;
        $map['enable_status'] = 1;
        $data = $applyModel
                ->field('game_id,tab_apply.game_name,promote_id,promote_account,relation_game_id,pack_url,plist_url,`status`,enable_status,tab_apply.sdk_version')
                ->join("tab_game ON tab_apply.game_id = tab_game.id AND promote_id = $promote_id AND relation_game_id = $game_id")
                ->where($map)
                ->find();
        if(empty($data)){
            $this->official_down_file($game_id,$sdk_version);
        }else{
            $pack_url = $data['pack_url'];
            M('Game','tab_')->where('id='.$data['game_id'])->setInc('dow_num');
            $this->add_down_stat($data['game_id']);
            if(!empty($pack_url)){
                if(preg_match("/clouddn/", $pack_url)){
                    $pack_url = "http://".$pack_url;
                }
                $this->down(0,$pack_url,$sdk_version,"");
            }else{
                $this->error('原包地址不存在');
            }
        }
    }

    /**
    *下载文件
    * int $game_id 游戏id
    * int $typ  下载环境 1:安卓 2:苹果
    */
    public function official_down_file($game_id=0,$type=1){
        $model = M('Game','tab_');
        $map['tab_game.relation_game_id'] = $game_id;
        $map['tab_game.sdk_version'] = $type;
        $data = $model
            ->field('tab_game_source.*,tab_game.game_name,tab_game.id as game_id,tab_game.and_dow_address,tab_game.ios_dow_address,tab_game.add_game_address,tab_game.ios_game_address,tab_game.down_port,tab_game.dow_status')
            ->join("left join tab_game_source on tab_game.id = tab_game_source.game_id")
            ->where($map)
            ->order('file_type asc')
            ->select();
        $first_data = reset($data);
        if(empty($first_data)){
            $this->error('暂无原包!');
        }
        if(!$first_data['dow_status']){
            $this->error('暂时未开启下载');
        }
        if($type==1 && empty($first_data['file_url'])) {
            $this->error('暂无原包!');
        }
        if($type==2 && empty($first_data['plist_url'])) {
            $this->error('暂无原包!');
        }

        if(substr($first_data['and_dow_address'], 0 , 2)==".."){
            $first_data['and_dow_address']=substr($first_data['and_dow_address'],'1',strlen($first_data['and_dow_address']));
        }
        if(substr($first_data['ios_dow_address'], 0 , 2)==".."){
            $first_data['ios_dow_address']=substr($first_data['ios_dow_address'],'1',strlen($first_data['ios_dow_address']));
        }

        $this->add_down_record($first_data['game_id'],$first_data['game_name']);
        M('Game','tab_')->where('id='.$first_data['game_id'])->setInc('dow_num');
        $this->add_down_stat($first_data['game_id']);
        if(strpos($_SERVER['HTTP_USER_AGENT'], 'iPhone')||strpos($_SERVER['HTTP_USER_AGENT'], 'iPad')){
            $phonetype = 2; //2ios
        }
        if($type==1){
            if($first_data['down_port']==1) {
                $url = $first_data['file_url'];
                if(!preg_match('/^http(s)?/', $url)) {
                    $url = 'http://' . $_SERVER['HTTP_HOST'] . substr($url,1);
                }
                if(varify_url($url)) {
                    $this->down(0,$url,$type);exit;
                } else {
                    $this->error('下载地址错误!');
                }
            } else {
                if(varify_url($first_data['and_dow_address'])){
                    $this->down(0,$first_data['and_dow_address'],$type);exit;
                }else{
                    $this->error('下载地址错误!');
                }
            }
        }else if($type==2){
            if($phonetype!=2){
                if($first_data['down_port']==1) {

                    $url = $first_data['file_url'];
                    if(!preg_match('/^http(s)?/', $url)) {
                        $url = 'http://' . $_SERVER['HTTP_HOST'] . substr($url,1);
                    }
                    if(varify_url($url)) {
                        $this->down(0,$url,$type);exit;
                    } else {
                        $this->error('下载地址错误!');
                    }

                } else {
                    if(varify_url($first_data['ios_dow_address'])){
                        $this->down(0,$first_data['ios_dow_address'],$type);
                    }else{
                        $this->error('下载地址错误!');
                    }
                }
            }else{
                if($first_data['down_port']==1) {
                    $this -> down(0, $first_data['plist_url'], $type);
                    exit;
                } else {
                    if(varify_url($first_data['ios_dow_address'])){
                        $this->down(0,$first_data['ios_dow_address'],$type);
                    }else{
                        $this->error('下载地址错误!');
                    }
                }
            }
        }
    }

    function access_url($url) {
        if ($url=='') return false;
        $fp = fopen($url, 'r') or exit('Open url faild!');
        if($fp){
        while(!feof($fp)) {
            $file.=fgets($fp)."";
        }
        fclose($fp);
        }
        return $file;
    }

    /**
     * [断点下载 需要服务器支持]
     * @param  [type] $file   [description]
     * @param  [type] $type   [description]
     * @param  [type] $rename [description]
     * @return [type]         [description]
     * @author [yyh] <[email address]>
     * @param  [type] $downtype   [0 不执行下载  1安卓下载  2苹果下载]
     */
    public function down($downtype=0,$file,$type='',$rename = NULL)
    {
        if($downtype){
            $file=think_decrypt($file);
        }
        if(strpos($_SERVER['HTTP_USER_AGENT'], 'iPhone')||strpos($_SERVER['HTTP_USER_AGENT'], 'iPad')){
            $iphonedown = 2;
        }

        if(headers_sent())return false;//检查 HTTP 标头是否已被发送,可以避免与 HTTP 标头有关的错误信息。
        if(!$file&&$type==1) {
            $this->error('安卓文件不存在哦 亲!');
        }
        if(!$file&&$type==2) {
            $this->error('苹果文件不存在哦 亲!');
        }
        $sourceFile = $file; //要下载的临时文件名
        $outFile = $rename;
        $file_extension = strtolower(substr(strrchr($sourceFile, "."), 1)); //获取文件扩展名
        //检测文件是否存在
        if (!varify_url($sourceFile)) {
            $this->error('文件已丢失,请联系客服!');
        }
        if($downtype==0){
            if($iphonedown==2&&$type==2){
                $this->success('文件合法',U('down',array('downtype'=>2,'file'=>think_encrypt($file),'type'=>$type,'rename'=>$rename)));
            }else{
								$this->success('文件合法',U('download',array('file'=>think_encrypt($file))));
                ///$this->success('文件合法',U('down',array('downtype'=>1,'file'=>think_encrypt($file),'type'=>$type,'rename'=>$rename)));
            }
            exit;
        }elseif($downtype==2){
           $plist_url = substr($file,'1',strlen($file));
            Header("HTTP/1.1 303 See Other");
            Header("Location: "."itms-services://?action=download-manifest&url="."https://".$_SERVER["HTTP_HOST"].$plist_url);
            exit;
        }

    }


function download($file){    //First, see if the file exists

	$url=think_decrypt($file);

    if(!preg_match('/^http(s)?/', $url)) {
        $host = 'http://'.$_SERVER['HTTP_HOST'];
        if(stripos($url,$host) === false) {
            $url = $host.str_replace('./','/',$url);
        } elseif(stripos($url,'http') === false) {
            $url = 'http://'.$url;
        }
    }

	header('Location: '.$url);exit;
}



		function dl_file_resume($file){
			$file=think_decrypt($file);
			//检测文件是否存在
			if (!is_file($file)) { die("404 File not found!"); }

			$len = filesize($file);//获取文件大小
			$filename = basename($file);//获取文件名字
			$file_extension = strtolower(substr(strrchr($filename,"."),1));//获取文件扩展名

			//根据扩展名 指出输出浏览器格式
			switch( $file_extension ) {
			case "exe": $ctype="application/octet-stream"; break;
			case "zip": $ctype="application/zip"; break;
			case "mp3": $ctype="audio/mpeg"; break;
			case "mpg":$ctype="video/mpeg"; break;
			case "avi": $ctype="video/x-msvideo"; break;
			default: $ctype="application/force-download";
			}

			//Begin writing headers
			header("Cache-Control:");
			header("Cache-Control: public");

			//设置输出浏览器格式
			header("Content-Type: $ctype");
			if (strstr($_SERVER['HTTP_USER_AGENT'], "MSIE")) {//如果是IE浏览器

			$iefilename = preg_replace('/\./', '%2e', $filename, substr_count($filename, '.') - 1);
			header("Content-Disposition: attachment; filename=\"$iefilename\"");
			} else {
			header("Content-Disposition: attachment; filename=\"$filename\"");
			}
			header("Accept-Ranges: bytes");

			$size=filesize($file);
			$range=0;
			if(isset($_SERVER['HTTP_RANGE'])) {

				list($a, $range)=explode("=",$_SERVER['HTTP_RANGE']);

				str_replace($range, "-", $range);
				$size2=$size-1;//文件总字节数
				$new_length=$size2-$range;//获取下次下载的长度
				header("HTTP/1.1 206 Partial Content");
				header("Content-Length: $new_length");//输入总长
				header("Content-Range: bytes $range$size2/$size");
			} else {//第一次连接
				$size2=$size-1;
				header("Content-Range: bytes 0-$size2/$size");
				header("Content-Length: ".$size);//输出总长
			}
			//打开文件
			$fp=fopen("$file","rb+");
			//设置指针位置
			fseek($fp,$range);
			//虚幻输出
			while(!feof($fp)){
				set_time_limit(0);
				echo fread($fp,1024*8);
				flush();
				ob_flush();
			}
			fclose($fp);
			exit;
		}



		public function down222($downtype=0,$file,$type='',$rename = NULL)
    {
        if($downtype){
            $file=think_decrypt($file);
        }
        if(strpos($_SERVER['HTTP_USER_AGENT'], 'iPhone')||strpos($_SERVER['HTTP_USER_AGENT'], 'iPad')){
            $iphonedown = 2;
        }

        if(headers_sent())return false;//检查 HTTP 标头是否已被发送,可以避免与 HTTP 标头有关的错误信息。
        if(!$file&&$type==1) {
            $this->error('安卓文件不存在哦 亲!');
        }
        if(!$file&&$type==2) {
            $this->error('苹果文件不存在哦 亲!');
        }
        $sourceFile = $file; //要下载的临时文件名
        $outFile = $rename;
        $file_extension = strtolower(substr(strrchr($sourceFile, "."), 1)); //获取文件扩展名
        //检测文件是否存在
        if (!varify_url($sourceFile)) {
            $this->error('文件已丢失,请联系客服!');
        }
        if($downtype==0){
            if($iphonedown==2&&$type==2){
                $this->success('文件合法',U('down',array('downtype'=>2,'file'=>think_encrypt($file),'type'=>$type,'rename'=>$rename)));
            }else{
                $this->success('文件合法',U('down',array('downtype'=>1,'file'=>think_encrypt($file),'type'=>$type,'rename'=>$rename)));
            }
            exit;
        }elseif($downtype==2){
           $plist_url = substr($file,'1',strlen($file));
            Header("HTTP/1.1 303 See Other");
            Header("Location: "."itms-services://?action=download-manifest&url="."https://".$_SERVER["HTTP_HOST"].$plist_url);
            exit;
        }


        //检测文件是否存在
        if (!is_file($sourceFile)) {
            die("<b>404 File not found!</b>");
        }
        $len = filesize($sourceFile); //获取文件大小
        $filename = basename($sourceFile,'.'.$file_extension); //获取文件名字
        $outFile_extension = $file_extension; //获取文件扩展名
        //根据扩展名 指出输出浏览器格式
        switch ($outFile_extension) {
            case "exe" :
                $ctype = "application/octet-stream";
                break;
            case "zip" :
                $ctype = "application/zip";
                break;
            case "mp3" :
                $ctype = "audio/mpeg";
                break;
            case "mpg" :
                $ctype = "video/mpeg";
                break;
            case "avi" :
                $ctype = "video/x-msvideo";
                break;
            default :
                $ctype = "application/force-download";
        }
        //Begin writing headers  允许缓存 把页面缓存
        header("Cache-Control:");
        header("Cache-Control: public");
        //设置输出浏览器格式
        //告诉浏览器强制下载
        header("Content-Type: $ctype");
        //下载后的名字以及后缀
        header("Content-Disposition: attachment; filename=" . $filename.".".$outFile_extension);
        //接受的范围单位
        header("Accept-Ranges: bytes");
        $size = filesize($sourceFile);
        //$_SERVER['HTTP_RANGE'] HTTP协议是否设置支持断点下载
        //如果有$_SERVER['HTTP_RANGE']参数
        if (isset ($_SERVER['HTTP_RANGE'])) {
            if (!preg_match('^bytes=\d*-\d*(,\d*-\d*)*$', $_SERVER['HTTP_RANGE'])) {
                header('HTTP/1.1 416 Requested Range Not Satisfiable');
                header('Content-Range: bytes */' . $size); // Required in 416.
                exit;
            }
            $ranges = explode(',', substr($_SERVER['HTTP_RANGE'], 6));
            foreach ($ranges as $range) {
                $parts = explode('-', $range);
                $start = $parts[0]; // If this is empty, this should be 0.
                $end = $parts[1]; // If this is empty or greater than than filelength - 1, this should be filelength - 1.

                if ($start > $end) {
                    header("HTTP/1.1 206 Partial Content");
                    header("Content-Length: $new_length"); //输入总长
                    header("Content-Range: bytes $range$size2/$size"); //Content-Range: bytes 4908618-4988927/4988928   95%的时候
                    exit;
                }
            }
        } else {
            //HTTP协议未设置断点下载 尝试设置
            //即第一次连接
            $size2 = $size -1;
            header("Content-Range: bytes 0-$size2/$size"); //Content-Range: bytes 0-4988927/4988928
            header("Content-Length: " . $size); //输出总长
        }
        //打开文件
        $fp = fopen("$sourceFile", "rb+");
        //设置指针位置
        fseek($fp, $range);
        //虚幻输出
        while (!feof($fp)) {
            //设置文件最长执行时间
            set_time_limit(0);
            print (fread($fp, 1024 * 8)); //输出文件
            flush(); //输出缓冲
            ob_flush();
        }
        fclose($fp);
        exit ();
    }




    /**
    *游戏下载统计
    */
    public function add_down_stat($game_id=null){
        $model = M('down_stat','tab_');
        $data['promote_id'] = 0;
        $data['game_id'] = $game_id;
        $data['number'] = 1;
        $data['type'] = 0;
        $data['create_time'] = NOW_TIME;
        $model->add($data);
    }

    /**
    *用户下载游戏记录
    *@param int    $game_id   游戏ID
    *@param string $game_name 游戏名称
    */
    public function add_down_record($game_id=0,$game_name=''){

				$member = new SuserApi;

        $logininfo = $member->login_info();

        if(!empty($logininfo)){
            $model = M('DownRecord','tab_');
            $map['game_id'] = $game_id;
            $map['user_id'] = $logininfo['user_id'];
            $d = $model->where($map)->find();
            if(empty($d)){
                $data['user_id'] = $logininfo['user_id'];
                $data['user_account'] = $logininfo['account'];
                $data['game_id'] = $game_id;
                $data['game_name'] = $game_name;
                $data['create_time'] = time();
                $model->add($data);
            }
        }
    }
}