<?php
namespace Home\Controller;
vendor('tencentsdk.TCloudAutoLoader');

use Think\Controller;
use SignedCookie;
use Zhida\OAuthHelperV3;
use Think\Upload\Driver\Qiniu\QiniuStorage;

use Think\Log;

class IndexController extends Controller
{
    private $auth_type = OAuthHelperV3::SCOPE_USERINFO;
    private $cookie_uid_key = 'skp-rotor-v1';
    private $debug = 1;
    private $today;
    use ControllerTrait;
    
    public function index()
    {
      $user = $this->get_user_info_from_cookie();
      // 如果没有获取到用户信息，引导用户授权
      if (!$user) {
          $this->request_auth($this->get_url());
          return;
      }

      session_start();
      $_SESSION['joinTime'] = time();

      $this->assign('type',$user['is_prize']);
      $this->assign('tel',$user['tel']);
      $this->display();
    }

    public function submit() {
        $referer = $_SERVER['HTTP_REFERER'];
        $refererInfo = parse_url( $referer );
        if( $refererInfo['host'] != $_SERVER['HTTP_HOST'] )
        {
            header("HTTP/1.0 404 Not Found");
            exit;
        }
        session_start();
        if(!$_SESSION['joinTime'] || time() - $_SESSION['joinTime'] < 2)
        {
            header("HTTP/1.0 404 Not Found");
            exit;
        }
        $user = $this->get_user_info_from_cookie();
        if (!$user) {
            $this->ajaxReturn(array(
                'status' => 404,
                'msg' => '用户信息错误',
                'step' => 0
            ));
            return;
        }

        M('user')->where(array(
          'id' => $user['id']
        ))->save(array(
          'tel' => $_POST['tel']
        ));

        $this->ajaxReturn(array(
            'status' => 1,
            'msg' => '提交成功',
            'step' => 0
        ));
        return;
    }

    public function tryPrize()
    {
        $referer = $_SERVER['HTTP_REFERER'];
        $refererInfo = parse_url( $referer );
        if( $refererInfo['host'] != $_SERVER['HTTP_HOST'] )
        {
            header("HTTP/1.0 404 Not Found");
            exit;
        }
        session_start();
        if(!$_SESSION['joinTime'] || time() - $_SESSION['joinTime'] < 2)
        {
            header("HTTP/1.0 404 Not Found");
            exit;
        }
        $user = $this->get_user_info_from_cookie();
        if (!$user) {
            $this->ajaxReturn(array(
                'status' => 404,
                'msg' => '用户信息错误',
                'step' => 0
            ));
            return;
        }

        if($user['is_prize'] != 0)
        {
          $this->ajaxReturn(array(
              'status' => 0,
              'msg' => '很遗憾,没有中奖',
              'prize_type' => 0,
              'step' => 3,
          ));
          return false;
        } else {
          $count = M('prize')->where(array(
              'user_id' => $user['id']
          ))->count();
          if($count > 0)
          {
            $this->ajaxReturn(array(
              'status' => 0,
              'msg' => '很遗憾,没有中奖',
              'prize_type' => 0,
              'step' => 5,
            ));
            return false;
          }
        }

        
        
        $prize = $this->get_random_prize($user);
        if ($prize) {
          M('user')->where(array(
            'id' => $user['id']
          ))->save(array(
            'is_prize' => $prize['type']
          ));
            $this->ajaxReturn(array(
                'status' => 1,
                'msg' => '恭喜您中奖了!',
                'prize_type' => $prize['type'],
                'step' => 4
            ));
        }
        else {
            $this->ajaxReturn(array(
                'status' => 0,
                'msg' => '很遗憾,没有中奖',
                'prize_type' => 0,
                'step' => 6,
            ));
        }
    }
    private function get_random_prize($user)
    {
        session_start();
        $v = rand(0, 1000000) / 1000000;
        $today_ratio = 0.5;
        if ($v > $today_ratio) {
            return false;
        }
        $now = time();
        $req_type = array();
        $type_list = array(1,2,3);
        foreach ($type_list as $type) {
            $c = M('prize')->where(array(
                'prize_type' => $type,
                'is_get' => 1,
            ))->count();
            if ($type == 1) {
                if ($c >= 25) {
                    continue;
                }
            }
            else if ($type == 2) {
                if ($c >= 500) {
                    continue;
                }
            }
            else if ($type == 3) {
                if ($c >= 1000) {
                    continue;
                }
            }
            $req_type[] = $type;
        }
        if (empty($req_type)) {
            return false;
        }
        $prize = M('prize')->where(array(
            'is_get' => 0,
            'user_id' => 0,
            'prize_type' => array('in', $req_type),
        ))->order('rand()')->limit(1)->find();
        if (!$prize) {
            return false;
        }
        $status = M('prize')->where(array(
            'id' => $prize['id'],
            'is_get' => 0,
            'user_id' => 0,
        ))->save(array(
            'is_get' => 1,
            'user_id' => $user['id'],
            'take_time' => time(),
            'last_ip' => $this->getIP()
        ));
        if($status === false || $status === 0)
        {
            return false;
        }
        else 
        {
            return $prize;
        }
    }

    // public function defaultStatus() {
    //     if($_GET['password'] != 'UUvjQ1AT9fNwYlmNGEe1TSqbin7tClIg')
    //     {
    //         header("HTTP/1.0 404 Not Found");
    //         exit;
    //     }
    //     M('user')->where('1=1')->save(array(
    //         'tel' => NULL,
    //         'is_prize' => 0
    //     ));

    //     M('prize')->where('1=1')->save(array(
    //       'take_time' => 0,
    //       'user_id' => 0,
    //       'is_get' => 0,
    //       'last_ip' => ''
    //     ));
    //     echo 'clear complete';
    // }
    
    public function cookie()
    {
        SignedCookie::set_cookie($this->cookie_uid_key, 'oVsrlt0zUWMLvMx2-KPGVmY2I-Xc', C('cookie_sign'), 86400 * 60);
    }

    // public function addprize() {
    //     for($i = 0;$i < 1000;$i++)
    //     {
    //         M('prize')->add(array(
    //             'type' => 2,
    //             'prize_type' => 3,
    //             'prize_name' => '1元全网手机话费'
    //         ));
    //         if($i < 500) {
    //           M('prize')->add(array(
    //               'type' => 2,
    //               'prize_type' => 2,
    //               'prize_name' => '2元全网手机话费'
    //           ));
    //         } if($i < 25) {
    //           M('prize')->add(array(
    //               'type' => 1,
    //               'prize_type' => 1,
    //               'prize_name' => '优酷VIP视频月卡'
    //           ));
    //         }
    //     }
    // }

}