<?php
namespace Mobile\Controller;
use Org\Ipa365SDK\Ipa365;
use Org\WeixinSDK\Weixin;
use User\Api\MemberApi;
use Base\Tool\TaskClient;
use Think\Log;
use Base\Service\GameService;
use Base\Service\PackageDownloadLogService;
use Base\Facade\Request;
use Base\Service\UserService;

class SsgController extends BaseController {
    const USER_NOT_ILLEGAL = -1;        //用户名不合法
    const USER_HAVE_SENSITIVE_STR = -2; //包含敏感字符
    const USER_HAS_REGISTERED = -3;     //用户已存在
    const USER_PROMOTE_NATURAL = 0;//自然注册
    const EMPTY_DATA = -100;        //数据为空
    const SIGN_ERROR = -99;         //验签失败
    const USER_NOT_EXIST = -1000;    //用户不存在
    const USER_FORBIDDEN = -1001;   //被禁用
    const USER_PWD_ERROR = -10021;  //密码错误
    const UNKNOWN_ERROR = -1100;    //未知错误
    const CODE_TIMEOUT = -98;       //验证码超时
    const CODE_ERROR = -97;         //验证码错误
    const RETURN_SUCCESS = 1;
    const RETURN_FALSE = 2;
    public $signprice = 10; //充值金额

    public function _initialize()
    {
        parent::_initialize();
        $this->signprice = C("SIGN_PRICE")?:10;
    } 
    public function login()
    {
        $promoteId = I("promote_id", 0);
        $gameId = I("game_id", 0);
        $user = session("user_auth");
        if ($user) {
            redirect(U("ssg/index", array('promete_id' => $promoteId)));
        }

        if ($promoteId) {
            $exists = M("promote", "tab_")->where(array('id' => $promoteId))->find();
            if (!$exists) {
                //$this->error("链接失效,请重新向推广员索取链接.");
                $this->assign("error","链接失效,请重新向推广员索取链接.");
                $this->display('blank');
                exit();
            }
        }
        //获取客服qq
        $appqq = M("config", "sys_")->field('value')->where("name='APP_QQ'")->find()['value'];
        $this->assign("app_qq", $appqq);

        $this->assign("promote_id", $promoteId);
        $this->assign("game_id", $gameId);
        $this->display();
    }

    public function home(){

        if (I('user_token')&&I('user_id')&&I('game_id')) {

            $userToker = I('user_token');
            $user_id = I('user_id');
            $game_id = I('game_id');
            $where['tab_user_token.user_token'] = $userToker;
            $where['tab_user_token.user_id'] = $user_id;
            $where['tab_user_token.game_id'] = $game_id;

            $isToken = M('user_token','tab_')->field('user.id as user_id,user.account as account,user.nickname as nickname')
                ->join("left join tab_user as user on user.id = tab_user_token.user_id")
                ->where($where)
                ->find();

            if ($isToken) {
                session("user_auth",$isToken);
                $this->redirect("Ssg/index",array('game_id'=>$game_id));
            } else {
                $this->redirect("Ssg/login");
            }

        }

        //获取客服qq
        $appqq = M("config", "sys_")->field('value')->where("name='APP_QQ'")->find()['value'];
        $promoteId = I("promote_id", 0);
        $this->assign("app_qq", $appqq);
        $this->assign("promote_id", $promoteId);
        $this->assign("rand", rand());
        $this->display();
    }

