<?php

namespace Home\Controller;

use OT\DataDictionary;
use Admin\Model\ApplyModel;
use Think\Model;
use Base\Facade\Request;
use Base\Service\ApplyService;
use Base\Service\PromoteService;


/**
 * 前台首页控制器
 * 主要获取首页聚合数据
 */
class ApplyController extends BaseController
{

    public function jion_list($model = array(), $p, $map = array())
    {

        $page = intval($p);
        $page = $page ? $page : 1; //默认显示第一页数据
        $name = $model['name'];
        $row = empty($model['list_row']) ? 15 : $model['list_row'];
        $data = M($name, 'tab_')
            /* 查询指定字段,不指定则查询所有字段 */
            ->field(empty($fields) ? true : $fields)
            ->join($model['jion'])
            // 查询条件
            ->where($map)
            /* 默认通过id逆序排列 */
            ->order($model['need_pk'] ? 'id DESC' : '')
            /* 数据分页 */
            ->page($page, $row)
            /* 执行查询 */
            ->select();

        /* 查询记录总数 */
        $count = M($name, "tab_")->where($map)->count();

        //分页
        if ($count > $row) {
            $page = new \Think\Page($count, $row);
            $page->setConfig('theme', '%FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END% %HEADER%');
            $this->assign('_page', $page->show());
        }

        $this->assign('list_data', $data);
        $this->meta_title = $model['title'];
        $this->display($model['tem_list']);
    }

    public function gameSpecialList()
    {
        $this->index(1);
    }

    public function gameList()
    {
        $this->index(2);
    }

    //首页 $type-查询的游戏平台类型 0-全部 10-安卓+ios 2-ios 1-安卓
    public function index($serverType = 1)
    {
        $loginPromote = $this->getLoginPromote();

        $promoteId = empty(I('promote_id')) ? $loginPromote['id'] : I('promote_id'); //搜索的渠道ID
        $promoteRole = empty(I('promote_role')) ? 1 : I('promote_role'); //渠道角色
        $parentPromoteId = getParentPromoteId($promoteId); //上级渠道ID
        $grandPromoteId = getGrandPromoteId($promoteId); //本账号会长渠道ID
        $childGameAddPermission = getChildGameAddPermission($grandPromoteId); //游戏添加权限

        $map['tab_game.online_status'] = 1;//开发者游戏上线状态
        $map['tab_game.down_port'] = 1;//游戏端口 第三方接口不能申请
        $map['tab_game.game_status'] = 1;//游戏状态
        $map['tab_game.server_type'] = $serverType;//专服游戏

        if (!empty(I('game_id'))) {
            $thisRelationGameName = M('Game', 'tab_')->where(array('id' => I('game_id')))->getField('relation_game_name');

            $map['tab_game.relation_game_name'] = ['like', $thisRelationGameName];
        }

        $type = I('get.type', 0);
        $group = '';
        switch ($type) {
            case 1:
            case 2:
                $gameIdList = M('Game', 'tab_')->group('relation_game_id')->having('count(id) = 1')->getField('id', true);

                $map['tab_game.sdk_version'] = $type;

                $applyService = new ApplyService();
                $tempIds = $applyService->getSociatyGameIds($loginPromote);
                $gameIdList = array_intersect($gameIdList, $tempIds);

                if (count($gameIdList) > 0) {
                    $gameIds = implode(',', $gameIdList);

                    $map['tab_game.id'] = ['in', $gameIds];
                } else {
                    $map = '1 = 2';
                }
                break;
            case 10:
                $group = 'tab_game.relation_game_id';

                if ($parentPromoteId > 0 && $childGameAddPermission == 0) {
                    $gameRelationGameIdList = M('Game', 'tab_')->group('relation_game_id')->having('count(id) = 2')->getField('relation_game_id', true);
                    if (count($gameRelationGameIdList) > 0) {
                        $gameRelationGameIdList = implode(',', $gameRelationGameIdList);

                        $where['tab_game.relation_game_id'] = ['in', $gameRelationGameIdList];
                    } else {
                        $where = '1 = 2';
                    }
                } else {
                    $gameIdList = M('Game', 'tab_')->group('relation_game_id')->having('count(id) = 2')->getField('id', true);

                    $applyService = new ApplyService();
                    $tempIds = $applyService->getSociatyGameIds($loginPromote);
                    $gameIdList = array_intersect($gameIdList, $tempIds);

                    if (count($gameIdList) > 0) {
                        $gameIds = implode(',', $gameIdList);
                        $map['tab_game.id'] = ['in', $gameIds];
                    } else {
                        $map = '1 = 2';
                    }
                }
                break;
            case 0:
                $applyService = new ApplyService();
                $gameIdList = $applyService->getSociatyGameIds($loginPromote);
                if (count($gameIdList) > 0) {
                    $gameIds = implode(',', $gameIdList);
                    $map['tab_game.id'] = ['in', $gameIds];
                } else {
                    $map = '1 = 2';
                }
        }

        $page = intval(I('get.p', 0));
        $page = $page ? $page : 1; //默认显示第一页数据

        if (isset($_REQUEST['row'])) {
            $row = $_REQUEST['row'];
        } else {
            $row = 10;
        }

        $join = '';
        if ($parentPromoteId > 0 && $childGameAddPermission == 0) {
            $map['tab_apply.promote_id'] = $grandPromoteId;
            if (!empty($where)) {
                $map['_logic'] = 'and';
                $map['_complex'] = $where;
            }

            $join = 'tab_apply on tab_game.id = tab_apply.game_id and tab_apply.offline_status = 0';//查询上级游戏
        }

        $data = M('Game', 'tab_')
            ->field('tab_game.id,tab_game.icon,tab_game.game_name,tab_game.features,tab_game.sdk_version,tab_game.game_size,tab_game.game_type_name,tab_game.relation_game_name,ta_1.id as apply_id_1,ta_2.id as apply_id_2')
            ->join($join)
            ->join('left join tab_apply as ta_1 on tab_game.id = ta_1.game_id and ta_1.offline_status = 0 and ta_1.promote_id = ' . $promoteId)//查询是否拥有该游戏
            ->join('left join tab_apply as ta_2 on tab_game.relation_game_id = ta_2.game_id and ta_2.offline_status = 0 and tab_game.id != tab_game.relation_game_id and ta_2.promote_id = ' . $promoteId)//查询是否拥有关联游戏
            ->join('left join tab_game_source on tab_game.id = tab_game_source.game_id')//查询游戏版本
            ->where($map)
            ->group($group)
            ->order('tab_game.sort desc,tab_game.id desc')
//            ->fetchSql(true)
            ->page($page, $row)
            ->select();

//        var_dump($data);
//        die;

        /* 查询记录总数 */
        $count = M("Game", "tab_")
            ->field('tab_game.id')
            ->join($join)//查询上级游戏
            ->where($map)
            ->group($group)
            ->select();
        $count = count($count);

        //分页
        $parameter['p'] = I('get.p', 1);
        $parameter['row'] = I('get.row');
        $parameter['type'] = $type;
        $parameter['promote_role'] = $promoteRole;
        empty(I('promote_id')) || $parameter['promote_id'] = I('promote_id');

        $page = set_pagination($count, $row, $parameter);
        if ($page) {
            $this->assign('_page', $page);
        }

        $this->assign('list_data', $data);
        $this->assign("count", $count);
        $this->assign('loginPromote', $loginPromote);
        $this->assign("promoteId", $promoteId);
        $this->assign('promoteRole', $promoteRole);
        $this->assign('promoteData', getAllPromoteListByType($promoteRole));
        $this->assign('type', $type);
        $this->assign('myGame', ($serverType == 1) ? 'specialMyGameList' : 'myGameList');
        $this->assign('game', ($serverType == 1) ? 'gameSpecialList' : 'gameList');
        $this->assign('position', ($serverType == 1) ? '专服管理' : '混服管理');
        $this->meta_title = "申请游戏";
        $this->display('index');
    }

