<?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', '');
        $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'];
        }

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

        $promote = M('promote', 'tab_')->field(['id', 'parent_id', 'chain', 'level'])->where(['id' => $promoteId])->find();
        $game = M('game','tab_')->field(['id', 'game_name', 'sdk_version', 'apply_auth'])->where(['id' => $apply['game_id']])->find();
        
        if (Request::isMobile() || Request::isTablet()) {
            if (!Request::isAndroid() && $game['sdk_version'] == 1) {
                $this->redirect("package/downloadError", ['message' => '请使用安卓浏览器下载']);
            }
            if (!(Request::isIOS() || Request::isIPadOS()) && $game['sdk_version'] == 2) {
                $this->redirect("package/downloadError", ['message' => '请使用ios浏览器下载']);
            }
        }

        $packageUrl = $game['sdk_version'] == 1 ? $apply['pack_url'] : $apply['plist_url'];

        M('game','tab_')->where(['id' => $game['id']])->setInc('dow_num');
        if (Request::isIOS() || Request::isIPadOS()) {
            $packageDownloadLogService = new PackageDownloadLogService();
            $packageDownloadLogService->add([
                'user_id' => 0,
                'game_id' => $gameId,
                '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=" . C('DOMAIN_DOWNLOAD') . '/' . ltrim($plistUrl, '/'));
        } else {
            $this->gotoPkgUrl($packageUrl);
        }
    }

    private function gotoPkgUrl($packageUrl)
    {
        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(C('DOMAIN_DOWNLOAD') . 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' => '系统异常'
            ]);
        }
    }
}