    //用户登录
    public function do_login()
    {
        $account = I("Account");
        $password =  I("Password");
        $promoteId = I("promote_id", 0);
        $password = base64_decode($password);
        /*if (!$promoteId) {
        	$this->ajaxReturn(array("ErrorCode" => -97, "ResultMsg" => "参数非法"));
        }*/
        $promote = array();
        if ($promoteId) {
            $promote = M("promote", "tab_")->where(array('id' => $promoteId))->find();
            if (!$promote) {
                $this->ajaxReturn(array("ErrorCode" => -97, "ResultMsg" => "参数非法."));
            }
        }

        $verify = new \Think\Verify();
        if (!$verify->check(I("VerifyCode"))) {
            $this->ajaxReturn(array("ErrorCode" => -97, "ResultMsg" => "验证码错误"));
        }

        $userApi = new MemberApi();
        $user_id = $userApi->login($account, $password,1);//调用登录
        $res_code = 0;
        $res_msg = "登录成功";
        if ($user_id < 0) {
            switch ($user_id) {
                case -1000 :
                    $res_code = self::USER_NOT_EXIST;
                    $res_msg = "用户不存在";
                    break;
                case -10021 :
                    $res_code = self::USER_PWD_ERROR;
                    $res_msg = "登录密码错误";
                    break;
                default :
                    $res_code = self::UNKNOWN_ERROR;
                    $res_msg = "未知错误";
            }
        }
        if($user_id>0){
            $_SESSION['user_id'] = $user_id;

            $user = M('user', 'tab_')->where(array(
                'id' => $user_id
            ))->find();
            if (!$user['promote_id'] && $promote) {
                M('user', 'tab_')->where(array(
                    'id' => $user_id
                ))->save(array(
                    'promote_id' => $promoteId,
                    'promote_account' => $promote['account']
                ));
            }
        }
        $this->ajaxReturn(array("ErrorCode"=>$res_code,"ResultMsg"=>$res_msg),'JSON');
    }

    //验证码
    public function verify($vid = '')
    {
        $config = array(
            'seKey' => 'ThinkPHP.CN',   //验证码加密密钥
            'fontSize' => 16,              // 验证码字体大小(px)
            'imageH' => 42,               // 验证码图片高度
            'imageW' => 107,               // 验证码图片宽度
            'length' => 4,               // 验证码位数
            'fontttf' => '4.ttf',              // 验证码字体,不设置随机获取
            'useCurve'  =>  false,            // 是否画混淆曲线
            'useNoise'  =>  false,            // 是否添加杂点	
            'useCurve' => false,
        );

        ob_clean();
        $verify = new \Think\Verify($config);
        $verify->codeSet = '0123456789';
        $verify->entry($vid);

    }

    //注册
    public function phoneRegister()
    {
        //添加用户
        C(api('Config/lists'));

        $user = $_POST;
        $promoteId =( $user['promote_id'] ? $user['promote_id'] : 0);
        $game_id = $user['game_id'] ?? 0;
        #判断数据是否为空
        if (empty($user)) {
            $this -> set_message(1001, "fail", "注册数据不能为空");
        }
        #验证短信验证码
        if (!$this->sms_verify($user['account'], $user['code'])) {
            $this->set_message(1000, "fail", '验证失败');
        }

        $res =   $this -> doRegister($user['account'],$user['password'],$user['account'],$promoteId,4,2, $game_id);
        if(empty($res)){
            $this -> set_message(1017, "fail", "添加失败");
        }
        //添加自动登录
        $userApi = new MemberApi();
        $user_id = $userApi->login($user['account'], $user['password'],1);

        $this -> set_message(1, "success", "添加成功");

    }
    //忘记密码
    public function forgetPassword()
    {
        $user = $_POST;
        if (empty($user)) {
            $this -> set_message(1001, "fail", "基础信息不能为空");
        }
        if (!$this->sms_verify($user['account'], $user['code'])) {
            $this->set_message(1000, "fail", '验证失败');
        }
        //更新密码
        $userApi = new MemberApi();
        $userInfo = M("user","tab_")->where("account = '".$user['account']."'")->find();
        if(empty($userInfo)){
            $this -> set_message(1003, "fail", "用户不存在");
        }
        //更新用户
        $upres  = $userApi->updatePassword($userInfo['id'], $user['password']);
        if($upres){
            //自动登陆
            $user_id = $userApi->login($user['account'], $user['password'],1);
            $this -> set_message(0, "success", "修改成功");

        }else{

            $this -> set_message(1005, "fail", "密码更新错误,请刷新后再次尝试");
        }
        # code...
    }
    //普通注册
    public function userRegister()
    {
        $account = I("account");
        $password = I("password");
        $promoteId = I("promote_id", 0);
        $res =   $this -> doRegister($account,$password,'',$promoteId,4,1);
        if(empty($res)){
            $this -> set_message(1017, "fail", "添加失败");
        }


        //添加自动登录
        $userApi = new MemberApi();
        $user_id = $userApi->login($account, $password,1);

        $this -> set_message(1, "success", "添加成功");
        # code...
    }
    //消息返回
    public function set_message($status=0,$return_code="fail",$return_msg="操作失败"){
        $msg = array(
            "status"      => $status,
            "return_code" => $return_code,
            "return_msg"  => $return_msg
        );
        $this->ajaxReturn($msg,'JSON');
        exit();
    }