    //查看游戏资料专区
    public function feature($p = 0, $type = 0)
    {
        $map = ['_string' => '1=1'];
        $map['online_status'] = 1;//开发者游戏上线状态
        $map['down_port'] = 1;//游戏端口 第三方接口不能申请
        $map['game_status'] = 1;//游戏状态
        $map['developers'] = 0; //平台游戏(官网游戏,非开发者游戏)

        $promote = $this->getLoginPromote();
        $promoteService = new PromoteService();
        $gameIds = $promoteService->getVisibleGameIds($promote);
        if (count($gameIds) > 0) {
            $map['id'] = ['in', $gameIds];
        } else {
            $map['_string'] .= ' and 1<>1';
        }
        
        if (!empty(I('game_id'))) {
            $relationGameId = M('game', 'tab_')->where(array('id' => I('game_id')))->getField('relation_game_id');
            if ($relationGameId) {
                $map['_string'] .= ' and relation_game_id=' . $relationGameId;
            } else {
                $map['_string'] .= ' and 1<>1';
            }
        }

        $query = M('game', 'tab_')
            ->field('id,icon,game_name,features,sdk_version,game_size,game_type_name,relation_game_name')
            ->where($map)
            ->order('developers desc,sort desc,id desc');

        list($records, $pagination, $count) = $this->paginate($query);

        $this->assign('pagination', $pagination);
        $this->assign('records', $records);
        $this->assign('count', $count);
        $this->assign('games', $this->getSelectGames());
        $this->meta_title = "资料专区";
        $this->display();
    }

    //查看游戏详情
    public function viewGameDetailed()
    {
        $id = $_POST['id'];
        $gameData = array();

        if ($id > 0) {
            $map['tab_game.id'] = $id;

            $gameData = M('Game', 'tab_')
                ->join('left join tab_game_source on tab_game.id = tab_game_source.game_id')
                ->where($map)
                ->field('tab_game.*,tab_game_source.version,tab_game_source.create_time')
                ->find();

            if (!empty($gameData['create_time'])) {
                $gameData['create_time'] = date('Y-m-d H:i:s', $gameData['create_time']);
            }

            $gameData['icon'] = __ROOT__ . get_cover($gameData['icon'], 'path');
            $gameData['screenshot'] = explode(',', $gameData['screenshot']);

            foreach ($gameData['screenshot'] as $value) {
                $gameData['screenshot_url'][] = get_cover($value, 'path');
            }
        }

        $this->ajaxReturn($gameData);
    }

    public function gapply()
    {
        $map1['relation_game_id'] = array('in', $_REQUEST['game_id']);
        $res = M('game', 'tab_')->field('id')->where($map1)->select();
        $res = array_map('array_shift', $res);
        $_REQUEST['game_id'] = implode(',', $res);

        $model = new ApplyModel(); //D('Apply');
        $map['game_id'] = array('in', $_REQUEST['game_id']);
        $map['promote_id'] = session("promote_auth.pid");
        $c = $model->where($map)->select();
        $_REQUEST['game_id'] = explode(',', $_REQUEST['game_id']);
        foreach ($c as $key => $value) {
            $va[] = $value['game_id'];
        }
        if (!empty($va)) {
            $game_id = array_diff($_REQUEST['game_id'], $va);
        } else {
            $game_id = $_REQUEST['game_id'];
        }

        if (empty($game_id)) {
            $this->ajaxReturn(array("status" => "0", "msg" => "游戏已申请过,请勿重复申请"));
            exit;
        }
        $_REQUEST['game_id'] = implode(',', $game_id);
        $data['game_id'] = array('in', $_REQUEST['game_id']);
        $data['promote_id'] = session("promote_auth.pid");
        $data['promote_account'] = session("promote_auth.account");
        $data['apply_time'] = NOW_TIME;
        $data['status'] = 0;
        $game = M('Game', 'tab_');
        foreach ($game_id as $key => $value) {
            $data['game_id'] = $value;
            $gdata = $game->where(array('id' => $value))->find();
            $data['game_name'] = get_game_name($value);
            $data['ratio'] = $gdata['ratio'];
            $data['money'] = $gdata['money'];
            $data['sdk_version'] = $gdata['sdk_version'];
            // $data['pattern']=current($pattern);
            // next($pattern);
            $res = $model->add($data);
        }
        if ($res) {
            $this->ajaxReturn(array("status" => "1", "msg" => "申请成功"));
        } else {
            $this->ajaxReturn(array("status" => "0", "msg" => "申请失败"));
        }
    }

    /**
     * 批量添加投放申请
     * @author 鹿文学
     */
    public function batch_apply_game()
    {
        if (IS_POST) {
            $relation_game_ids = $_POST['game_id'];
            $platform_id = $_POST['platform_id'];
            $platform_name = $_POST['platform_name'];
            $remark = $_POST['remark'];
            $promote_id = is_login_promote();

            if ($promote_id < 1) {
                $this->ajaxReturn(['status' => 0, 'msg' => '请登录后再操作'], 'json');
            }

            if (empty($relation_game_ids)) {
                $this->ajaxReturn(['status' => 0, 'msg' => '你还没有选择任何内容!'], 'json');
            }

            if ((!is_numeric($platform_id) || $platform_id < 1) && empty($platform_name)) {
                $this->ajaxReturn(['status' => 0, 'msg' => '投放平台不能为空'], 'json');
            }

            $gamemodel = M('Game', 'tab_');

            $game = $gamemodel->field('id,game_name,sdk_version,ratio,money')->where(['relation_game_id' => ['in', $relation_game_ids]])->select();

            if (!is_array($game) || empty($game[0])) {
                $this->ajaxReturn(['status' => 0, 'msg' => '游戏不存在'], 'json');
            }

            $game_id = array_column($game, 'id');


            // 先查投放平台,如有渠道输入则先判断平台是否存在,不存在则添加,存在则获取信息;没有趣的输入,则判断选择平台是否存在,不存在返回

            $platformmodel = M('launch_platform', 'tab_');


            if ($platform_name) {
                $platform = $platformmodel->where(['name' => $platform_name])->find();

                if (empty($platform)) {
                    $platform_id = $platformmodel->add(['create_time' => time(), 'update_time' => time(), 'name' => $platform_name, 'promote_id' => $promote_id, 'promote_account' => get_promote_account($promote_id), 'mark' => 1]);
                } else {
                    $platform_id = $platform['id'];
                }

            } else {

                $platform = $platformmodel->where(['id' => $platform_id])->find();
                if (empty($platform)) {
                    $this->ajaxReturn(['status' => 0, 'msg' => '投放平台选择有误,请重新选择'], 'json');
                }

            }

            // 再查申请表,数据是否存在,存在则不予理会,不存在则添加

            $applymodel = M('Apply', 'tab_');

            $apply = $applymodel->field('id,game_id,status')->where(['promote_id' => $promote_id, 'game_id' => ['in', $game_id]])->select();

            $exist = 1;

            if (empty($apply)) {

                $apply = $this->add_apply($applymodel, $game, $promote_id, $game_id);

                $exist = C('SET_AUTO_PACK');

            }

            foreach ($apply as $k => $v) {
                foreach ($game as $m => $n) {
                    if ($v['game_id'] == $n['id']) {
                        unset($game[$m]);
                    }
                }
            }

            if (!empty($game)) {
                $apply = $this->add_apply($applymodel, $game, $promote_id, $game_id);
            }

            $apply_ids = array_column($apply, 'id');

            if ($platform_id > 0 && is_array($apply_ids)) {

                $launchmodel = M('apply_launch', 'tab_');

                $launch = $launchmodel->field('platform_id,apply_id,max(position) as position')->where(['platform_id' => $platform_id, 'apply_id' => ['in', $apply_ids]])->group('platform_id,apply_id')->order('launch_time desc')->select();

                if (empty($launch)) {

                    foreach ($apply as $k => $v) {
                        $data[] = array(
                            'platform_id' => $platform_id,
                            'apply_id' => $v['id'],
                            'launch_game_id' => $v['game_id'],
                            'launch_time' => time(),
                            'position' => 1,
                            'remark' => $remark,
                        );

                    }

                } else {

                    foreach ($apply as $k => $v) {
                        $flag = true;
                        foreach ($launch as $m => $n) {

                            if ($n['apply_id'] == $v['id']) {
                                if ($v['status'] == 1) {
                                    $data[$k] = array(
                                        'platform_id' => $platform_id,
                                        'apply_id' => $v['id'],
                                        'launch_game_id' => $v['game_id'],
                                        'launch_time' => time(),
                                        'position' => $n['position'] > 0 ? (intval($n['position']) + 1) : 1,
                                        'remark' => $remark,
                                    );
                                    break;
                                } else {
                                    $flag = false;
                                }
                            }

                        }
                        if (!$data[$k] && $flag) {
                            $data[$k] = array(
                                'platform_id' => $platform_id,
                                'apply_id' => $v['id'],
                                'launch_game_id' => $v['game_id'],
                                'launch_time' => time(),
                                'position' => 1,
                                'remark' => $remark,
                            );
                        }

                    }

                }

                $res = $launchmodel->addAll($data);

                if ($res > 0) {
                    $this->ajaxReturn(['status' => 1, 'msg' => '申请成功', 'exist' => $exist], 'json');
                } else {
                    $this->ajaxReturn(['status' => 0, 'msg' => '申请失败'], 'json');
                }

            } else {
                $this->ajaxReturn(['status' => 0, 'msg' => '申请失败,请重新申请'], 'json');
            }

        } else {

            $this->ajaxReturn(['status' => 0, 'msg' => '请求有误'], 'json');

        }

    }

