<?php

namespace Site\Controller;
use http\Header;
use Think\Controller;
use App\Model\GameModel;

/**
 * 后台首页控制器
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
class DownController extends BaseController {

    public function down_file1($id=0,$promote_id=0){
        $model = M('site_game','tab_');
        $device = get_devices_type();
        $map['sdk_version'] = $device;
        $map['id'] = $id;
        $map['promote_id'] = $promote_id;
        $map['status'] = 1;
        $game = $model->where($map)->field("game_id,promote_id,game_dow_url")->find();
        if($game){
            if($game['game_id'] == 0){
                if(empty($game['game_dow_url']))$this->error('下载地址已禁用或未审核!请联系管理员');
                $model->where($map)->setInc('download_number',1);
                redirect($game['game_dow_url']);
                exit;
            }else{
                $this->down_file($game['game_id'],$promote_id,$device);
            }
        }else{
            $condition['id'] = $id;
            $condition['promote_id'] = $promote_id;
            $condition['status'] = 1;
            $data = $model->where($condition)->field("game_name")->find();
            $game_name = str_replace(array('(安卓版)','(苹果版)'),'',$data['game_name']);
            $map1['game_name'] = array('in',array($game_name,$game_name.'(安卓版)',$game_name.'(苹果版)'));
            $map1['sdk_version'] = $device;
            $map1['promote_id'] = $promote_id;
            $map1['status'] = 1;
            $game = $model->where($map1)->field("game_id,promote_id,game_dow_url")->find();
            if($game){
                if($game['game_id'] == 0){
                    if(empty($game['game_dow_url']))$this->error('下载地址已禁用或未审核!请联系管理员');
                    $model->where($map)->setInc('download_number',1);
                    redirect($game['game_dow_url']);
                    exit;
                }else{
                    $this->down_file($game['game_id'],$promote_id,$device);
                }
            }else{
                $this->error('下载地址已禁用或未审核!请联系管理员');
                exit();
            }
        }
    }

    public function down_file($game_id=0,$promote_id=0,$type=1){

        $model = M('Apply','tab_');
        $map['game_id'] = $game_id;
        $map['promote_id'] = $promote_id;
        $data = $model->where($map)->find();
        if($data['status']!=1 || $data['enable_status'] !=1){
            $this->error('下载地址已禁用或未审核!请联系管理员');
            exit();
        }
        $game = M('Game','tab_')->where(array('id'=>$game_id))->find();
        if($game['dow_status'] == 0){
            $this->error('下载地址已禁用或未审核!请联系管理员');
            exit();
        }
        $gamemodel = new GameModel();
        $source = $gamemodel->getGameDownInfo($game_id);
        $data['pack_url'] = $this->package($source['packet'],$promote_id);
        if(!empty($data['pack_url'])){
            if(preg_match("/oss/", $data['pack_url'])){

                if(is_mobile_request()) {
                    if($type == 2) {
                        Header("Location: "."itms-services://?action=download-manifest&url="."https://".$_SERVER["HTTP_HOST"].substr($data['plist_url'],1));
                        exit;
                    }else {
                        if(is_weixin()) {
                            exit("请使用安卓浏览器下载");
                        }
                    }
                }
                $url=str_replace('-internal', '', $data['pack_url']);
                Header("Location: ".$url);

                /*echo "<script>window.location.href='$url';</script>";*/
            }elseif(preg_match("/clouddn/", $data['pack_url'])){

                if(is_mobile_request()) {
                    if($type == 2) {
                        Header("Location: "."itms-services://?action=download-manifest&url="."https://".$_SERVER["HTTP_HOST"].substr($data['plist_url'],1));
                        exit;
                    }else {
                        if(is_weixin()) {
                            exit("请使用安卓浏览器下载");
                        }
                    }
                }
                $url = "http://".$data['pack_url'];

                redirect($url);
            }else{
                if($type == 2) {
                    if(is_mobile_request()){
                        Header("Location: "."itms-services://?action=download-manifest&url="."https://".$_SERVER["HTTP_HOST"].substr($data['plist_url'],1));
                        exit;
                    }else{
                        $this->down($data['pack_url']);
                    }
                }else{
                    $this->down($data['pack_url']);
                }
            }
        }
        else{
            if($game['sdk_version']==1){
                if($game['add_game_address']!=''){
                    $game_address=$game['add_game_address'];
                }else{
                    $game_address=$game['and_dow_address'];
                }
            }else{
                if($game['ios_game_address']!=''){
                    $game_address=$game['ios_game_address'];
                }else{
                    $game_address=$game['ios_dow_address'];
                }
            }
            if(empty($game_address)){$this->error('游戏原包暂未上传!');}
            Header("HTTP/1.1 303 See Other");
            Header("Location: ".$game_address);
        }
         M('Game','tab_')->where(array('id'=>$game_id))->setInc('download_number',1);
        M('site_game','tab_')->where(array('game_id'=>$game_id,'promote_id'=>$promote_id))->setInc('download_number',1);
    }

    public function media_down_file($game_id=0,$type=1){
        $model = M('Game','tab_');
        $map['tab_game.id'] = $game_id;
        $map['file_type'] = $type;
        $data = $model
        ->field('tab_game_source.*,tab_game.game_name,tab_game.add_game_address,tab_game.ios_game_address')
        ->join("left join tab_game_source on tab_game.id = tab_game_source.game_id")->where($map)->find();
        if($type==1){
            if($data['file_url']!=''||!varify_url($data['add_game_address'])){
                $this->down($data['file_url']);
            }
            else{
                Header("HTTP/1.1 303 See Other");
                Header("Location: ".$data['add_game_address']);
            }
        }else{
            if($data['file_url']!=''||!varify_url($data['ios_game_address'])){
                $this->down($data['file_url']);
            }
            else{
                Header("HTTP/1.1 303 See Other");
                Header("Location: ".$data['ios_game_address']);
            }
        }
    }
    public function down($file, $isLarge = false, $rename = NULL)
    {
        if(headers_sent())return false;
        if(!$file) {
            $this->error('文件不存在哦 亲!');
            //exit('Error 404:The file not found!');
        }
        if($rename==NULL){
            if(strpos($file, '/')===false && strpos($file, '\\')===false)
                $filename = $file;
            else{
                $filename = basename($file);
            }
        }else{
            $filename = $rename;
        }

        header('Content-Description: File Transfer');
        header("Content-Type: application/force-download;");
        header('Content-Type: application/octet-stream');
        header("Content-Transfer-Encoding: binary");
        header("Content-Disposition: attachment; filename=\"$filename\"");
        header('Expires: 0');
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header('Pragma: public');
        header('Content-Length: '.filesize($file));//$_SERVER['DOCUMENT_ROOT'].
        header("Pragma: no-cache"); //不缓存页面
        ob_clean();
        flush();
        if($isLarge)
            self::readfileChunked($file);
        else
            readfile($file);
    }

    public function down_material($game_id){
        $map['status'] = 1;
        $game = M("game",'tab_')->where($map)->find($game_id);
        $material = $game['material_url'];
        $this->down($material);
    }

		/**
	 * 下载
	 */
	public function index(){
        if (is_mobile_request()) {
            if(strpos($_SERVER['HTTP_USER_AGENT'], 'iPhone')||strpos($_SERVER['HTTP_USER_AGENT'], 'iPad')){
                    $system = 1;
                    $type = 4;
                    $version_name = C('IOS_VERSION');
            }else{
                    $system = 2;
                    $type = 1;
                    $version_name = C("APP_VERSION");
            }
            $data = M('app', 'tab_')->find($type);
            if(!empty($_REQUEST['account'])){
                $pid = get_promote_id_by_account($_REQUEST['account']);
                $map['promote_id'] = $pid;
                $map['app_id'] = $type;
                $map['enable_status'] = 1;
                $app_info = M('app_apply', 'tab_')->where($map)->find();
                if(!empty($app_info)){
                    /*if(strpos($app_info['dow_url'],'http')!==false){
                        $data['file_url'] = $app_info['dow_url'];
                    }else{
                        $data['file_url'] = "http://".$_SERVER['HTTP_HOST'].substr($app_info['dow_url'],1);
                    }
                    $data['plist_url'] = "https://".$_SERVER['HTTP_HOST'].substr($app_info['plist_url'],1);*/
                    $file_url = $app_info['dow_url'];
                    $plist_url = $app_info['plist_url'];
                }else{
                    $file_url = $data['file_url'];
                    $plist_url = $data['plist_url'];
                    /*$data['file_url'] = "http://".$_SERVER['HTTP_HOST'].substr($data['file_url'],1);
                    $data['plist_url'] = "https://".$_SERVER['HTTP_HOST'].substr($data['plist_url'],1);*/
                }
            }else{
                $file_url = $data['file_url'];
                $plist_url = $data['plist_url'];
                /*$data['file_url'] = "http://".$_SERVER['HTTP_HOST'].substr($data['file_url'],1);
                $data['plist_url'] = "https://".$_SERVER['HTTP_HOST'].substr($data['plist_url'],1);*/
            }

            if(preg_match("/oss/", $file_url)){

                $file_url=str_replace('-internal', '', $file_url);

            }

            if(preg_match('/^\.\/Uploads/', $file_url)) {
                $file_url = "http://".$_SERVER['HTTP_HOST'].substr($file_url,1);
            } elseif (!preg_match('/^http(s)?/', $file_url)) {
                $file_url = 'https://' . $file_url;
            }
            $data['file_url'] = $file_url;

            $data['plist_url'] = "https://".$_SERVER['HTTP_HOST'].substr($plist_url,1);

            $this->assign('data',$data);
            $this->assign('system',$system);
            $this->assign('version_name',$version_name);
            $this->assign('app_name',"手游APP");
            $this->assign('logo_name',get_cover(C('APP_DOWN_LOGO'),'path'));
            $this->display();
        } else {
            //$this->display();
        }
    }

    /**
     * 安卓打包渠道信息
     * @param $source_info  原包信息
     * @param $promote_id
     * @return string
     * author: xmy 280564871@qq.com
     */
    public function package($source_info, $promote_id)
    {
        $file_path = $source_info['file_url'];
        //验证原包是否存在
        if (!varify_url($file_path)) {
            $this->error("未上传原包");
        } else {

            $result = M('apply', 'tab_')
                    ->alias('a')
                    ->field('id, pack_url, plist_url')
                    ->where(['a.game_id'=>$source_info['game_id'],'a.promote_id'=>$promote_id])
                    ->find();
            if(empty($result)) {
                $this->error('此游戏不存在');
            }

            if(GameModel::ANDROID == $source_info['sdk_version']){
                if(varify_url($result['pack_url'])) {
                    return $result['pack_url'];
                }
            }elseif(GameModel::IOS == $source_info['sdk_version']){
                if(varify_url($result['plist_url'])) {
                    return $result['plist_url'];
                }
            }else{
                $this->error('游戏版本错误');
            }

            $zip = new \ZipArchive();

            if ($source_info['sdk_version'] == 1) {
                $str_ver = ".apk";
                $file_name = "GamePack";
                $url_ver = "META-INF/mch.properties";
            } else {
                $zip_open_game_source = zip_open(get_game_source_file_url($source_info['game_id']));
                if ($zip_open_game_source) {
                    while ($zip_entry = zip_read($zip_open_game_source)) {
                        if (preg_match("/.app/", zip_entry_name($zip_entry))) {
                            $ios_app = substr(zip_entry_name($zip_entry), 8) . "<br/>";
                        }
                        $new_ios_1 = explode("/", $ios_app);
                    }
                    zip_close($zip_open_game_source);
                }
                $str_ver = ".ipa";
                $file_name = "IosGamePack";
                $url_ver = "Payload/" . $new_ios_1[0] . "/_CodeSignature/TXChannel";

            }

            $new_name = "game_package" . $source_info['game_id'] . "-" . $promote_id . $str_ver;
            $to = "./Uploads/" . $file_name . "/" . $new_name;
            copy(get_game_source_file_url($source_info['game_id']), ROOTTT . ltrim($to, './'));
            $zip_res = $zip -> open(ROOTTT . ltrim($to, './'), \ZipArchive::CREATE);

            if ($zip_res == true) {
                #打包数据
                $pack_data = array(
                        "game_id" => $source_info["game_id"],
                        "game_name" => $source_info['game_name'],
                        "game_appid" => get_game_appid($source_info["game_id"], "id"),
                        "promote_id" => $promote_id,
                        "promote_account" => get_promote_account($promote_id),
                        "source_version" => $source_info['source_version'],
                );
                $zip -> addFromString($url_ver, json_encode($pack_data));
                $zip->close();

                $newname = $new_name;

                if (get_tool_status("oss_storage") == 1) {

                    if (C("oss_storage.is_cname")) {
                        $to = "http://" . C("oss_storage.domain") . "/" . str_replace("IosGamePack", "GamePack", $file_name) . "/" . $newname;
                    } else {
                        $to = "https://" . C("oss_storage.bucket") . "." . C("oss_storage.domain") . "/" . str_replace("IosGamePack", "GamePack", $file_name) . "/" . $newname;
                        $to = str_replace('-internal', '', $to);
                    }
                    if (!empty(C('oss_storage.bd_domain')) && strlen(C('oss_storage.bd_domain')) > 5) {
                        $to = C('oss_storage.bd_domain') . "/GamePack/" . $newname;
                    }
                    $new_to = ROOTTT . "Uploads/" . $file_name . "/" . $newname;
                    $updata['savename'] = $newname;
                    $updata['path'] = $new_to;
                    $this -> upload_game_pak_oss($updata);
                    @unlink($new_to);

                } elseif (get_tool_status("cos_storage") == 1) {

                    $new_to = ROOTTT . "Uploads/" . $file_name . "/" . $newname;

                    $updata['path'] = $new_to;
                    $updata['savename'] = 'GamePack/'. $newname;

                    $to = $this->upload_cos($updata);

                }

                $promote = array('game_id' => $source_info['game_id'], 'promote_id' => $promote_id);
                $plist_url = '';
                if ($source_info['sdk_version'] == 2) {
                    $plist_url = $this -> create_plist($promote['game_id'], $promote['promote_id'], get_payload_name($source_info['game_id']), $to);
                }
                $jieguo = $this -> updateinfo($result['id'], $to, $promote, $plist_url);

                if ($source_info['sdk_version'] == 2) {
                    return $plist_url;
                }else{
                    return $to;
                }
            }

            return $to;

        }
    }

    /**
     *上传到OSS
     */
    public function upload_game_pak_oss($return_data = null)
    {
        /**
         * 根据Config配置,得到一个OssClient实例
         */
        try {
            Vendor('OSS.autoload');
            $ossClient = new \OSS\OssClient(C("oss_storage.accesskeyid"), C("oss_storage.accesskeysecr"), C("oss_storage.domain"));
        } catch (OssException $e) {
            $this -> error($e -> getMessage());
        }
        $bucket = C('oss_storage.bucket');
        // if(preg_match('/.apk/',$return_data['savename']) ){
        $oss_name = "GamePack";
        // }else{
        //       $oss_name="IosGamePack";
        // }
        $oss_file_path = $oss_name . "/" . $return_data["savename"];
        $avatar = $return_data["path"];
        try {

            $this -> multiuploadFile($ossClient, $bucket, $oss_file_path, $avatar);
            return true;
        } catch (OssException $e) {
            /* 返回JSON数据 */
            $this -> error($e -> getMessage());
        }
    }

    /**
     * 腾讯云上传
     *
     * @param null $data
     *
     * @return mixed
     *
     * @author: 鹿文学[lwx]<fyj301415926@126.com>
     * @since: 2019\4\18 0018 17:40
     */
    public function upload_cos($data=null) {

        Vendor('COS5.vendor.autoload');

        $schema=C("cos_storage.schema")?:"https";

        $secretId = C("cos_storage.SecretId"); //"云 API 密钥 SecretId";
        $secretKey = C("cos_storage.SecretKey"); //"云 API 密钥 SecretKey";
        $region = C("cos_storage.domain"); //设置一个默认的存储桶地域
        $cosClient = new \Qcloud\Cos\Client(
                array(
                        'region' => $region,
                        'schema' => $schema, //协议头部,默认为http
                        'credentials'=> array(
                                'secretId'  => $secretId ,
                                'secretKey' => $secretKey
                        )
                )
        );


        $bucket = C("cos_storage.bucket"); //存储桶名称 格式:BucketName-APPID
        $key = $data['savename'];
        $srcPath = $data["path"];//本地文件绝对路径

        try {
            $result = $cosClient->Upload(
                    $bucket = $bucket,
                    $key = $key,
                    $body = fopen($srcPath, 'rb')
            );
            $location = $result['Location'];
            if(!preg_match('/^(http)|(https)/', $location)) {
                $result['Location'] = 'https://' . $result['Location'];
            }
            return $result['Location'];
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }

    }

    public function create_plist($game_id = 0, $promote_id = 0, $marking = "", $url = "", $platform_id = 0, $position=1)
    {
        $find_web_stie = M('config') -> field('value') -> where(['name' => 'WEB_SITE']) -> find();
        $xml = new \DOMDocument();
        $xml -> load(ROOTTT . 'Uploads/Plist/testdemo.Plist');
        $online = $xml -> getElementsByTagName('dict');//查找节点
        $asd = $online -> item(1) -> getElementsByTagName('string');//第二个节点下所有string
        foreach ($asd as $key => $value) {
            switch ($value -> textContent) {
                case 'ipa_url':
                    if (preg_match("/Uploads/", $url)) {
                        $value -> nodeValue = "https://" . $find_web_stie['value'] . ltrim($url, ".");//"https://iosdemo.vlcms.com/app/MCHSecretary.ipa";//替换xml对应的值
                    } else {
                        $value -> nodeValue = $url;
                    }
                    break;
                case 'icon':
                    $icon_url = get_cover(get_game_icon_id($game_id), 'path', 2);
                    if (preg_match("/http/", $icon_url)) {
                        $value -> nodeValue = $icon_url;
                    } else {
                        $value -> nodeValue = "https://" . $find_web_stie['value'] . $icon_url;
                    }
                    break;
                case 'com.dell':
                    $value -> nodeValue = $marking;
                    break;
                case '1.0.0':
                    $value -> nodeValue = game_version($game_id);
                    break;
                case 'mchdemo':
                    $value -> nodeValue = get_ios_game_name($game_id);
                    break;

            }
            if ($promote_id == 0) {
                $xml -> save(ROOTTT . "Uploads/SourcePlist/$game_id.Plist");
            } elseif ($platform_id > 0) {
                $ppname = $game_id . "-" . $promote_id . "-" . $platform_id . "-" .$position;
                $xml -> save(ROOTTT . "Uploads/GamePlist/$ppname.Plist");
            } else {
                $pname = $game_id . "-" . $promote_id;
                $xml -> save(ROOTTT . "Uploads/GamePlist/$pname.Plist");
            }
        }
        if ($promote_id == 0) {
            return "./Uploads/SourcePlist/$game_id.Plist";
        } elseif ($platform_id > 0) {
            $ppname = $game_id . "-" . $promote_id . "-" . $platform_id . "-" . $position;
            return "./Uploads/GamePlist/$ppname.Plist";
        } else {
            return "./Uploads/GamePlist/$pname.Plist";
        }


    }

    public function multiuploadFile($ossClient, $bucket, $url, $file)
    {
        //$file = __FILE__;
        $options = array();
        try {
            #初始化分片上传文件
            $uploadId = $ossClient -> initiateMultipartUpload($bucket, $url);
            //$ossClient->multiuploadFile($bucket, $url, $file, $options);
        } catch (OssException $e) {
            printf(__FUNCTION__ . ": initiateMultipartUpload FAILED\n");
            printf($e -> getMessage() . "\n");
            return;
        }
        /*
         * step 2. 上传分片
         */
        $partSize = 5 * 1000 * 1024;
        $uploadFile = $file;
        $uploadFileSize = filesize($uploadFile);
        $pieces = $ossClient -> generateMultiuploadParts($uploadFileSize, $partSize);
        $responseUploadPart = array();
        $uploadPosition = 0;
        $isCheckMd5 = true;
        foreach ($pieces as $i => $piece) {
            $fromPos = $uploadPosition + (integer) $piece[$ossClient ::OSS_SEEK_TO];
            $toPos = (integer) $piece[$ossClient ::OSS_LENGTH] + $fromPos - 1;
            $upOptions = array(
                    $ossClient ::OSS_FILE_UPLOAD => $uploadFile,
                    $ossClient ::OSS_PART_NUM => ($i + 1),
                    $ossClient ::OSS_SEEK_TO => $fromPos,
                    $ossClient ::OSS_LENGTH => $toPos - $fromPos + 1,
                    $ossClient ::OSS_CHECK_MD5 => $isCheckMd5,
            );
            if ($isCheckMd5) {
                $contentMd5 = \OSS\Core\OssUtil ::getMd5SumForFile($uploadFile, $fromPos, $toPos);
                $upOptions[$ossClient ::OSS_CONTENT_MD5] = $contentMd5;
            }
            //2. 将每一分片上传到OSS
            try {
                $responseUploadPart[] = $ossClient -> uploadPart($bucket, $url, $uploadId, $upOptions);
            } catch (OssException $e) {
                printf(__FUNCTION__ . ": initiateMultipartUpload, uploadPart - part#{$i} FAILED\n");
                printf($e -> getMessage() . "\n");
                return;
            }
        }
        $uploadParts = array();
        foreach ($responseUploadPart as $i => $eTag) {
            $uploadParts[] = array(
                    'PartNumber' => ($i + 1),
                    'ETag' => $eTag,
            );
        }
        /**
         * step 3. 完成上传
         */
        try {
            $ossClient -> completeMultipartUpload($bucket, $url, $uploadId, $uploadParts);
        } catch (OssException $e) {
            printf(__FUNCTION__ . ": completeMultipartUpload FAILED\n");
            printf($e -> getMessage() . "\n");
            return;
        }
    }

    /**
     *修改申请信息
     */
    public function updateinfo($id, $pack_url, $promote, $plist_url)
    {
        $model = M('Apply', "tab_");
        $data['id'] = $id;
        $data['pack_url'] = $pack_url;
        $data['dow_url'] = '/index.php?s=/Home/Down/down_file/game_id/' . $promote['game_id'] . '/promote_id/' . $promote['promote_id'];
        $data['dow_status'] = 1;
        $data['enable_status'] = 1;
        $data['plist_url'] = $plist_url;
        $res = $model -> save($data);
        return $res;
    }


}