<?php

namespace Home\Controller;

use Think\Controller;
use Think\Think;
use Base\Service\PromoteService;
use Base\Facade\Request;
use Base\Service\ApplyService;
use Base\Service\PackageDownloadLogService;

/**
 * @author elf<360197197@qq.com>
 */

class PackageController extends Controller
{
    protected function _initialize()
    {
        C(api('Config/lists'));
    }

    public function downloadError($message)
    {
        $this->assign('message', $message);
        $this->display('error');
    }

    public function download()
    {
        $code = I('code', '');
        $force = I('force', '');
        $gameId = I('game_id', 0);
        $promoteId = I('promote_id', 0);
        
        if ($code == '' && ($gameId == 0 || $promoteId == 0)) {
            $this->redirect("package/downloadError", ['message' => '访问错误']);
        }

        $identifier = $code != '' ? $code : 'game_id/' . $gameId . '/promote_id/' . $promoteId;
        $isBlack = M('device_bans', 'tab_')->where(['type' => 4, 'tag' => ['like', '%' . $identifier . '%']])->limit(1)->getField('id');
        if ($isBlack) {
            $this->redirect("package/downloadError", ['message' => '该链接已被禁']);
        }
        
        $applyService = new ApplyService();
        if ($code != '') {
            $data = $applyService->decodeApplyCode($code);
            $result = $applyService->checkApplyCode($data, ApplyService::ENCRYPT_TYPE_DOWNLOAD);
            if (!$result['status']) {
                $this->error($result['message']);
            }
            
            $gameId = $data['game_id'];
            $promoteId = $data['promote_id'];
        }

        $promote = M('promote', 'tab_')->field(['id', 'account', 'parent_id', 'chain', 'level'])->where(['id' => $promoteId])->find();
        if (!$promote) {
            $this->error('该链接已失效');
        }

        if (in_array($promote['account'], ['yl3xiaojian', 'huangshengchang'])) {
            $this->error('链接无效');
        }

        $promoteService = new PromoteService();
        if (!$promoteService->checkPromoteLimitRule($promote)) {
            $this->error('链接已失效');
        }

        $sdkVersion = 0;
        if (Request::isMobile() || Request::isTablet() || $force == 'ios' || $force == 'android') {
            if (Request::isAndroid() || $force == 'android') {
                $sdkVersion = 1;
            } elseif (Request::isIOS() || Request::isIPadOS() || $force == 'ios') {
                $sdkVersion = 2;
            }
        }

        $gameColumns = ['id', 'game_name', 'sdk_version', 'apply_auth', 'relation_game_id'];
        $game = M('game','tab_')->field($gameColumns)->where(['id' => $gameId])->find();
        if ($sdkVersion > 0 && $game && $game['sdk_version'] != $sdkVersion) {
            $game = M('game','tab_')->field($gameColumns)->where(['sdk_version' => $sdkVersion, 'relation_game_id' => $game['relation_game_id']])->find();
        }

        if (!$game) {
            $this->error('游戏不存在');
        }

        $map = [];
        $map['status'] = 1;
        $map['enable_status'] = 1;
        $map['game_id'] = $game['id'];
        $map['promote_id'] = $promoteId;
        $apply = M('apply','tab_')->where($map)->find();
        if (!$apply) {
            $this->redirect("package/downloadError", ['message' => '该链接已经停止使用']);
        }

        $packageUrl = $game['sdk_version'] == 1 ? $apply['pack_url'] : $apply['plist_url'];
        
        $url = $applyService->getLandingPageUrl($apply, $code);
        M('game','tab_')->where(['id' => $game['id']])->setInc('dow_num');
        $log['game_id'] = $game['id'];
        $log['game_name'] = $game['game_name'];
        $log['action'] = $url;
        $log['type'] = 6;
        $log['ip'] = get_client_ip();
        $log['create_time'] = time();
        $log['remarks'] = '记录成功';

        M('user_action_log', 'tab_')->data($log)->add();

        $downloadDomain = $applyService->getDownloadDomain();
        if ($game['sdk_version'] == 2) {
            /* if (!Request::getMobileDetect()->is('Safari')) {
                return $this->display('open_in_safari');
            } */
            $packageDownloadLogService = new PackageDownloadLogService();
            $packageDownloadLogService->add([
                'user_id' => 0,
                'game_id' => $game['id'],
                'promote_id' => $promoteId,
                'type' => 1,
            ]);

            $plistUrl = substr($packageUrl, 1, strlen($packageUrl));
            header("HTTP/1.1 303 See Other");
            header("Location: "."itms-services://?action=download-manifest&url=" . $downloadDomain . '/' . ltrim($plistUrl, '/'));
        } else {
            $this->gotoPkgUrl($packageUrl);
        }
    }

    private function gotoPkgUrl($packageUrl)
    {
        $applyService = new ApplyService();
        $downloadDomain = $applyService->getDownloadDomain();
        if (preg_match("/http/", $packageUrl)) {
            $url = str_replace('-internal', '', $packageUrl);
            echo "<script>window.location.href='$url';</script>";
        } elseif (preg_match("/clouddn/", $packageUrl)) {
            $url = "http://".$packageUrl;
            redirect($url);
        } elseif (preg_match("/myqcloud/", $packageUrl)) {
            redirect($packageUrl);
        } elseif(preg_match("/bcebos/", $packageUrl)) {
            redirect($packageUrl);
        } else {
            if (!file_exists($packageUrl)) {
                $this->error('文件不存在哦,亲!');
            }else{
                redirect($downloadDomain . ltrim($packageUrl, '.'));
            }
        }
    }

    public function addDownloadLog()
    {
        $params = $_POST;
        $packageDownloadLogService = new PackageDownloadLogService();
        if ($packageDownloadLogService->add($params)) {
            $this->ajaxReturn([
                'status' => true,
                'message' => '记录成功'
            ]);
        } else {
            $this->ajaxReturn([
                'status' => false,
                'message' => '系统异常'
            ]);
        }
    }
}