    /**
     * 批量添加申请并返回符合条件的申请信息
     * @param object $applymodel 申请表模型对象
     * @param array $game 游戏数组对象
     * @param integer $promote_id 渠道编号
     * @param array $game_id 要查找的游戏编号数组
     * @param string $fields 查询字段
     * @param array            根据条件获取的申请信息数组
     * @author 鹿文学
     */
    private function add_apply($applymodel, $game, $promote_id, $game_id, $fields = 'id,game_id,status')
    {

        foreach ($game as $k => $v) {
            $data[] = array(
                'game_id' => $v['id'],
                'game_name' => $v['game_name'],
                'promote_id' => $promote_id,
                'promote_account' => session("promote_auth.account"),
                'apply_time' => time(),
                'status' => C('SET_AUTO_PACK'),
                'dispose_time' => C('SET_AUTO_PACK') ? time() : '',
                'sdk_version' => $v['sdk_version'],
                'ratio' => $v['ratio'],
                'money' => $v['money'],
            );

        }


        $applymodel->addAll($data);

        $apply = $applymodel->field($fields)->where(['promote_id' => $promote_id, 'game_id' => ['in', $game_id]])->select();

        return $apply;

    }

    public function specialMyGameList()
    {
        $this->my_game(1);
    }

    public function myGameList()
    {
        $this->my_game(2);
    }

    public function my_game($serverType = 1)
    {
        $loginPromote = $this->getLoginPromote();

        //渠道可申请游戏
        if (empty($_REQUEST['promote_id'])) {
            $promoteId = $loginPromote['id'];
        } else {
            $promoteId = $_REQUEST['promote_id'];
        }

        $applyService = new ApplyService();
        $gameIdList = $applyService->getSociatyGameIds($loginPromote);

        $applyMap['promote_id'] = $promoteId;
        $applyMap['offline_status'] = 0;
        $applyMap['game_id'] = ['in', $gameIdList];

        $gameIds = M('Apply', 'tab_')->where($applyMap)->getField('game_id', true);
        $gameIds = implode(',', $gameIds);

        if (empty($gameIds)) {
            $map['_string'] = '1 = 2';
        } else {
            $map['tab_game.id'] = ['in', $gameIds];
        }

        $map['tab_apply.promote_id'] = $promoteId;
        $map['tab_game.online_status'] = 1;//开发者游戏上线状态
        $map['tab_game.down_port'] = 1;//游戏端口 第三方接口不能申请
        $map['tab_game.game_status'] = 1;//游戏状态
        $map['tab_game.server_type'] = $serverType;//游戏服务器类型

        if ($_REQUEST['game_id'] != null) {
            $relationGameName = M('Game', 'tab_')->where(array('id' => $_REQUEST['game_id']))->getField('relation_game_name');
            if ($relationGameName) {
                $map['tab_game.relation_game_name'] = ['like', $relationGameName];
            } else {
                $map['tab_apply.game_id'] = $_REQUEST['game_id'];
            }
        }
        if ($_REQUEST['pattern'] != null) {
            $map['tab_apply.pattern'] = $_REQUEST['pattern'];
        }

        $page = intval(I('get.p', 0));
        $page = $page ? $page : 1; //默认显示第一页数据

        if (isset($_REQUEST['row'])) {
            $row = $_REQUEST['row'];
        } else {
            $row = 10;
        }

        $data = M("game", "tab_")
            /* 查询指定字段,不指定则查询所有字段 */
            ->field("tab_game.id,tab_game.game_size,tab_game.game_name,tab_game.features,tab_game.money,tab_game.sdk_version,tab_game.ratio,tab_game.icon,tab_game.game_type_name,tab_game.recommend_status,promote_id,status,tab_apply.dow_status,tab_apply.plist_url,tab_apply.id as applyid,tab_apply.enable_status,tab_game.sort,tab_game.relation_game_id,tab_game.relation_game_name,tab_game.material_url,dispose_time,tab_apply.promote_money as applymoney,tab_apply.promote_ratio as applyratio,apply_time,tab_apply.status as applystatus,tab_game.and_dow_address,tab_game.ios_dow_address,tab_game.add_game_address,tab_game.ios_game_address")
            ->join("tab_apply ON tab_game.id = tab_apply.game_id and tab_apply.promote_id = " . $promoteId)
//            ->join("left join tab_game as tg ON (tab_game.id = tg.relation_game_id and tg.game_status = 1 and tab_game.id!=tab_game.relation_game_id) or (tab_game.id = tg.relation_game_id  and tab_game.id!=tg.id and tg.game_status = 1) or (tab_game.id!=tab_game.relation_game_id and tab_game.relation_game_id=tg.id and tab_game.game_status=1)")
            // 查询条件
            ->where($map)
            /* 默认通过id逆序排列 */
            ->order("apply_time desc,id desc")
            /* 数据分页 */
            ->page($page, $row)
            /* 执行查询 */
            ->select();

        /* 查询记录总数 */
        $count = count(M("game", "tab_")
            /* 查询指定字段,不指定则查询所有字段 */
            ->field("tab_game.*,tab_apply.promote_id,tab_apply.status")
            ->join("tab_apply ON tab_game.id = tab_apply.game_id and tab_apply.promote_id = " . $promoteId)
            // 查询条件
            ->where($map)
            ->select());
        //分页

        $parameter = array(
            'row' => I('get.row'),
            'sdk_version' => I('request.sdk_version'),
            'p' => I('p', 1),
            'type' => I('request.type'),
            'enable_status' => I('request.enable_status'),
            'game_id' => I('request.game_id'),
        );

        $page = set_pagination($count, $row, $parameter);
        if ($page) {
            $this->assign('_page', $page);
        }

        $promoteRole = empty(I('promote_role')) ? 1 : I('promote_role');

        $url = "http://" . $_SERVER['HTTP_HOST'] . __ROOT__ . "/media.php/member/preg/pid/" . session("promote_auth.pid");
        $this->assign("url", $url);
        $this->assign("count", $count);
        $this->assign("row", $row);
        $this->assign('loginPromote', $loginPromote);
        $this->assign('promoteId', $promoteId);
        $this->assign('promoteRole', $promoteRole);
        $this->assign('promoteData', getAllPromoteListByType($promoteRole));
        $this->assign('list_data', $data);
        $this->assign('serverType', $serverType);
        $this->assign('myGame', ($serverType == 1) ? 'specialMyGameList' : 'myGameList');
        $this->assign('game', ($serverType == 1) ? 'gameSpecialList' : 'gameList');
        $this->assign('position', ($serverType == 1) ? '专服管理' : '混服管理');
        $this->meta_title = "我的游戏";
        $this->display('my_game');
    }


