<?php
namespace Home\Controller;

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

class IndexController extends Controller
{
    private $auth_type = OAuthHelperV3::SCOPE_BASE;
//    private $auth_type = OAuthHelperV3::SCOPE_USERINFO;
    private $cookie_uid_key = 'mtime-laopao-v1';
    private $debug = 1;
    private $today;
    use ControllerTrait;

    public function _initialize()
    {
        $this->debug = $this->debug && session('X-DEBUG') ? true : false;
        $pub_mode = C('PUBLISH_MODE');
        if (ACTION_NAME != 'test_magic' && ACTION_NAME != 'debug_close' && ACTION_NAME != 'debug_open'
            && $pub_mode != 'production'
            && cookie('X-PUB_MODE') != 'development'
        ) {
            header("Content-type: text/html; charset=utf-8");
            echo '活动尚未开始，敬请期待';
            exit(0);
        }
        $this->today = date('Ymd');
    }
//$user = $this->get_user_info_from_cookie();
//if (!$user) {
//$this->ajaxReturn(array(
//'errcode' => 1,
//'errmsg' => '用户信息错误',
//));
//return;
//}
    public function index()
    {
        $user = $this->get_user_info_from_cookie();
//         如果没有获取到用户信息，引导用户授权
        if (!$user) {
            $this->request_auth($this->get_url());
            return;
        }
        $list = glob('Public/static/images/*');
        foreach ($list as $key => $value) {
            $list[$key] = '/' . $value;
        }
        // 计算统计使用的app_stat_key
        $app_key = md5($this->app_stat_key);
        // 将值传递给view页面
        $image = json_encode($list);
        $this->assign('image', $image);
        // 展示页面
        $this->display();
    }

    public function get_random_prize($user)
    {
        $v = rand(0, 1000000) / 1000000;
        $today_ratio = 1;
        if ($v > $today_ratio) {
            return false;
        }
//        if (stripos($user['openid'], 'fake_') !== false) {
//            return false;
//        }
//        $user_prize = M('UserPrize')->where(array(
//            'tel' => $_POST['tel']
//        ))->find();
//        if ($user_prize) {
//            return false;
//        }

        $now = time();
        $req_type = array();
        $type_list = array(1, 2, 3, 4, 5);
        $from = strtotime(date('Y-m-d', $now));
        $to = strtotime(date('Y-m-d', $now + 86400));
        foreach ($type_list as $type) {
            $c = M('prize')->where(array(
                'type' => $type,
                'take_time' => array(array('gt', $from), array('lt', $to)),
                'is_get' => 1,
            ))->count();
//            1牙膏
            if ($type == 1) {
                if ($c >= 2) {
                    continue;
                }
            }

            $req_type[] = $type;
        }
        if (empty($req_type)) {
            return false;
        }
        $prize = M('Prize')->where(array(
            'reward_time' => array('elt', $now),
            'is_get' => 0,
            'user_id' => 0,
            'type' => array('in', $req_type),
        ))->order('rand()')->limit(1)->find();
        if (!$prize) {
            return false;
        }
        $result = M('Prize')->where(array(
            'id' => $prize['id'],
            'is_get' => 0,
            'user_id' => 0,
        ))->save(array(
            'is_get' => 1,
            'user_id' => $user['id'],
            'take_time' => $now,
        ));
        if ($result > 0) {
            return $prize;
        }
        return false;
    }


    public function addInfo()
    {
        $user = $this->get_user_info_from_cookie();
        if (!$user) {
            $this->ajaxReturn(array(
                'errcode' => 1,
                'errmsg' => '用户信息错误',
            ));
            return;
        }
        $prize = M('Prize')->where(array(
            'user_id' => $user['id']
        ))->find();
        if ($prize) {
            M('Prize')->where(array(
                'user_id' => $user['id']
            ))->save(array(
                'name' => $_POST['name'],
                'tel' => $_POST['tel'],
                'address' => $_POST['address'],
                'reward_time' => time()

            ));
            $this->ajaxReturn(array(
                'errcode' => 0,

            ));
        } else {
            $this->ajaxReturn(array(
                'errcode' => 1,
                'errmsg' => '用户信息错误',
            ));
            return;
        }
    }

    public function get_prize()
    {
        //判断是否中奖过
        //要是中奖过了，就不能在中奖
        //查看各个奖品的数量是否已经满了
        //满了提示没中奖的页面
        //要是没中奖，跳到再玩一次页面
        //中奖名称和中奖几率
        $user = $this->get_user_info_from_cookie();
        if (!$user) {
            $this->ajaxReturn(array(
                'errcode' => 1,
                'errmsg' => '用户信息错误',
            ));
            return;
        }
        M('User')->where(array(
            'id'=>$user['id']
        ))->save(array(
            'photo'=>$url = $this->saveCommonImageToQiniu($_POST['photo_url'], uniqid('missfresh_dianzan__'))
        ));
        $prizeInfo = M('Prize')->where(array(
            'user_id' => $user['id']
        ))->find();
        if ($prizeInfo) {
            $this->prizeSate($prizeInfo, 1);
        } else {
            $prize = $this->get_random_prize($user);
            if ($prize) {
                $this->prizeSate($prize, 2);
            } else {
                $this->ajaxReturn(array(
                    'errcode' => 0,
                    'data' => array(
                        'prize_type' => 0,
                        'info_type' => 2,
                    )
                ));
            }
        }

    }

    public function prizeSate($prize, $type)
    {
        if (!$prize['tel']) {
            if ($type == 1) {
                $type_id = 2;
            } else {

                $type_id = 0;
            }
            $this->ajaxReturn(array(
                'errcode' => 0,
                'data' => array(
                    'prize_type' => 1,
                    'info_type' => $type_id,
                    'prize_id' => $prize['type']
                )
            ));
            return;
        } else {
            $this->ajaxReturn(array(
                'errcode' => 0,
                'data' => array(
                    'prize_type' => 1,
                    'info_type' => 1,
                    'name'=>$prize['name'],
                    'tel'=>$prize['tel'],
                    'address'=>$prize['address'],
                    'prize_id' => $prize['type']
                )
            ));
            return;
        }

    }

    private function saveCommonImageToQiniu($imgData, $fileNameWithoutExt)
    {
        $head = substr($imgData, 0, 20);
        $type = 'png';
        if (stripos($head, 'data:image/jpg;') !== false || stripos($head, 'data:image/jpeg;') !== false) {
            $type = 'jpg';
            $imgData = substr($imgData, strlen('data:image/jpeg;base64,'));
        } else {
            $imgData = substr($imgData, strlen('data:image/png;base64,'));
        }
        $imgData = str_replace(' ', '+', $imgData);
        $data = base64_decode($imgData);
        if (strlen($data) == 0) {
            return false;
        }
        $fileName = $fileNameWithoutExt . '.' . $type;
        $upfile = array(
            'name' => 'file',
            'fileName' => $fileName,
            'fileBody' => $data,
        );
        $config = C('UPLOAD_SITEIMG_QINIU')['driverConfig'];
        $qiniu = new QiniuStorage($config);
        $opt = array();
        $result = $qiniu->upload($opt, $upfile);
        $url = $qiniu->downlink($fileName);
        return $url;
    }
    public function prize()
    {
        for ($i = 0; $i < 3; $i++) {
            M('Prize')->add(array(
                'content' => '牙膏',
                'type' => 1,
            ));
        }


    }
}