    //真正注册代码
    public function doRegister($account,$password,$phone,$promote_id,$register_way,$register_type, $game_id = 0)
    {
        $userService = new UserService();
        if ($userService->isAccountExist($account)) {
            $this -> set_message(1017, "fail", "用户名已存在");
        }
        $data = array(
            'account'    => $account,
            'password'   => think_ucenter_md5($password, UC_AUTH_KEY),
            'phone'      => $phone,
            'head_img'  =>'',
            'promote_id' => $promote_id,
            'promote_account' =>get_promote_account($promote_id),
            'register_way' => $register_way,
            'register_type' => $register_type,
            'register_ip'  => get_client_ip(),
            'parent_id'=>get_fu_id($promote_id),
            'parent_name'=>get_parent_name($promote_id),
            'register_time'=>time(),
            'check_time' => time(),
        );

        if (Request::isIOS()) {
            $data['device_type'] = 2;
        } elseif (Request::isAndroid()) {
            $data['device_type'] = 1;
        }

        if ($game_id) {//关联游戏
            $game = M('game', 'tab_')->where(['id' => $game_id])->find();
            if ($game) {
                $data['fgame_id'] = $game_id;
                $data['fgame_name'] = $game['game_name'];
            }
        }
        /* 添加用户 */
        $res = M('user', 'tab_') ->add($data);
        if ($res) {
            $taskClient = new TaskClient();
            $taskClient->registerEvent($res, 'SSG');
        }
        return $res;
        # code...
    }

    //首页
    public function index(){
        $user = session("user_auth");
        if (!$user) {
            redirect(U("ssg/login"));
            //$this->error("请登入", U('ssg/login'));
        }
        $appqq = M("config", "sys_")->field('value')->where("name='APP_QQ'")->find()['value'];
        $this->assign("app_qq", $appqq);
        $this->display();
    }

    public function getGamaList()
    {
        $user = session("user_auth");
        $game_name = I("game_name", false);
        $type = I("type",false);
        $map = [];
        if($game_name){
            $map["game_name"] = array("like","%{$game_name}%");
        }
        $map["sdk_version"] = 2;
        $map["game_status"] = 1;
        $game_list = M("game", "tab_")->field("*, id as game_id")->where($map)->select();
        $games = [];
        foreach ($game_list as $game) {
            if (($game['download_ways'] & GameService::DOWNLOAD_SUPER) != GameService::DOWNLOAD_SUPER) {
                continue;
            }
            $game["game_icon"] = get_cover($game["icon"], 'path');
            $games[] = $game;
        }
        $res = array("list"=>$games);
        if($type == 1){
            $map['user_id']= $user['user_id'];
            $map['pay_status'] = 1;
            $userpay = M("game_supersign","tab_")->field("game_id")->where($map)->select();
            if(empty($userpay)){
                $userpay = [];
            }else{
                $tmparr = [];
                for ($i=0; $i < count($userpay); $i++) {
                    # code...
                    $tmparr[] = $userpay[$i]["game_id"];
                }
                $userpay = $tmparr;
            }
            $res["pay_game_id"] = $userpay;
        }
        $this->ajaxReturn($res,'JSON');
        # code...
    }