    public function my_game_ch($type = -1, $p = 0)
    {
        //渠道可申请游戏
        $game_ids = M('promote', 'tab_')->where(['id' => get_pid()])->getField('game_ids');
        if (!empty($game_ids) || $game_ids === '0') {
            $game_ids = explode(',', $game_ids);
            $map['tab_game.id'] = ['in', $game_ids];
        }
        $map['promote_id'] = session("promote_auth.pid");
        $map['tab_game.game_status'] = 1;//游戏状态

        if ($_REQUEST['game_id'] != null) {
            $map['tab_game.relation_game_id'] = $_REQUEST['game_id'];
        }
        $res = M('game', 'tab_')->where(['relation_game_id' => $_REQUEST['game_id']])->find();
        if (empty($res) && $_REQUEST['game_id']) {
            $res_ = M('game', 'tab_')->find($_REQUEST['game_id']);
            $map['tab_game.relation_game_id'] = $res_['relation_game_id'];
        }
        $map['tab_apply.status'] = 0;

        $page = intval($p);
        $page = $page ? $page : 1; //默认显示第一页数据

        $row = 6;

        if (isset($_REQUEST['row'])) {
            $row = $_REQUEST['row'];
        } else {
            $row = 10;
        }

        $data = M("game", "tab_")
            /* 查询指定字段,不指定则查询所有字段 */
            ->field("tab_game.id,tab_game.game_size,tab_game.game_name,tab_game.money,tab_game.sdk_version,tab_game.ratio,tab_game.icon,tab_game.game_type_name,tab_game.recommend_status,promote_id,status,tab_apply.dow_status,tab_apply.plist_url,tab_apply.id as applyid,enable_status,tab_game.sort,tab_game.relation_game_id,tab_game.relation_game_name,tab_game.material_url,tg.relation_game_id as trelation_game_id,tg.id as tid,tg.sdk_version as tsdk_version,tg.game_size as tgame_size,tg.money as tmoney,tg.ratio as tratio,tg.material_url as tmaterial_url,dispose_time,apply_time,tab_apply.promote_money as applymoney,tab_apply.promote_ratio as applyratio,tab_apply.status as applystatus")
            ->join("tab_apply ON tab_game.id = tab_apply.game_id and tab_apply.promote_id = " . session('promote_auth.pid'))
            ->join("left join tab_game as tg ON (tab_game.id = tg.relation_game_id and tg.game_status = 1 and tab_game.id!=tab_game.relation_game_id) or (tab_game.id = tg.relation_game_id  and tab_game.id!=tg.id and tg.game_status = 1) or (tab_game.id!=tab_game.relation_game_id and tab_game.relation_game_id=tg.id and tab_game.game_status=1)")
            // 查询条件
            ->where($map)
            /* 默认通过id逆序排列 */
            ->order("id desc")
            ->group("relation_game_id")
            /* 数据分页 */
            ->page($page, $row)
            /* 执行查询 */
            ->select();
        $applymodel = M('apply', 'tab_');
        $launchmodel = M('apply_launch', 'tab_');
        foreach ($data as $key => $value) {

            if ($value['sdk_version'] == 2 && $value['tsdk_version'] == 1) {
                $game_ios = get_game_info($value['id']);
                $game_and = get_game_info($value['tid']);
                $data[$key] = $game_and;
                $data[$key]['tid'] = $game_ios['id'];
                $data[$key]['tsdk_version'] = $game_ios['sdk_version'];
                $data[$key]['tgame_size'] = $game_ios['game_size'];
                $data[$key]['tmoney'] = $game_ios['money'];
                $data[$key]['tratio'] = $game_ios['ratio'];
                $data[$key]['dispose_time'] = $game_ios['dispose_time'];
                $data[$key]['tapplymoney'] = $apply_info['promote_money'];
                $data[$key]['tapplyratio'] = $apply_info['promote_ratio'];
            }
        }

        foreach ($data as $key => $value) {
            $apply = $applymodel->field('id,status')->where(['promote_id' => get_pid(), 'game_id' => $value['tid']])->find();

            if ($value['applyid']) {
                $platform = $launchmodel->field('platform_id')->where(['apply_id' => $value['applyid']])->find();
                $data[$key]['platform_id'] = $platform['platform_id'];
            } else {
                $data[$key]['applyid'] = 0;
            }

            if ($apply['id']) {
                $data[$key]['tapplyid'] = $apply['id'];
                $tplatform = $launchmodel->field('platform_id')->where(['apply_id' => $apply['id']])->find();
                $data[$key]['tplatform_id'] = $tplatform['platform_id'];
                $data[$key]['tapplystatus'] = $apply['status'];
            } else {
                $data[$key]['tapplyid'] = 0;
                $data[$key]['tapplystatus'] = 0;
            }
        }

        /* 查询记录总数 */
        $count = count(M("game", "tab_")
            /* 查询指定字段,不指定则查询所有字段 */
            ->field("tab_game.*,tab_apply.promote_id,tab_apply.status")
            ->join("tab_apply ON tab_game.id = tab_apply.game_id and tab_apply.promote_id = " . session('promote_auth.pid'))
            // 查询条件
            ->where($map)
            ->group("relation_game_id")
            ->select());

        //分页

        $parameter = array(
            'row' => I('get.row'),
            'sdk_version' => I('request.sdk_version'),
            'p' => I('p', 1),
            'type' => I('request.type'),
            'enable_status' => I('request.enable_status'),
            'game_id' => I('request.game_id'),
        );

        $page = set_pagination($count, $row, $parameter);
        if ($page) {
            $this->assign('_page', $page);
        }


        $url = "http://" . $_SERVER['HTTP_HOST'] . __ROOT__ . "/media.php/member/preg/pid/" . session("promote_auth.pid");
        $this->assign("url", $url);
        $this->assign("count", $count);
        $this->assign('model', $model);
        $this->assign('list_data', $data);
        $this->meta_title = "我的游戏";
        $this->display();
    }


