<?php

namespace Admin\Controller;

use Qiniu\Storage\UploadManager;
use User\Api\UserApi as UserApi;
use OSS\OssClient;
use OSS\Core\OSsException;
use Qiniu\Storage\BucketManager;
use Qiniu\Auth;
use Think\Controller;
use BaiduBce\BceClientConfigOptions;
use BaiduBce\Util\Time;
use BaiduBce\Util\MimeTypes;
use BaiduBce\Http\HttpHeaders;
use BaiduBce\Services\Bos\BosClient;
use BaiduBce\Services\Bos\CannedAcl;
use BaiduBce\Services\Bos\BosOptions;
use BaiduBce\Auth\SignOptions;
use BaiduBce\Log\LogFactory;
use Think\Think;
use Base\Service\GameSourceService;
use Base\Tool\CosClient;
use Base\Tool\OssClient as ToolOssClient;
use Base\Tool\Printer;
use Base\Tool\Redis;

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


    protected function _initialize()
    {
        C(api('Config/lists'));
    }


    public function package()
    {
        $find_web_stie = M('config')->field('value')->where(['name' => 'WEB_SITE'])->find();

        if (null == $find_web_stie) {
            \Think\Log ::record('请先到站点->网站设置->网站域名处设置官网域名');
            exit;
        }

        $progressLimit = C('PACK_PROGRESS_LIMIT', null, 1);
        $currentProgress = Redis::incr('console_packing');
        $progressId = date('His') . rand(100, 999) . $currentProgress;
        if ($currentProgress > $progressLimit) {
            Redis::decr('console_packing');
            Printer::export('打包进程已满,进程数量限制[' . $progressLimit . ']', true);
        }

        Printer::export('打包进程[' . $progressId . ']开始');

        $this->checkPackageStatus();
        // $this->app_package();//app渠道自动打包
        $result = $this->channel($progressId);
        // $this->launch_package(false);
        // $this->leak_detection();
        Redis::decr('console_packing');
        $message = '打包进程[' . $progressId . ']结束。' 
            . '处理数量[' . $result['total'] . '],' 
            . '成功数量[' . $result['success'] . '],' 
            . '失败数量[' . $result['error'] . ']';
        Printer::export($message);
    }

    /**
     * 更改申请游戏的状态
     *
     * @author: 鹿文学[lwx]<fyj301415926@126.com>
     * @since: 2019\4\23 0023 11:22
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function checkPackageStatus() {
        $applyModel = M('apply', 'tab_');
        $launchModel = M('apply_launch', 'tab_');

        $launchGameIds = $launchModel
                ->alias('l')
                ->field('l.id')
                ->join('tab_game_source as s on (s.game_id = l.launch_game_id and trim(s.file_name) <> trim(l.game_source_filename))')
                ->where('1=1')
                ->group('l.id')
                ->select();

        if(!empty($launchGameIds)) {
            $ids = array_column($launchGameIds, 'id');
            $launchModel->where(['id'=>['in',$ids]])->setField('launch_packge', 2);
        }

        $launchIds = $launchModel
                ->field('apply_id,count(id) as count')
                ->where(['launch_packge'=>1])
                ->group('apply_id')
                ->select();
        $launchAllIds = $launchModel
                ->field('apply_id,count(id) as count')
                ->group('apply_id')
                ->select();

        $launchId = [];
        foreach ($launchIds as $launchValue) {
            foreach ($launchAllIds as $launchAllValue) {
                if($launchValue['apply_id'] == $launchAllValue['apply_id']
                        && $launchValue['count'] == $launchAllValue['count']) {
                    $launchId[] = $launchValue['apply_id'];
                }
            }
        }

        if(!empty($launchId)) {
            $applyModel->where(['id'=> ['in',$launchId]])->setField('enable_status', 1);
        }

    }

    /**
     * 投放申请游戏打包
     *
     * @param bool $flag
     *
     * @author: 鹿文学[lwx]<fyj301415926@126.com>
     * @since: 2019\4\17 0017 17:44
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function launch_package($flag=true)
    {

        if($flag) {
            $find_web_stie = M('config')
                    -> field('value')
                    -> where(['name' => 'WEB_SITE'])
                    -> find();

            if (null == $find_web_stie) {
                \Think\Log ::record('请先到站点->网站设置->网站域名处设置官网域名');
                exit;
            }

        }

        $zip = new \ZipArchive();

        $applyModel = M('apply', 'tab_');
        $gameSourceModel = M('Game_source', 'tab_');
        $launchModel = M('apply_launch', 'tab_');

        $map['launch_packge'] = ['in',[0,2]];
        $map['launch_status'] = 1;

        $launchData = $launchModel->alias('l')
                    ->field('l.id, l.platform_id, l.apply_id, l.position,l.launch_packge, l.game_source_filename, a.game_id, a.game_name, a.promote_id, a.promote_account, a.sdk_version')
                    ->join('tab_apply as a on(a.id = l.apply_id and a.status=1) ')
                    ->where($map)
                    ->order('apply_id')
                    ->limit(3)
                    ->select();
        if (!empty($launchData)) {

            foreach($launchData as $key => $value) {

                $gameSourceData = $gameSourceModel
                        -> field('id,file_name,source_version')
                        -> where(['game_id' => $value['game_id']])
                        -> find();

                $url = get_game_source_file_url($value['game_id']);
                $launchMap = ['apply_id' => $value['apply_id']];
                if(!file_exists($url) || null == $gameSourceData) {
                    $applyModel -> where(['id' => $value['apply_id']]) -> setField('enable_status', -1);
                    $launchModel->where($launchMap)->setField('launch_packge', -1);
                    continue;
                }

                if($gameSourceData['file_name'] == $value['game_source_filename'] && !empty($value['launch_down_url'])) {
                    $applyModel -> where(['id' => $value['apply_id']]) -> setField('enable_status', 1);
                    $launchModel->where($launchMap)->setField('launch_packge', 1);
                    continue;
                }

                $applyModel -> where(['id' => $value['apply_id']]) -> setField('enable_status', 3);
                $launchModel->where(['platform_id' => $value['platform_id'], 'apply_id' => $value['apply_id'], 'position'=>$value['position']])->setField('launch_packge', 3);
                if($value['sdk_version'] == 1) {
                    $str_ver = ".apk";
                    $file_name = "GamePack";
                    $url_ver = "META-INF/mch.properties";
                } else {
                    $zip_open_game_source = zip_open($url);
                    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" . $value['game_id'] . "-" . $value['promote_id'] . "-" . $value['platform_id'] . "-" . $value['position'] . $str_ver;
                $to = "./Uploads/" . $file_name . "/" . $new_name;
                copy($url, ROOTTT . ltrim($to, './'));
                $zip_res = $zip -> open(ROOTTT . ltrim($to, './'), \ZipArchive::CREATE);

                if($zip_res == true) {
                    #打包数据
                    $pack_data = array(
                            "game_id" => $value["game_id"],
                            "game_name" => $value['game_name'],
                            "game_appid" => get_game_appid($value["game_id"], "id"),
                            "promote_id" => $value['promote_id'],
                            "promote_account" => $value['promote_account'],
                            "source_version" => $gameSourceData['source_version'],
                            'launch_id' => $value['platform_id'],
                            'position' => $value['position'],
                    );

                    $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("qiniu_storage") == 1) {

                        $this -> dleteQiNiuFile($newname);
                        $url = $this -> upQiNiuFile($newname, ROOTTT . ltrim($to, './'));
                        if (empty($url)) {
                            $this -> error('七牛错误,请检查七牛配置,并确保七牛空间权限正确!');
                        }
                        @unlink(ROOTTT . ltrim($to, './'));
                        $to = "http://" . $url;

                    } 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);


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

                        $to = "http://" . C("bos_storage.bucket") . "." . C("bos_storage.domain") . "/" . $file_name . "/" . $newname;
                        $to = str_replace('-internal', '', $to);
                        $new_to = ROOTTT . "Uploads/" . $file_name . "/" . $newname;
                        $updata['savename'] = $newname;
                        $updata['path'] = $new_to;
                        $this -> upload_bos($updata);
                    }
                    $promote = array('game_id' => $value['game_id'], 'promote_id' => $value['promote_id']);
                    $plist_url = '';
                    if ($value['sdk_version'] == 2) {
                        $plist_url = $this -> create_plist($value['game_id'], $value['promote_id'], get_payload_name($value['game_id']), $to, $value['platform_id'], $value['position']);
                    }

                    $jg = $this -> update_launch_info(['platform_id' => $value['platform_id'], 'apply_id' => $value['apply_id'], 'position'=>$value['position']], $to, $plist_url, $gameSourceData['file_name']);

                    $applyModel -> where(['id' => $value['apply_id']]) -> setField('enable_status', 1);

                } else {

                    $applyModel -> where(['id' => $value['apply_id']]) -> setField('enable_status', -1);
                    $launchModel->where(['platform_id' => $value['platform_id'], 'apply_id' => $value['apply_id'], 'position'=>$value['position']])->setField('launch_packge', -1);
                }



            }

        }

    }


    /**
     * 渠道游戏打包
     */
    private function channel($progressId = 0) {
        $map = [];
        $map['status'] = 1;
        $map['enable_status'] = ['in', '0,2'];

        $applys = M('apply', 'tab_')->field('id,game_id,game_name,promote_id,promote_account,sdk_version,pack_url,plist_url')
            ->where($map)
            ->order('bale_sort desc,id desc')
            ->limit(15)
            ->select();

        $packResult = [
            'total' => 0,
            'success' => 0,
            'error' => 0,
        ];
        if (count($applys) == 0) {
            return $packResult;
        }

        $applyIds = array_column($applys, 'id');

        M('apply', 'tab_')->where(['id' => ['in', $applyIds]])->save(['enable_status' => 3]);

        $gameIds = array_unique(array_column($applys, 'game_id'));
        $games = M('game', 'tab_')->field(['id', 'game_appid', 'game_name', 'icon', 'sdk_version'])->where(['id' => ['in', $gameIds]])->select();
        $games = index_by_column('id', $games);

        $launchCountList = M('apply_launch', 'tab_')->field(['apply_id', 'count(*) count'])->where(['apply_id' => ['in', $applyIds]])->group('apply_id')->select();
        $launchCountList = index_by_column('apply_id', $launchCountList);

        $gameSources = M('game_source', 'tab_')->field(['id', 'file_name', 'source_version', 'file_type', 'bao_name', 'game_id', 'is_new_sdk'])->where(['game_id' => ['in', $gameIds]])->select();
        $gameSources = index_by_column('game_id', $gameSources);
        $gameSourceService = new GameSourceService();

        if (!empty($applys)) {
            foreach ($applys as $apply) {
                $gameSource = $gameSources[$apply['game_id']] ?? null;
                $game = $games[$apply['game_id']];
                $launchCount = $launchCountList[$apply['id']] ?? 0;
                $result = $gameSourceService->channelPack($gameSource, $game, $apply, $launchCount);
                $message = '进程[' . $progressId . '],游戏['. $apply['game_id'] . '],渠道['. $apply['promote_id'] . ']打包,';
                $packResult['total'] += 1;
                if ($result['status']) {
                    $message = 'SUCCESS ----- ' . $message . $result['message'];
                    $packResult['success'] += 1;
                } else {
                    $message = 'ERROR ----- ' . $message . $result['message'];
                    $packResult['error'] += 1;
                }
                Printer::export($message);
            }
        }
        return $packResult;
    }


    public function leak_detection()
    {
        $applymodel = M('apply', 'tab_');
        $launchmodel = M('apply_launch', 'tab_');
        $game_somodel = M('Game_source', 'tab_');
        $map['a.status'] = 1;
        $map['a.enable_status'] = 1;
        $map['al.launch_packge'] = array('in', [0, 2, 3]);
        $apply = $applymodel->alias('a')
                ->field('a.id,a.game_id,a.game_name,a.promote_account,a.pack_url,a.plist_url,a.promote_id,a.sdk_version,a.enable_status')
                ->join('tab_apply_launch as al on (al.apply_id=a.id) ')
                ->where($map)
                ->limit(300)
                ->group('a.id')
                ->select();
        foreach ($apply as $key => $value) {
            $gameSource =  $gameSourceModel
                ->field('id,file_name,source_version,file_type')
                ->where(['game_id' => $value['game_id']])
                ->find();
            $gameSourceUrl = $gameSourceService->getGameSourceUrl($gameSource);
            if ($gameSource || !file_exists($gameSourceUrl)) {
                M('apply', 'tab_') -> where(['id' => $value['id']]) -> setField('enable_status', -1);
                $launchmodel -> where(['apply_id' => $value['id']]) -> setField('launch_packge', 0);
                continue;
            }

            if (!empty($gameSourceUrl) && is_file($gameSourceUrl)) {

                $launch = $launchmodel -> where(['apply_id' => $value['id'], 'launch_packge' => array('in', [0, 2, 3])]) -> select();
                $zip = new \ZipArchive();
                foreach ($launch as $k => $v) {

                    if ($value['sdk_version'] == 1) {
                        if (!empty($v['game_source_filename'])) {
                            if ($v['game_source_filename'] == $gameSource['file_name']) {
                                if (!empty($v['launch_down_url'])) {
                                    $launchmodel -> where(['id' => $v['id']]) -> setField(['launch_packge' => 1]);
                                    continue;
                                }
                            }
                        }
                        $str_ver = '.apk';
                        $file_name = "GamePack";
                        $url_ver = "META-INF/mch.properties";
                    } else {
                        if (!empty($v['game_source_filename'])) {
                            if ($v['game_source_filename'] == $gameSource['file_name']) {
                                if (!empty($v['launch_plist_url'])) {
                                    if (!empty($v['launch_down_url'])) {
                                        $launchmodel -> where(['id' => $v['id']]) -> setField(['launch_packge' => 1]);
                                        continue;
                                    }
                                }
                            }
                        }
                        $zip_open_game_source = zip_open($gameSourceUrl);
                        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" . $value['game_id'] . "-" . $value['promote_id'] . "-" . $v['platform_id'] . "-" . $v['position'] . $str_ver;
                    $to = "./Uploads/" . $file_name . "/" . $new_name;
                    copy($gameSourceUrl, ROOTTT . ltrim($to, './'));
                    $zip_res = $zip -> open(ROOTTT . ltrim($to, './'), \ZipArchive::CREATE);
                    if ($zip_res == true) {
                        #打包数据
                        $pack_data = array(
                                "game_id" => $value["game_id"],
                                "game_name" => $value['game_name'],
                                "game_appid" => get_game_appid($value["game_id"], "id"),
                                "promote_id" => $value['promote_id'],
                                "promote_account" => $value['promote_account'],
                                "source_version" => $gameSource['source_version'],
                                'launch_id' => $v['platform_id'],
                                'position' => $v['position'],
                        );
                        $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("qiniu_storage") == 1) {

                            $this -> dleteQiNiuFile($newname);
                            $url = $this -> upQiNiuFile($newname, ROOTTT . ltrim($to, './'));
                            if (empty($url)) {
                                $this -> error('七牛错误,请检查七牛配置,并确保七牛空间权限正确!');
                            }
                            @unlink(ROOTTT . ltrim($to, './'));
                            $to = "http://" . $url;

                        } elseif (get_tool_status("cos_storage") == 1) {
                            /*$cos = A('Cos');
                            $cos -> cosupload("", "/" . $file_name . "/" . $newname, 2);
                            $cos_res = $cos -> cosupload(ROOTTT . ltrim($to, './'), "/" . $file_name . "/" . $newname);
                            if (strlen($cos_res) > 10) {
                                @unlink(ROOTTT . ltrim($to, './'));
                                $to = $cos_res;

                            } else {
                                $this -> error("Cos参数错误", U('ios_lists'));
                            }*/


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

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

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


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

                            $to = "http://" . C("bos_storage.bucket") . "." . C("bos_storage.domain") . "/" . $file_name . "/" . $newname;
                            $to = str_replace('-internal', '', $to);
                            $new_to = ROOTTT . "Uploads/" . $file_name . "/" . $newname;
                            $updata['savename'] = $newname;
                            $updata['path'] = $new_to;
                            $this -> upload_bos($updata);
                        }
                        $promote = array('game_id' => $value['game_id'], 'promote_id' => $value['promote_id']);
                        $plist_url = '';
                        if ($value['sdk_version'] == 2) {
                            $plist_url = $this -> create_plist($promote['game_id'], $promote['promote_id'], get_payload_name($value['game_id']), $to, $v['platform_id'], $v['position']);
                        }
                        $jg = $this -> update_launch_info(['platform_id' => $v['platform_id'], 'apply_id' => $value['id'], 'position'=>$v['position']], $to, $plist_url, $gameSource['file_name']);

                    }


                }


            } else {
                $applymodel -> where(['id' => $value['id']]) -> setField('enable_status', 2);
                $launchmodel -> where(['apply_id' => $value['id']]) -> setField('launch_packge', 0);
            }

        }

    }

    /**
     * 更改投放申请包信息
     *
     * @author 鹿文学
     */
    public function update_launch_info($map, $pack_url, $plist_url, $source_file)
    {
        $find_web_stie = M('config') -> field('value') -> where(['name' => 'WEB_SITE']) -> find();
        $host = 'http://' . $find_web_stie['value'];
        $hosts = 'https://' . $find_web_stie['value'];
        $model = M('apply_launch', "tab_");
        $data['launch_down_url'] = $pack_url;
        $data['launch_status'] = 1;
        $data['launch_packge'] = 1;
        $data['launch_plist_url'] = $plist_url;
        $data['game_source_filename'] = $source_file;
        $res = $model -> where($map) -> save($data);
        return $res;
    }

    /**
     * app渠道包打包
     *
     * @param  [type] $ids [description]
     *
     * @return [type]      [description]
     */
    public function app_package()
    {
        $map['status'] = 1;
        $map['enable_status'] = 2;
        $arr_id = M('app_apply', 'tab_')->field('id')->where($map)->order('id desc')->limit(300)->select();
        if (empty($arr_id)) {
            return false;
        }
        $ids = array_map('array_shift', $arr_id);
        if (!is_array($ids)) {
            $ids = [$ids];
        }
        foreach ($ids as $key => $value) {
            $apply_data = M('app_apply', 'tab_') -> find($value);
            #获取原包数据
            $source_file = M('app', 'tab_') -> find($apply_data['app_id']);
            if ($apply_data['app_version'] == 1) {
                $app_type = ".apk";
                $url_ver = "META-INF/mch.properties";
            } else {
                $app_type = ".ipa";
                $url_ver = "Payload/XiGuMobileGame.app/_CodeSignature/mch.txt";
            }
            $newname = "app_package" . $apply_data["app_id"] . "-" . $apply_data['promote_id'] . $app_type;
            $to = "./Uploads/GamePack/" . $newname;
            copy($source_file['file_url'], $to);
            #打包新路径
            $zip = new \ZipArchive;
            $res = $zip -> open($to, \ZipArchive::CREATE);
            if ($res == true) {
                #打包数据
                $pack_data = array(
                        "promote_id" => $apply_data['promote_id'],
                        "promote_account" => get_promote_name($apply_data["promote_id"]),
                );
                $zip -> addFromString($url_ver, json_encode($pack_data));
                $zip -> close();
                if (get_tool_status("oss_storage") == 1) {

                    if (C("oss_storage.is_cname")) {
                        $to = "http://" . C("oss_storage.domain") . "/GamePack/" . $newname;
                    } else {
                        $to = "https://" . C("oss_storage.bucket") . "." . C("oss_storage.domain") . "/GamePack/" . $newname;
                        $to = str_replace('-internal', '', $to);
                    }
                    $new_to = "./Uploads/GamePack/" . $newname;
                    $updata['savename'] = $newname;
                    $updata['path'] = $new_to;
                    $this -> upload_game_pak_oss($updata);
                    @unlink($new_to);
                } elseif (get_tool_status("qiniu_storage") == 1) {
                    $this -> dleteQiNiuFile($newname);
                    $url = $this -> upQiNiuFile($newname, $to);
                    @unlink($to);
                    $to = "http://" . $url;
                } elseif (get_tool_status("cos_storage") == 1) {
                    /*$cos = A('Cos');
                    $cos -> cosupload("", "/App/" . $newname, 2);
                    $cos_res = $cos -> cosupload($to, "/App/" . $newname);
                    if (strlen($cos_res) > 10) {
                        @unlink($to);
                        $to = $cos_res;

                    } else {
                        $this -> error("Cos参数错误");
                    }*/

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

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

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


                }
                if ($apply_data['app_version'] == 2) {
                    $plist_url = A('Plist') -> create_plist_app('1', $apply_data['app_id'], 'app', $to, $apply_data['promote_id']);
                    $apply_data['plist_url'] = $plist_url;
                }
                $apply_data['dow_url'] = $to;
                $apply_data['enable_status'] = 1;
                M('app_apply', 'tab_') -> save($apply_data);
            }
        }


    }


    /**
     *修改申请信息
     */
    public function updateinfo($id, $pack_url, $promote, $plist_url)
    {
        $data = [];
        $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['dispose_id'] = UID;
        $data['dispose_time'] = NOW_TIME;
        $data['plist_url'] = $plist_url;
        $res = M('Apply', 'tab_')->save($data);
        return $res;
    }


    //生成游戏渠道plist文件
    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 qiniu_ios_upload($promote_id, $game_id)
    {
        if (get_tool_status("qiniu_storage") == 1) {
            $map['channelid'] = $promote_id;
            $map['game_id'] = $game_id;
            $find = M('iospacket') -> where($map) -> find();
            if (file_exists("./Uploads/Ios/" . $find['channelpath']) && !empty($find['channelpath'])) {
                $newname = "game_package" . $find["game_id"] . "-" . $find['channelid'] . ".ipa";
                $to = "./Uploads/Ios/" . $find['channelpath'];
                $this -> dleteQiNiuFile($newname);
                $url = $this -> upQiNiuFile($newname, $to);
                if (empty($url)) {
                    $this -> error('七牛错误,请检查七牛配置,并确保七牛空间权限正确!');
                }
                unset($map['channelid']);
                $map['promote_id'] = $promote_id;
                $data['pack_url'] = $url;
                $result = M('apply', 'tab_') -> where($map) -> save($data);
                if ($result !== false) {
                    @unlink($to);
                    $this -> AjaxReturn(['status' => 1, 'msg' => '上传成功']);
                } else {
                    $this -> AjaxReturn(['status' => 0, 'msg' => '上传失败']);
                }
            } else {
                $this -> AjaxReturn(['status' => 0, 'msg' => '文件不存在或已上传云空间']);
            }
        } else {
            $this -> AjaxReturn(['status' => 0, 'msg' => '未开启七牛上传']);
        }
    }


    /**
     *上传到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());
        }
    }

    /**
     *删除OSS
     */
    public function delete_oss($objectname)
    {
        /**
         * 根据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');
        $objectname = "GamePack/" . $objectname;
        $ossClient -> deleteObject($bucket, $objectname);

    }

    /**
     *上传到BOS
     */
    public function upload_bos($return_data = null)
    {
        /**
         * 根据Config配置,得到一个OssClient实例
         */
        try {
            $BOS_TEST_CONFIG =
                    array(
                            'credentials' => array(
                                    'accessKeyId' => C("bos_storage.AccessKey"),
                                    'secretAccessKey' => C("bos_storage.SecretKey"),
                            ),
                            'endpoint' => C("bos_storage.domain"),
                    );
            require VENDOR_PATH . 'BOS/BaiduBce.phar';
            $client = new BosClient($BOS_TEST_CONFIG);
        } catch (Exception $e) {
            $this -> error($e -> getMessage());
        }
        $bucket = C('bos_storage.bucket');
        $bos_file_path = "GamePack/" . $return_data["savename"]; //在bos的路径
        $avatar = $return_data["path"];
        try {

            $client -> putObjectFromFile($bucket, $bos_file_path, $avatar);
        } catch (Exception $e) {
            $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());
        }

    }


    /*
   删除bos的object
    */
    public function delete_bos($name)
    {
        /**
         * 根据Config配置,得到一个OssClient实例
         */
        try {
            $BOS_TEST_CONFIG =
                    array(
                            'credentials' => array(
                                    'accessKeyId' => C("bos_storage.AccessKey"),
                                    'secretAccessKey' => C("bos_storage.SecretKey"),
                            ),
                            'endpoint' => C("bos_storage.domain"),
                    );
            require VENDOR_PATH . 'BOS/BaiduBce.phar';
            $client = new BosClient($BOS_TEST_CONFIG);
        } catch (Exception $e) {
            $this -> error($e -> getMessage());
        }
        $bucket = C('bos_storage.bucket');
        //$path ="icon/". $name; //在bos的路径
        $path = "GamePack/" . $name;
        $client -> deleteObject($bucket, $path);


    }


    public function game_source($game_id, $type)
    {
        $model = D('GameSource');
        $map['game_id'] = $game_id;
        $map['type'] = $type;
        $data = $model -> where($map) -> find();
        return $data;
    }

    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;
        }
    }

    /**
     * 获取七牛上传token
     */
    public function getQiNiuToken()
    {
        $this -> dleteQiNiuFile($_REQUEST['key']);
        Vendor('Qiniu.autoload');
        $config = C('qiniu_storage');
        $accessKey = $config['AccessKey'];
        $secretKey = $config['SecretKey'];
        $Qiniu = new Auth($accessKey, $secretKey);
        $bucket = $config['bucket'];
        //定义上传后返回客户端的值
        $policy = array(
                'returnBody' => '{"name":$(fname),"size":$(fsize),"key":$(key)}',
        );
        //生成上传token
        $result['uptoken'] = $Qiniu -> uploadToken($bucket, null, 3600, $policy);
        $this -> ajaxReturn($result);
    }

    /**
     * 删除七牛空间文件
     *
     * @param $key
     *
     * @return mixed
     */
    public function dleteQiNiuFile($key)
    {
        Vendor('Qiniu.autoload');
        $config = C('qiniu_storage');
        $accessKey = $config['AccessKey'];
        $secretKey = $config['SecretKey'];
        $auth = new Auth($accessKey, $secretKey);
        //初始化BucketManager
        $bucketMgr = new BucketManager($auth);
        $bucket = C('qiniu_storage.bucket');
        $res = $bucketMgr -> delete($bucket, $key);
        return $res;
    }

    /**
     * 七牛上传
     *
     * @param $newName  上传到七牛的文件名称
     * @param $filePath 文件路径
     */
    public function upQiNiuFile($newName, $filePath)
    {
        Vendor('Qiniu.autoload');
        //读取七牛配置
        $config = C('qiniu_storage');
        $accessKey = $config['AccessKey'];
        $secretKey = $config['SecretKey'];
        //实例化鉴权对象
        $auth = new Auth($accessKey, $secretKey);
        $bucket = $config['bucket'];
        //生成token
        $token = $auth -> uploadToken($bucket);
        //实例化上传类
        $uploadMgr = new UploadManager();
        //上传附件
        list($ret, $err) = $uploadMgr -> putFile($token, $newName, $filePath);
        if ($ret) {

            return $url = $config['domain'] . '/' . $newName;

        } else {
            return '';
        }
    }

    public function clearPkg() {
        $client = new ToolOssClient();
        $client->listObjects();
    }
}