    public function order(){
        //.echo md5(sha1('123456') . 'UmtW6-Z(S^8xvwDn;B:J{X7FG9z2+Np.|C#~QRY"');exit();
        $user = session("user_auth");
        if (!$user) {
            redirect(U("ssg/login"));
            //$this->error("请登入", U('ssg/login'));
        }

        $order_list = M("game_supersign a","tab_")->field("a.order_id, b.game_name, b.icon, b.id as game_id, a.pay_status, a.user_id,  a.create_time")->join("left join tab_game b on a.game_id=b.id")->where(array(
            'a.user_id' => $user['user_id'],
        ))->order("a.id")->select();
        //         pp($order_list);

        foreach ($order_list as $key => $value){
            $deff = $this->timediffs(time(),$value['create_time']);
            //计算分钟数
            if(($deff['day']+ $deff['hour'])>=1 || $deff['min']>30){
                $order_list[$key]['invalid']=1;
            }else{
                $order_list[$key]['invalid']=0;
            }
        }
        $this->assign("data_list", $order_list);
        $this->assign("nowtime", time());
        $this->display();
    }

    //流程
    public function process(){
        $this->display();
    }

    //教程
    public function tutorial(){
        $this->display();
    }

    //帮助
    public function help(){
        $this->display();
    }

    //规则
    public function rule(){
        $this->display();
    }

    //退出
    public function logout() {
        session("user_auth",null);
        redirect(U("ssg/login"));
    }

    //发送验证码
    public function sendPhoneCode()
    {
        $phone = I('phone');
        $taskClient = new TaskClient();
        $result = $taskClient->sendSmsCode($phone, get_client_ip());
        $data = [];
        if ($result['code'] == TaskClient::SUCCESS) {
            $data['status'] = 1;
        } else {
            $data['status'] = 0;
        }
        $data['msg'] = $result['message'];
        echo json_encode($data);
        exit;
    }

    public function timediffs($begin_time, $end_time) {
        if ($begin_time < $end_time) {
            $starttime = $begin_time;
            $endtime = $end_time;
        } else {
            $starttime = $end_time;
            $endtime = $begin_time;
        }

        //计算天数
        $timediff = $endtime - $starttime;
        $days = intval($timediff / 86400);
        //计算小时数
        $remain = $timediff % 86400;
        $hours = intval($remain / 3600);
        //计算分钟数
        $remain = $remain % 3600;
        $mins = intval($remain / 60);
        //计算秒数
        $secs = $remain % 60;
        $res = array("day" => $days, "hour" => $hours, "min" => $mins, "sec" => $secs);
        return $res;
    }

    public function sms_verify($phone , $code)
    {
        $taskClient = new TaskClient();
        $result = $taskClient->checkSms($phone, $code);
        $data = [];
        if ($result['code'] == TaskClient::SUCCESS) {
            return true;
        } else {
            return false;
        }
    }

    /**
     *支付中心
     */
    public function pay(){
        $user = session("user_auth");
        $gameId = I("game_id", 0);
        $promoteId = I("promote_id");

        //$price = self::signprice;
        if (!$user) {
            redirect("/mobile.php/ssg/login/game_id/{$gameId}/promote_id/$promoteId");
            // $this->error("请登入", "/mobile.php/ssg/login");
        }
        $userId = $user['user_id'];
        $gameInfo = M('game', 'tab_')->field('game_name,supersign_token')->where(array(
            'id' => $gameId,
        ))->find();


        $isPay = M('game_supersign', 'tab_')->where(array(
            'user_id' => $userId,
            'game_id' => $gameId,
            'pay_status' =>1
        ))->find();

        if($isPay){

            $packageDownloadLogService = new PackageDownloadLogService();
            $packageDownloadLogService->add([
                'user_id' => $userId,
                'game_id' => $gameId,
                'promote_id' => $promoteId,
                'type' => 3,
            ]);

            redirect("/mobile.php/Ssg/install_show/user_id/$userId/game_id/$gameId/order_id/".$isPay['order_id']);
        }else{
            if (!$gameInfo['supersign_token']) {
                //$this->error("超级签token未填写!");
                $this->assign("error","超级签token未配置~");
                $this->display('blank');
                exit();
            }

            $this->assign("price", $this->signprice);
            //$this->assign("order_id", $orderId);
            $this->assign("game_id",$gameId);
            $this->assign("game_name",$gameInfo['game_name']);
            $this->display('pay');
        }
    }