    public function child_game($p = 0)
    {
        $loginPromote = $this->getLoginPromote();
        if ($loginPromote['level'] > 3) {
            echo '<script>window.location.go(-1);</script>';
            exit;
        }

        if (!empty($_REQUEST['game_id'])) {
            $map['tab_apply.game_id'] = $_REQUEST['game_id'];
        }
        if (!empty($_REQUEST['promote_id'])) {
            $map['tab_apply.promote_id'] = $_REQUEST['promote_id'];
        } else {
            $sid = M('Promote', 'tab_')->field('id')->where(array('parent_id' => PID, 'status' => 1))->select();
            if ($sid) {
                $map['tab_apply.promote_id'] = array('in', array_column($sid, 'id'));
            } else {
                $map['tab_apply.promote_id'] = -1;
            }
        }
        $map['tab_game.game_status'] = 1;//游戏状态
        $start_time = strtotime(I('time_start'));
        $end_time = strtotime(I('time_end'));
        if (!empty($start_time) && !empty($end_time)) {
            $map['tab_apply.dispose_time'] = ['BETWEEN', [$start_time, $end_time + 24 * 60 * 60 - 1]];
            unset($_REQUEST['time_start']);
            unset($_REQUEST['time_end']);
        } else if (!empty($start_time)) {
            $map['tab_apply.dispose_time'] = array('gt', $start_time);
        } else if (!empty($end_time)) {
            $map['tab_apply.dispose_time'] = array('lt', $end_time + 24 * 60 * 60 - 1);
        }
        $map['tab_apply.status'] = 1;

        $page = intval($p);
        $page = $page ? $page : 1; //默认显示第一页数据


        if (isset($_REQUEST['row'])) {
            $row = $_REQUEST['row'];
        } else {
            $row = 10;
        }

        $data = M("game", "tab_")
            /* 查询指定字段,不指定则查询所有字段 */
            ->field("tab_game.id,tab_game.game_size,tab_game.game_name,tab_game.money,tab_game.sdk_version,tab_game.ratio,tab_game.icon,tab_game.game_type_name,tab_game.recommend_status,promote_id,promote_account,status,tab_apply.dow_status,tab_apply.plist_url,tab_apply.id as applyid,enable_status,tab_game.sort,tab_game.relation_game_id,tab_game.relation_game_name,tab_game.material_url,tg.relation_game_id as trelation_game_id,tg.id as tid,tg.game_name as tgame_name,tg.sdk_version as tsdk_version,tg.game_size as tgame_size,tg.money as tmoney,tg.ratio as tratio,tg.material_url as tmaterial_url,dispose_time,apply_time,promote_account,tab_apply.promote_money as applymoney,tab_apply.promote_ratio as applyratio,tab_apply.status as applystatus")
            ->join("tab_apply ON tab_game.id = tab_apply.game_id ")
            ->join("left join tab_game as tg ON (tab_game.id = tg.relation_game_id and tg.game_status = 1 and tab_game.id!=tab_game.relation_game_id) or (tab_game.id = tg.relation_game_id  and tab_game.id!=tg.id and tg.game_status = 1) or (tab_game.id!=tab_game.relation_game_id and tab_game.relation_game_id=tg.id and tab_game.game_status=1)")
            // 查询条件
            ->where($map)
            /* 默认通过id逆序排列 */
            ->order("id desc")
            ->group("tab_apply.promote_id,relation_game_id")
            /* 数据分页 */
            ->page($page, $row)
            /* 执行查询 */
            ->select();
        $count = count(M("game", "tab_")
            /* 查询指定字段,不指定则查询所有字段 */
            ->field("tab_game.*,tab_apply.promote_id,tab_apply.status")
            ->join("tab_apply ON tab_game.id = tab_apply.game_id ")
            // 查询条件
            ->where($map)
            ->group("tab_apply.promote_id,relation_game_id")
            ->select());
        $applymodel = M('apply', 'tab_');
        $launchmodel = M('apply_launch', 'tab_');
        foreach ($data as $key => $value) {
            if ($value['sdk_version'] == 2 && $value['tsdk_version'] == 1) {
                $game_ios = get_game_info($value['id']);
                $game_and = get_game_info($value['tid']);
                $apply_info = M('apply', 'tab_')->where(['game_id' => $value['id'], 'promote_account' => $value['promote_account']])->find();
                $data[$key] = $game_and;
                $data[$key]['tid'] = $game_ios['id'];
                $data[$key]['tsdk_version'] = $game_ios['sdk_version'];
                $data[$key]['tgame_size'] = $game_ios['game_size'];
                $data[$key]['tmoney'] = $game_ios['money'];
                $data[$key]['tratio'] = $game_ios['ratio'];
                $data[$key]['applyid'] = $apply_info['id'];
                $data[$key]['enable_status'] = $apply_info['enable_status'];
                $data[$key]['promote_id'] = $apply_info['promote_id'];
                $data[$key]['promote_account'] = $apply_info['promote_account'];
                $data[$key]['applymoney'] = $apply_info['promote_money'];
                $data[$key]['tapplyratio'] = $apply_info['promote_ratio'];
                $data[$key]['tapply_time'] = $apply_info['apply_time'];
                $data[$key]['dispose_time'] = $apply_info['apply_time'];
            }
        }

        foreach ($data as $key => $value) {
            $apply = $applymodel->field('id,status')->where(['promote_id' => $value['promote_id'], 'game_id' => $value['tid']])->find();

            if ($value['applyid']) {
                $data[$key]['launch_count'] = $launchmodel->where(['apply_id' => $value['applyid']])->count();
            } else {
                $data[$key]['applyid'] = 0;
            }

            if ($apply['id']) {
                $data[$key]['tapplyid'] = $apply['id'];
                $data[$key]['tlaunch_count'] = $launchmodel->where(['apply_id' => $apply['id']])->count();
                $data[$key]['tapplystatus'] = $apply['status'];
            } else {
                $data[$key]['tapplyid'] = 0;
                $data[$key]['tapplystatus'] = 0;
            }
        }

        //分页


        $parameter = $_POST;
        $parameter['p'] = I('get.p', 1);
        $parameter['row'] = I('get.row');


        $page = set_pagination($count, $row, $parameter);
        if ($page) {
            $this->assign('_page', $page);
        }


        $this->assign("count", $count);
        $this->assign('model', $model);
        $this->assign('list_data', $data);
        $this->meta_title = "子渠道游戏";
        $this->display();
    }


    public function changevalue()
    {
        if (IS_POST) {
            if (!is_numeric($_REQUEST['id']) || $_REQUEST['id'] <= 0) {
                echo json_encode(array('status' => 0, 'info' => '数据有误'));
                exit;
            }
            if (!is_numeric($_REQUEST['value']) || $_REQUEST['value'] < 0) {
                echo json_encode(array('status' => 0, 'info' => '数据有误'));
                exit;
            }
            $apply = M('apply', 'tab_');
            if ($_REQUEST['type'] == 1) {
                $res = $apply->where(array('id' => $_REQUEST['id']))->setField(array('promote_money' => $_REQUEST['value']));
                if ($res) {
                    echo json_encode(array('status' => 1, 'info' => '注册单价修改成功'));
                    exit;
                } else {
                    echo json_encode(array('status' => 0, 'info' => '注册单价修改失败'));
                    exit;
                }
            } elseif ($_REQUEST['type'] == 2) {
                $res = $apply->where(array('id' => $_REQUEST['id']))->setField(array('promote_ratio' => $_REQUEST['value']));
                if ($res) {
                    echo json_encode(array('status' => 1, 'info' => '分成比例修改成功'));
                    exit;
                } else {
                    echo json_encode(array('status' => 0, 'info' => '分成比例修改失败'));
                    exit;
                }
            } else {
                echo json_encode(array('status' => 0, 'info' => '数据有误'));
                exit;
            }
        } else {
            echo json_encode(array('status' => 0, 'info' => '数据有误'));
            exit;
        }
    }

    /**
     * 申请游戏
     */
    public function apply()
    {
        if ($_POST['game_id']) {
            $loginPromote = $this->getLoginPromote();
            $promoteService = new PromoteService();
            if (!$promoteService->isPresidentAccess($loginPromote)) {
                $this->ajaxReturn([
                    'status' => 0, 
                    'msg' => '请联系市场专员开启',
                ]);
            }

            $gameMap['tab_game.id'] = $_POST['game_id'];

            $promoteId = I('promote_id');
            if (empty($promoteId)) {
                $promoteId = $loginPromote['id'];
            }

            if ($promoteId == $loginPromote['id']) {
                $promoteData = $loginPromote;
            } else {
                $promoteData = D('Promote')->where(array('id' => $promoteId))->find();
            }

            $grandPromoteId = getGrandPromoteId($promoteId);
            $grandPromoteId = empty($grandPromoteId) ? $promoteData['parent_id'] : $grandPromoteId;//本账号会长渠道ID
            $childGameAddPermission = getChildGameAddPermission($grandPromoteId);//游戏添加权限

            if ($_POST['sdk_type'] > 0) {
                if ($promoteData['parent_id'] > 0 && $childGameAddPermission == 0) {
                    $gameRelationName = M('game', 'tab_')->where(array('id' => $_POST['game_id']))->getField('relation_game_name');
                    $gameData = M('game', 'tab_')
                        ->field('tab_game.*')
                        ->join('tab_apply on tab_game.id = tab_apply.game_id and tab_apply.offline_status = 0 and tab_apply.promote_id = ' . $grandPromoteId)
                        ->where(array('tab_game.relation_game_name' => $gameRelationName))
                        ->select();
                } else {
                    $gameRelationName = M('game', 'tab_')->where(array('id' => $_POST['game_id']))->getField('relation_game_name');
                    $gameData = M('game', 'tab_')
                        ->where(array('relation_game_name' => $gameRelationName))
                        ->select();
                }
            } else {
                if ($promoteData['parent_id'] > 0 && $childGameAddPermission == 0) {
                    $gameData = M('game', 'tab_')
                        ->field('tab_game.*')
                        ->join('tab_apply on tab_game.id = tab_apply.game_id and tab_apply.offline_status = 0 and tab_apply.promote_id = ' . $grandPromoteId)
                        ->where($gameMap)->select();
                } else {
                    $gameData = M('game', 'tab_')->where($gameMap)->select();
                }
            }

            if (empty($gameData)) {
                $this->ajaxReturn(array("status" => 0, "msg" => "游戏权限异常"));
            }

            foreach ($gameData as $list) {
                $updateStatus = 0;

                $map['promote_id'] = $promoteId;
                $map['game_id'] = $list['id'];
                $result = M('apply', 'tab_')->field('id,offline_status')->where($map)->find();
                if (!empty($result)) {
                    if ($result['offline_status'] == 1) {
                        $updateStatus = 1;
                    } else {
                        if ($_POST['sdk_type'] > 0) {
                            continue;
                        } else {
                            $this->ajaxReturn(array("status" => 1, "msg" => "已申请过该游戏"));
                        }
                    }
                }

                $model = new ApplyModel(); //D('Apply');
                $ratio = $list['ratio'];
                $money = $list['money'];
                $data['ratio'] = $ratio;
                $data['money'] = $money;
                $data['promote_account'] = $promoteData['account'];
                $data['apply_time'] = NOW_TIME;
                $data['offline_status'] = 0;

                if ($updateStatus == 0) {
                    $sdk_version = $list['sdk_version'];
                    $data['sdk_version'] = $sdk_version;
                    $data['game_id'] = $list['id'];
                    $data['game_name'] = get_game_name($list['id']);
                    $data['promote_id'] = $promoteId;
                    $data['status'] = C('SET_AUTO_PACK');

                    $res = $model->add($data);
                } else {
                    $res = $model->where('id = ' . $result['id'])->save($data);
                }

                if (($updateStatus == 0 && $res) || ($updateStatus == 1 && $res !== false)) {
                    $thsiAppltId = M('Apply', 'tab_')->where(array('game_id' => $list['id'], 'promote_id' => $promoteId))->getField('id');
                    $gameSource = M('Game_source', 'tab_')->field('id,source_version')->where(['game_id' => $list['id']])->find();
                    if (!file_exists(get_game_source_file_url($list['id'])) || null == $gameSource) {
                        M('apply', 'tab_')->where(['id' => $thsiAppltId])->setField('enable_status', -1);
                        M('apply_launch', 'tab_')->where(['apply_id' => $thsiAppltId])->setField('launch_packge', -1);
                    } else {
                        M('apply', 'tab_')->where(['id' => $thsiAppltId])->setField(['enable_status' => 2, 'pack_url' => '', 'plist_url' => '']);
                        M('apply_launch', 'tab_')->where(['apply_id' => $thsiAppltId])->setField('launch_packge', 0);
                    }
                } else {
                    $this->ajaxReturn(array("status" => 0, "msg" => "申请失败", 'ret' => $res));
                }
            }

            if ($_POST['sdk_type'] > 0 && empty($res)) {
                $this->ajaxReturn(array("status" => 1, "msg" => "已申请过该游戏"));
            }
            recordPromoteLogs('游戏管理','专服管理添加游戏');
            $this->ajaxReturn(array("status" => 1, "msg" => "申请成功"));
        } else {
            $this->ajaxReturn(array("status" => "0", "msg" => "数据有误"));
        }
    }

    public function apply_game()
    {
        if (IS_POST) {
            $relation_game_id = $_POST['game_id'];
            $sdk_version = $_POST['sdk_version'];
            $platform_id = $_POST['platform_id'];
            $platform_name = $_POST['platform_name'];
            $remark = $_POST['remark'];
            $promote_id = is_login_promote();
            if ($promote_id < 1) {
                $this->ajaxReturn(['status' => 0, 'msg' => '请登录后再操作'], 'json');
            }

            if (!is_numeric($relation_game_id) || $relation_game_id < 1) {
                $this->ajaxReturn(['status' => 0, 'msg' => '缺少游戏'], 'json');
            }
            if (!is_numeric($sdk_version) || $sdk_version < 1 || $sdk_version > 2) {
                $this->ajaxReturn(['status' => 0, 'msg' => '缺少版本'], 'json');
            }
            if ((!is_numeric($platform_id) || $platform_id < 1) && empty($platform_name)) {
                $this->ajaxReturn(['status' => 0, 'msg' => '投放平台不能为空'], 'json');
            }


            $gamemodel = M('Game', 'tab_');

            $game = $gamemodel->where(['relation_game_id' => $relation_game_id, 'sdk_version' => $sdk_version])->find();

            if (!is_array($game)) {
                $this->ajaxReturn(['status' => 0, 'msg' => '此游戏不存在'], 'json');
            }

            $game_id = $game['id'];

            // 先查投放平台,如有渠道输入则先判断平台是否存在,不存在则添加,存在则获取信息;没有趣的输入,则判断选择平台是否存在,不存在返回

            $platformmodel = M('launch_platform', 'tab_');


            if ($platform_name) {
                $platform = $platformmodel->where(['name' => $platform_name])->find();

                if (empty($platform)) {
                    $platform_id = $platformmodel->add(['create_time' => time(), 'update_time' => time(), 'name' => $platform_name, 'promote_id' => $promote_id, 'promote_account' => get_promote_account($promote_id), 'mark' => 1]);
                } else {
                    $platform_id = $platform['id'];
                }

            } else {

                $platform = $platformmodel->where(['id' => $platform_id])->find();
                if (empty($platform)) {
                    $this->ajaxReturn(['status' => 0, 'msg' => '投放平台选择有误,请重新选择'], 'json');
                }

            }


            // 再查申请表,数据是否存在,存在则不予理会,不存在则添加

            $applymodel = M('Apply', 'tab_');

            $apply = $applymodel->field('id')->where(['promote_id' => $promote_id, 'game_id' => $game_id])->find();
            if (empty($apply)) {
                $data = array(
                    'game_id' => $game_id,
                    'game_name' => $game['game_name'],
                    'promote_id' => $promote_id,
                    'promote_account' => session("promote_auth.account"),
                    'apply_time' => time(),
                    'status' => C('SET_AUTO_PACK'),
                    'dispose_time' => C('SET_AUTO_PACK') ? time() : '',
                    'sdk_version' => $sdk_version,
                    'ratio' => $game['ratio'],
                    'money' => $game['money'],
                );

                $exist = C('SET_AUTO_PACK');

                $apply_id = $applymodel->add($data);
            } else {
                $apply_id = $apply['id'];
                $exist = 1;
            }

            if ($platform_id > 0 && $apply_id > 0) {

                $launchmodel = M('apply_launch', 'tab_');

                $launch = $launchmodel->field('position')->where(['platform_id' => $platform_id, 'apply_id' => $apply_id])->order('launch_time desc')->find();


                $data = array(
                    'platform_id' => $platform_id,
                    'apply_id' => $apply_id,
                    'launch_game_id' => $game_id,
                    'launch_time' => time(),
                    'position' => $launch['position'] > 0 ? (intval($launch['position']) + 1) : 1,
                    'remark' => $remark,
                );

                $res = $launchmodel->add($data);

                if ($res > 0) {
                    $this->ajaxReturn(['status' => 1, 'msg' => '申请成功', 'exist' => $exist], 'json');
                } else {
                    $this->ajaxReturn(['status' => 0, 'msg' => '申请失败'], 'json');
                }


            } else {
                $this->ajaxReturn(['status' => 0, 'msg' => '申请失败,请重新申请'], 'json');
            }
        } else {
            $this->ajaxReturn(['status' => 0, 'msg' => '请求有误'], 'json');
        }
    }