    /*
 * 发起支付
 */
    public function dopay() {
        $user = session("user_auth");
        if (!$user ) {
            //redirect("/mobile.php/ssg/login");
            redirect(U("ssg/login"));
        }
        $gameId = I("game_id", 0);
        $paytype = I("pay_type", 'ali');
        $price = $this->signprice;
        $userId = $user['user_id'];
        if (!$userId || !$gameId) {
            //$this->error("参数有误!");
            $this->assign("error","参数有误~");
            $this->display('blank');
            exit();
        }

        $isPay = M('game_supersign', 'tab_')->where(array(
            'user_id' => $userId,
            'game_id' => $gameId,
            'pay_status' => 1
        ))->find(); //是否有已支付订单

        $gameInfo = M('game', 'tab_')->field('game_name,supersign_token')->where(array(
            'id' => $gameId,
        ))->find();

        if ($isPay){
            $this->assign("error","亲~您已购买过了~<br/>请到【订单查询】查看订单信息哟~");
            $this->display('blank');
            exit();
        } else {
            $orderId = "SS_" . date('Ymd') . date('His') . sp_random_string(4); // 超级签
            if (!$gameInfo['supersign_token']) {
                //$this->error("超级签token未填写!");
                $this->assign("error","超级签token未配置~");
                $this->display('blank');
                exit();
            }

            $r = M('game_supersign', 'tab_')->add(array(
                'udid' => '',
                'user_id' => $userId,
                'game_id' => $gameId,
                'order_id' => $orderId,
                'pay_price' => $price,
                'pay_status' => 0,
                'ticket' => '',  // 调用安装的时候分配
                'token' => $gameInfo['supersign_token'],
                'create_time' => time()
            ));
            if (!$r) return -1;
        }
        if($paytype=='ali'){
            $param['price'] = $price;
            $param['sdk_version'] = '2';
            $param['user_id'] = $userId;
            $param['game_id'] = $gameId;
            $param['order_id'] = $orderId;
            $param['apitype'] = "alipay";
            $param['config']  = "alipay";
            $param['signtype']= "MD5";
            $param['server']  = "alipay.wap.create.direct.pay.by.user";
            $param['payway']  = 1;
            $param['title'] = $price;
            $param['body'] = $price;
            //$param['callback'] = "https://m.wmtxkj.com/mobile.php/Ssg/install_show/user_id/{$userId}/game_id/{$gameId}/order_id/{$orderId}";
            //$param['notifyurl'] = "https://m.wmtxkj.com/callback.php/Notify/notify/apitype/alipay";
            if(stripos($_SERVER['HTTP_HOST'], '.wmtxkj.cn') || $_SERVER['HTTP_HOST']=='127.0.0.1' || stripos($_SERVER['HTTP_HOST'], '.free.idcfengye.com')){
                $param['callback'] = "http://".$_SERVER['HTTP_HOST']."/mobile.php/Ssg/install_show/user_id/{$userId}/game_id/{$gameId}/order_id/{$orderId}";
                //$param['notifyurl'] = "http://".$_SERVER['HTTP_HOST']."/callback.php/Notify/notify/apitype/alipay";
            }else{
                $param['callback'] = "https://".$_SERVER['HTTP_HOST']."/mobile.php/Ssg/install_show/user_id/{$userId}/game_id/{$gameId}/order_id/{$orderId}";
                //$param['notifyurl'] = "https://".$_SERVER['HTTP_HOST']."/callback.php/Notify/notify/apitype/alipay";
            }
            $ali_pay = $this->alipay($param);
            redirect($ali_pay['url']);
        }else{
            $weixn = new Weixin();
            $wx_pay = json_decode($weixn->weixin_pay('超级签消费', $orderId, $price, 'MWEB', 4), true);
            if($wx_pay['status']==1){
                //$redirect_url = $_SERVER['HTTP_HOST']."/mobile.php/Ssg/install_show/user_id/{$userId}/game_id/{$gameId}/order_id/{$orderId}";
                redirect($wx_pay['mweb_url']);
            }else{
                $this->assign("error",$wx_pay['return_msg']);
                $this->display('blank');
            }
        }
    }