    /*
     * APP申请
     */
    public function app_index()
    {

        $map['tab_app.type'] = 1;
        empty(I('version')) || $map['tab_app.version'] = I('version');
        $promote_id = PID;
        $data = M('app', 'tab_')
            ->field('tab_app.*,p.status as apply_status,p.dow_url,p.enable_status,p.promote_id')
            ->join("left join tab_app_apply p on p.app_id = tab_app.id and p.promote_id = {$promote_id}")
            ->where($map)
            ->select();
        $this->assign('data', $data);
        $this->meta_title = "APP申请";
        $this->display();
    }

    //app申请
    public function apply_app($app_id)
    {
        $app = M('app', 'tab_')->find($app_id);
        $map['app_id'] = $app_id;
        $map['promote_id'] = PID;
        $data = M('app_apply', 'tab_')->where($map)->find();
        if (!empty($data)) {
            $res['status'] = 2;
            $res['msg'] = '该渠道已经申请过此APP!';
        } else {
            $data['promote_id'] = PID;
            $data['app_id'] = $app_id;
            $data['app_name'] = $app['name'];
            $data['app_version'] = $app['version'];
            $data['apply_time'] = time();
            $data['status'] = 0;

            $result = M('app_apply', 'tab_')->add($data);
            if ($result !== false) {
                $res['status'] = 1;
                $res['msg'] = '申请成功';
            } else {
                $res['status'] = 2;
                $res['msg'] = '申请失败';
            }
        }
        $this->ajaxReturn($res);
    }

    //打包
    public function allpackage($ids = null, $game_id = 0)
    {
        if (empty($ids)) {
            $gameData = M('Game', 'tab_')->find($game_id);
            $model = new ApplyModel(); //D('Apply');
            $data['game_id'] = $_POST['game_id'];
            $data['game_name'] = get_game_name($game_id);
            $data['promote_id'] = session("promote_auth.pid");
            $data['promote_account'] = session("promote_auth.account");
            $data['apply_time'] = NOW_TIME;
            $data['status'] = 1;
            $data['enable_status'] = 2;
            $data['dispose_id'] = 0;
            $data['dispose_time'] = NOW_TIME;
            $data['sdk_version'] = $gameData['sdk_version'];
            $data['ratio'] = $gameData['ratio'];
            $data['money'] = $gameData['money'];
            $result = $model->add($data);
            if ($result > 0) {
                $this->success("已加入打包队列,刷新此页面可查看当前打包状态");
            } else {
                $this->error('打包失败');
            }
        } else {
            $map['id'] = $ids;
            $data = array('status' => 1, 'enable_status' => 2);
            M('apply', 'tab_')->where($map)->setField($data);
            $this->success("已加入打包队列,刷新此页面可查看当前打包状态");
            exit;
        }
    }

    /**
     *APP打包
     */
    public function app_package($appid = null)
    {
        $appData = M('app', 'tab_')->find($appid);
        $map['app_id'] = $appid;
        $map['promote_id'] = PID;
        $ids = 0;
        $data = M('app_apply', 'tab_')->where($map)->find();
        if (empty($data)) {
            $data['promote_id'] = PID;
            $data['app_id'] = $appid;
            $data['app_name'] = $appData['name'];
            $data['app_version'] = $appData['version'];
            $data['apply_time'] = time();
            $data['status'] = 1;
            $data['enable_status'] = 1;
            $data['dispose_id'] = 0;
            $data['dispose_time'] = NOW_TIME;
            $result = M('app_apply', 'tab_')->add($data);
            $ids = $result;
        } else {
            $ids = $data['id'];
        }
        try {
            $apply_data = M('app_apply', 'tab_')->find($ids);
            #获取原包数据
            $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) {
                    $to = "http://" . 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参数错误");
                    }
                }