    // alipay
    public function alipay($param) {
        $pay  = new \Think\Pay($param['apitype'],C($param['config']));
        $vo   = new \Think\Pay\PayVo();
        $vo->setBody("超级签消费")
            ->setFee($param['price'])//支付金额
            ->setTitle($param['title'])
            ->setOrderNo($param['order_id'])
            ->setService($param['server'])
            ->setSignType($param['signtype'])
            ->setPayMethod("wap")
            ->setTable("supersign")
            ->setPayWay($param['payway'])
            ->setCallback($param['callback'])
            //->setNotifyUrl($param['notifyurl'])
            ->setGameName(get_game_name($param['game_id']))
            ->setServerId(0)
            ->setUserId($param['user_id'])
            ->setSdkVersion($param['sdk_version']);
        $pay_['url']= $pay->buildRequestForm($vo);
        //$pay_['out_trade_no']= $out_trade_no;
        return $pay_;

    }


    /**
     * 用户点击安装
     */
    public function install() {
        $user = session("user_auth");
        if (!$user ) {
            //$this->error("请登入", "/mobile.php/ssg/login");
            redirect(U("ssg/login"));
        }
        $userId = $user['user_id'];
        $gameId = I('game_id', 0);
        $orderId = I('order_id', 0);
        if (!$userId || !$gameId || !$orderId) {
            //$this->error("参数有误!");
            $this->assign("error","参数有误~");
            $this->display('blank');
            exit();
        }
        M()->startTrans();
        // 获取支付记录
        $gamesign = M('game_supersign', 'tab_')->where(array(
            'order_id' => $orderId,
            'user_id' => $userId,
            'game_id' => $gameId,
            'pay_status' => 1,
        ))->find();
        if (!$gamesign) {
            //$this->error("支付记录不存在");
            $this->assign("error","支付记录不存在~");
            $this->display('blank');
            exit();
        }
        if ($gamesign['url']) {
            redirect($gamesign['url']);
        }

        $token = $gamesign['token'];
        $ipa365 = new Ipa365();

        $i = 1;
        while (1) {
            // 获取授权码
            $list = $ipa365->ticketList(array(
                'token' => $token,
                'status'=>0,//未使用是0
                'limit' => $i,
            ));  // @todo: 并发授权码已分配的情况
            if($list['errno'] != 0){
                $this->assign("error","超级签获取失败~{$list['errmsg']}");
                $this->display('blank');
                exit();
            }
            $code = $list['data']['list'][$i-1]['code'];
            if($code){
                $codeExists = M('game_supersign', 'tab_')->field('id')->where(array(
                    'ticket' => $code,
                ))->find();
                if (!$codeExists) {
                    break;
                }
            }else{
                $this->assign("error","超级签已售罄~");
                $this->display('blank');
                exit();
            }
            $i ++;
        }
        $game = M('game', 'tab_')->where(array(
            'id' => $gameId,
        ))->find();
        $url = $game['supersign_url']."?code={$code}";
        $r = M('game_supersign', 'tab_')->where(array(
            'user_id' => $userId,
            'game_id' => $gameId,
            'pay_status' => 1
        ))->save(array(
            'ticket' => $code,  // 调用安装的时候分配
            'url' => $url,
        ));
        if (!$r) {
            pp(M('game_supersign', 'tab_')->_sql());
            M()->rollback();
            return -1;
        }
        M()->commit();
        redirect($url);
    }