                if ($apply_data['app_version'] == 2) {
                    $plist_url = A('Plist')->create_plist_app('1', $apply_data['promote_id'], 'app', $to);
                    $apply_data['plist_url'] = $plist_url;
                }
                $apply_data['dow_url'] = $to;
                $apply_data['enable_status'] = 1;
                $apply_data['status'] = 1;
                $res = M('app_apply', 'tab_')->save($apply_data);
            } else {
                $this->error('解压文件失败');
            }
            $this->success('打包成功');
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
    }

    public function promitionofregestion()
    {
        $map['relation_game_id'] = $_GET['gid'];
        $data = M('game', 'tab_')->field('id,sdk_version,icon,screenshot,relation_game_id,relation_game_name')->where($map)->select();
        $this->assign('data', $data);
        $this->display();
    }

    public function qrcode($url = '', $logo = '', $level = 3, $size = 4)
    {
        $url = base64_decode(base64_decode($url));
        $logo = base64_decode(base64_decode($logo));
        Vendor('phpqrcode.phpqrcode');
        $errorCorrectionLevel = intval($level);//容错级别
        $matrixPointSize = intval($size);//生成图片大小
        //生成二维码图片
//        echo $_SERVER['REQUEST_URI'];
        ob_clean();
        echo \QRcode::png($url, false, $errorCorrectionLevel, $matrixPointSize, 2, false, $logo);
    }

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

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


    /**
     * 投放平台列表
     * @param integer $applyid 申请表编号
     * @author  鹿文学
     */
    public function launch($applyid = 0, $p = 1)
    {

        if (is_numeric($applyid) && $applyid > 0) {
            $launchmodel = M('apply_launch', 'tab_');
            $page = intval($p);
            $page = $page ? $page : 1; //默认显示第一页数据
            $map = ['apply_id' => $applyid];
            $count = $launchmodel->alias('l')
                ->join('tab_apply as a on(a.id=l.apply_id) ')
                ->where($map)->count();
            if ($count > 0) {
                if (isset($_REQUEST['row'])) {
                    $row = $_REQUEST['row'];
                } else {
                    $row = 10;
                }

                $list = $launchmodel->alias('l')->field('l.*,a.game_id,a.promote_id,a.promote_id,a.sdk_version,a.enable_status')
                    ->join('tab_apply as a on(a.id=l.apply_id) ')
                    ->where($map)->page($page, $row)->select();
                $game = M('game', 'tab_')->where(['id' => $list[0]['launch_game_id']])->field('game_status,dow_status')->find();
                if ($game['dow_status'] == 0 || $game['game_status'] == 0) {
                    foreach ($list as $key => $v) {
                        unset($list[$key]['launch_down_url']);
                        unset($list[$key]['launch_plist_url']);
                    }
                }
                $page = set_pagination($count, $row);
                if ($page) {
                    $this->assign('_page', $page);
                }
                $this->assign('list_data', $list);
                $this->assign('is_launch', 1);
            } else {
                $list = M('apply', 'tab_')->where(['id' => $applyid])->find();
                $game = M('game', 'tab_')->where(['id' => $list['game_id']])->field('game_status,dow_status')->find();
                if ($game['dow_status'] == 0 || $game['game_status'] == 0) {
                    unset($list['pack_url']);
                    unset($list['plist_url']);
                }
                $this->assign('list_data', [$list]);
                $this->assign('is_launch', 0);
            }
        }
        $this->assign('relation_game_id', I('get.rgid', ''));
        $this->assign('notchild', stripos($_SERVER['HTTP_REFERER'], 'child_game') ? 0 : 1);
        $this->display();

    }

    function getPromoteListByRole()
    {
        $promoteRole = I('promote_role');
        $data = array();

        switch ($promoteRole) {
            case 2:
            case 3:
            case 4:
                $data = getAllPromoteListByType($promoteRole);
                break;
        }

        $this->ajaxReturn($data);
    }

    public function getGameInfo()
    {
        $promote = $this->getLoginPromote();
        $promoteService = new PromoteService();
        if (!$promoteService->isPresidentAccess($promote)) {
            $this->ajaxReturn([
                'status' => 0, 
                'message' => '请联系市场专员开启',
                'data' => [
                ]
            ]);
        }

        $gameId = I('game_id');
        $promoteType = I('promote_type');
        $gameData = array();

        if ($gameId > 0) {
            $map['id'] = $gameId;

            $gameData = M('Game', 'tab_')
                ->where($map)
                ->find();
        }

        $gameData['sdk_name'] = getSDKTypeName($gameData['sdk_version']);

        $promotes = getAllPromoteListByType($promoteType);

        $newPromoteData = [];
        if (count($promotes) > 0) {

            $promoteIds = array_column($promotes, 'id');
            $oldIds = M('apply', 'tab_')->where(['game_id' => $gameId, 'promote_id' => ['in', $promoteIds], 'offline_status' => 0])->getField('id', true);
            $newPromoteIds = $oldIds && count($oldIds) > 0 ? array_diff($promoteIds, $oldIds) : $promoteIds;
            foreach ($promotes as $promote) {
                if (in_array($promote['id'], $newPromoteIds)) {
                    $newPromoteData[] = $promote;
                }
            }
        }

        $data['game_data'] = $gameData;
        $data['promote_data'] = $newPromoteData;

        $this->ajaxReturn([
            'status' => 1, 
            'message' => '获取成功',
            'data' => $data
        ]);
    }

    function addGameToPromote()
    {
        $loginPromote = $this->getLoginPromote();
        $gameId = I('game_id');
        $promoteIds = I('promote_ids');

        if (empty($gameId)) {
            $data['status'] = -1;
            $data['msg'] = '游戏id错误';

            $this->ajaxReturn($data);
        }

        if (empty($promoteIds)) {
            $data['status'] = -1;
            $data['msg'] = '未选择渠道';

            $this->ajaxReturn($data);
        }

        $gameData = M('Game', 'tab_')->where(array('id' => $gameId))->find();

        foreach ($promoteIds as $value) {
            $thisPromoteData = D('Promote')->where(array('id' => $value))->find();

            if (empty($thisPromoteData) || !hasPromotePermission($loginPromote['id'], $value)) {
                $data['status'] = -1;
                $data['msg'] = '渠道权限异常';

                $this->ajaxReturn($data);
            }

            $map['game_id'] = $gameId;
            $map['promote_id'] = $value;
            $applyData = M('apply', 'tab_')->field('id,offline_status')->where($map)->find();

            $updateStatus = 0;
            if (!empty($applyData)) {
                if ($applyData['offline_status'] == 0) {
                    continue;
                } else {
                    $updateStatus = 1;
                }
            }

            $save['promote_account'] = $thisPromoteData['account'];
            $save['apply_time'] = NOW_TIME;
            $save['ratio'] = $gameData['ratio'];
            $save['money'] = $gameData['money'];
            $save['offline_status'] = 0;

            $gameSource = M('Game_source', 'tab_')->field('id,source_version')->where(['game_id' => $gameId])->find();
            if (!file_exists(get_game_source_file_url($gameId)) || null == $gameSource) {
                $save['enable_status'] = -1;
            } else {
                $save['enable_status'] = 2;
            }

            if ($updateStatus == 0) {
                $save['sdk_version'] = $gameData['sdk_version'];
                $save['game_id'] = $gameId;
                $save['game_name'] = get_game_name($gameId);
                $save['promote_id'] = $value;
                $save['status'] = C('SET_AUTO_PACK');

                $res = M('Apply', 'tab_')->add($save);
            } else {
                $res = M('Apply', 'tab_')->where('id = ' . $applyData['id'])->save($save);
            }

            if (!$res) {
                $this->ajaxReturn(array("status" => -1, "msg" => "添加失败", 'ret' => $res));
            }
        }

        $this->ajaxReturn(array("status" => 0, "msg" => "添加成功"));
    }

    public function getEnableStatus()
    {
        $applyId = I('post.apply_id');

        if (empty($applyId)) {
            $this->ajaxReturn(['status' => 0, 'msg' => '数据异常']);
        }

        $map['id'] = $applyId;
        $enableStatus = M('Apply', 'tab_')->where($map)->getField('enable_status');

        $this->ajaxReturn(['status' => 1, 'data' => $enableStatus]);
    }

    public function backDetailData()
    {                 //返回详情数据
        $result = ['code' => 10001, 'msg' => "该游戏信息不存在,请确认!", 'error' => 1, 'info' => ''];
        $id = $_POST['id'];
        if (empty($id)) {
            $this->ajaxReturn($result);
        }
        $gameInfo = M('Game', 'tab_')->where(['id' => $id])->getField('detail_content');
        if (!$gameInfo) {
            $this->ajaxReturn($result);
        } else {
            $result['code'] = 10000;
            $result['msg'] = "获取信息成功";
            $result['error'] = -1;
            $result['info'] = $gameInfo;
            $this->ajaxReturn($result);

        }
    }

    public function getDownloadUrl()
    {
        $gameId = I('game_id', 0);
        $promoteId = I('promote_id', 0);
        $promote = $this->getLoginPromote();
        if ($promoteId == 0) {
            $promoteId = $promote['id'];
        }
        $apply = M('apply', 'tab_')->where(['promote_id' => $promoteId, 'game_id' => $gameId])->find();
        $game = M('game', 'tab_')->field(['id', 'icon', 'apply_auth'])->where(['id' => $gameId])->find();
        if ($apply == null) {
            $this->ajaxReturn([
                'status' => 0, 
                'message' => '游戏不存在',
                'data' => [
                ]
            ]);
        }
        
        $promoteService = new PromoteService();
        if (!$promoteService->isPresidentAccess($promote)) {
            $this->ajaxReturn([
                'status' => 0, 
                'message' => '请联系市场专员开启',
                'data' => [
                ]
            ]);
        }
        
        $icon = Request::getHost() . '/' . get_cover($game['icon'], 'path');

        $applyService = new ApplyService();
        $result = $applyService->checkApplyStatus($apply);
        if (!$result['status']) {
            $this->ajaxReturn([
                'status' => 0, 
                'message' => $result['message'],
                'data' => [
                ]
            ]);
        }
        $url = $applyService->getDownloadUrl($apply);
        $this->ajaxReturn([
            'status' => 1, 
            'message' => '获取成功',
            'data' => [
                'url' => $url,
            ]
        ]);
    }

    public function getLandingPageUrl()
    {
        $gameId = I('game_id', 0);
        $promoteId = I('promote_id', 0);
        $promote = $this->getLoginPromote();
        if ($promoteId == 0) {
            $promoteId = $promote['id'];
        }

        $apply = M('apply', 'tab_')->where(['promote_id' => $promoteId, 'game_id' => $gameId])->find();
        $game = M('game', 'tab_')->field(['icon', 'apply_auth', 'id'])->where(['id' => $gameId])->find();

        if ($apply == null) {
            $this->ajaxReturn([
                'status' => 1, 
                'message' => '游戏不存在',
                'data' => [
                ]
            ]);
        }

        $promoteService = new PromoteService();
        if (!$promoteService->isPresidentAccess($promote)) {
            $this->ajaxReturn([
                'status' => 0, 
                'message' => '请联系市场专员开启',
                'data' => [
                ]
            ]);
        }

        $icon = Request::getHost() . '/' . get_cover($game['icon'], 'path');

        $applyService = new ApplyService();
        $result = $applyService->checkApplyStatus($apply);
        if (!$result['status']) {
            $this->ajaxReturn([
                'status' => 0, 
                'message' => $result['message'],
                'data' => [
                ]
            ]);
        }

        $url = $applyService->getLandingPageUrl($apply);
        $this->ajaxReturn([
            'status' => 1, 
            'message' => '获取成功',
            'data' => [
                'url' => $url,
            ]
        ]);
    }
}