    /**
     * 下载页面  判断订单是否支付成功
     */
    public function install_show() {
        $orderId = I('order_id', 0);
        $gameId = I('game_id', 0);

        $user = session("user_auth");
        if (!$user ) {
            //$this->error("请登入", "/mobile.php/ssg/login");
            redirect(U("ssg/login"));
        }

        $userId = $user['user_id'];
        if (!$userId ) {
            //$this->error("请登入", "/mobile.php/ssg/login");
            redirect(U("ssg/login"));
        }
        if (!$orderId || !$gameId || !$userId) {
            //$this->error("参数校验失败,请重试");
            $this->assign("error","参数校验失败,请重试~");
            $this->display('blank');
            exit();
        }

        $supersign = M('game_supersign', 'tab_')->where(array('order_id' => $orderId,"game_id"=>$gameId))->find();
        if (!$supersign) {
            //$this->error("订单不存在");
            $this->assign("error","订单不存在");
            $this->display('blank');
            exit();
        }
        if ($supersign['pay_status'] != 1) {
            //$this->error("订单未支付");
            $this->assign("error","订单未支付");
            $this->display('blank');
            exit();
        }
        $game = M('game', 'tab_')->where(array('id' => $gameId))->find();

        $this->assign('game', $game);
        $this->assign('url', U('Ssg/install', array(
            'order_id' => $orderId,
            'user_id' => $userId,
            'game_id' => $gameId
        )));
        //获取礼包码
        $giftbag = M('giftbag', 'tab_')->field("*")->where(array("game_id"=>$gameId,"giftbag_version"=>3))->find();
        if(empty($giftbag)){
            $giftbag = false;
        }else{
            $desribe = $giftbag['desribe'];
            $mygif =  $this->checkAccountGiftExist($userId,$giftbag['id']);
            if(!empty($mygif)){
                //已经领取
                $giftbag =$mygif;
            }else{
                if($giftbag['novice_num']>0){
                    //领取
                    $giftbag = $this->getNovice($userId,$user['account'],$giftbag['id']);
                }
            }
            $giftbag['desribe'] = $desribe;

        }
        //验证是否领取
        $this->assign('giftbag', $giftbag);
        $this->display();
    }

    /*
     * 打包列表
     */
    public function pay_list() {
        $user = session("user_auth");
        if (!$user ) {
            //$this->error("请登入", "/mobile.php/ssg/login");
            redirect(U("ssg/login"));
        }
        $userId = $user['user_id'];
        $list = M('game_supersion', 'tab_')->where(array(
            'user_id' => $userId,
        ))->select();
        $this->assign("list", $list);
        $this->display();
    }

    //领取礼包码
    public function getNovice($user_id,$account,$gift_id){
        $data =M("giftbag",'tab_')->find($gift_id);
        $novice_str = $data['novice'];
        $novice_arr = str2arr($novice_str,",");
        if (empty($novice_arr)){
            return "";
        }
        $novice_arr = array_filter($novice_arr);
        $novice = array_pop($novice_arr);
        $data['novice_num'] = count($novice_arr);
        $data['novice'] = arr2str($novice_arr,",");
        M("giftbag",'tab_')->startTrans();
        $novice_result = M("giftbag",'tab_')->save($data);
        if(!empty($novice)){
            //记录领取
            $record['game_id'] = $data['game_id'];
            $record['game_name'] = $data['game_name'];//get_game_name($data['game_id']);
            $record['gift_id'] = $gift_id;
            $record['gift_name'] = $data['giftbag_name'];
            $record['status'] = 0;
            $record['novice'] = $novice;
            $record['user_id'] = $user_id;
            $record['user_account'] = $account;
            $record['create_time'] = time();
            $record['start_time'] = $data['start_time'];
            $record['end_time'] = $data['end_time'];
            $record_result = M("gift_record",'tab_')->add($record);
        }else{
            $novice_result = false;
        }

        if($novice_result === false || $record_result === false){
            M("giftbag",'tab_')->rollback();
            return "";
        }else{
            M("giftbag",'tab_')->commit();
            return $record;
        }
    }

    public function checkAccountGiftExist($user_id,$gift_id){
        $map['user_id'] = $user_id;
        $map['gift_id'] = $gift_id;
        return M("gift_record",'tab_')->field('*')->where($map)->find();
    }
}