<?php
// +----------------------------------------------------------------------
// | OneThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.onethink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: 麦当苗儿 <zuojiazi@vip.qq.com> <http://www.zjzit.cn>
// +----------------------------------------------------------------------

namespace Home\Controller;

use OT\DataDictionary;

use User\Api\PromoteApi;

use Home\Controller\DownController;
use Base\Tool\TaskClient;
use Base\Service\PromoteService;

/**
 * 前台首页控制器
 * 主要获取首页聚合数据
 */
class IndexController extends HomeController
{
    //系统首页
    public function index()
    {
        $map['game_status'] = 1;
        $map['recommend_status'] = 1;
        $rec_data = M('Game', "tab_")->where($map)->group('relation_game_id')->order('id DESC')->limit(36)->select();
        $this->assign("rec_data", $rec_data);
        $map['recommend_status'] = 2;
        $hot_data = M('Game', "tab_")->where($map)->group('relation_game_id')->order('id DESC')->limit(6)->select();
        $hot_data = index_show($hot_data);
        $this->assign("hot_data", $hot_data);

        $gg = M('Document')->where(array('category_id' => 56, 'status' => 1, 'display' => 1))->order('id DESC')->select();
        $this->assign("gg", $gg);
        $links = M("Links", "tab_")->where("mark=1 and status=1")->select();
        $this->assign("links", $links);

        $this->carousel();

        $this->display();
    }

    public function carousel()
    {
        $list = D('Adv')->lists('promote_index_banner');

        $this->assign('adv', $list);
    }

    public function login()
    {
        $verify = new \Think\Verify();
        if (!$verify->check(I('yzm'))) {
            $this->ajaxReturn(array("status" => 0, "msg" => "验证码错误", 'code' => 0));
        }

        if ($_POST['remm'] == 'on') {
            setcookie('home_account', $_POST['account'], time() + 3600 * 10000, $_SERVER["HTTP_HOST"]);
            //setcookie('home_pas',$_POST['password'],time()+3600*10000,$_SERVER["HTTP_HOST"]);
        } else {
            setcookie('home_account', $_POST['account'], time() - 1, $_SERVER["HTTP_HOST"]);
            //setcookie('home_pas',$_POST['password'],time()-1,$_SERVER["HTTP_HOST"]);
        }

        $account = $_POST['account'];
        $password = $_POST['password'];
        $api = new PromoteApi();
        $result = $api->login($account, $password);
        if ($result > 0) {

            $promote = M("promote", "tab_")->where(['id' => $result])->find();
            $promoteService = new PromoteService();
            if (!$promoteService->isPresidentAccess($promote)) {
                $this->ajaxReturn(array("status" => 0, "msg" => '请联系市场专员开通账号。'));
            }

            $map['account'] = $account;
            $data['last_login_time'] = time();
            M("promote", "tab_")->where($map)->save($data);
            $loginrecord['promote_id'] = get_pid();
            $loginrecord['account'] = $_POST['account'];
            $loginrecord['client_ip'] = $_SERVER['REMOTE_ADDR'];
            $loginrecord['login_type'] = 1;
            $loginrecord['create_time'] = time();
            M("promote_login_record", "tab_")->add($loginrecord);
            $this->ajaxReturn(array("status" => 1, "msg" => "登录成功", 'url' => U('Promote/index')));
        } else {
            $msg = $this->getLoginMessage($result);
            $this->ajaxReturn(array("status" => 0, "msg" => $msg));
        }
    }

    public function doPhoneLogin() {
        $mobile = $_POST['login_phone'];
        $verify = $_POST['code'];
        if (!$this->checksafecode($mobile, $verify)) {
            $this->error('验证码错误');
        }
        $promote = M('promote', 'tab_')->where([
            'login_phone' => $mobile,
        ])->find();

        if($promote) {
            $loginrecord['promote_id'] = $promote['id'];
            $loginrecord['account'] = $promote['account'];
            $loginrecord['client_ip'] = $_SERVER['REMOTE_ADDR'];
            $loginrecord['login_type'] = 2;
            $loginrecord['create_time'] = time();
            M("promote_login_record", "tab_")->add($loginrecord);
            setcookie('login_phone', $mobile, time() + 3600 * 10000, $_SERVER["HTTP_HOST"]);
            $api = new PromoteApi();
            $result = $api->login_phone($promote['account']);
            if ($result > 0) {

                $promoteService = new PromoteService();
                if (!$promoteService->isPresidentAccess($promote)) {
                    $this->ajaxReturn(array("status" => 0, "msg" => '请联系市场专员开通账号。'));
                }

                $this->ajaxReturn(array("status" => 1, "msg" => "登录成功", 'url' => U('Promote/index')));
            } else {
                $msg = $this->getLoginMessage($result);
                $this->ajaxReturn(array("status" => 0, "msg" => $msg));
            } 
        } else {
            $this->error('此电话未注册,登录失败');
        }
    }

    public function getLoginMessage($result)
    {
        $msg = "";
        switch ($result) {
            case -1:
                $msg = "账号或密码错误!";
                break;
            case -2:
                $msg = "账号或密码错误!";
                break;
            case -3:
                $msg = "账号被禁用,请联系管理员";
                break;
            case -4:
                $msg = "审核中,请联系管理员";
                break;
            default:
                $msg = "未知错误!请联系管理员";
                break;
        }
        return $msg;
    }

    /* public function register()
    {
        if (IS_POST) {
            $this->ajaxReturn(array('status' => 0, 'info' => '已关闭用户注册!'));

            //   unset($_POST['remember']);
            $Promote = new PromoteApi();
            $data = $_POST;
            $data['status'] = 0;
            $pid = $Promote->register($data);

            if ($pid > 0) {
                $this->ajaxReturn(array('status' => 1, 'info' => $pid, 'url' => U('index')));
            } else {
                $this->ajaxReturn(array('status' => 0, 'info' => $pid));
            }
        } else {
            $this->display();
        }
    } */

    public function rule()
    {
        $category = D('category')->where(array('name' => 'rule'))->find();
        $docu = D('document')->where(array('category_id' => $category['id'], 'status' => 1))->order('create_time desc')->find();
        $document_article = D('document_article')->where(array('id' => $docu['id']))->find();
        $this->assign('article', $document_article);
        $this->assign('docu', $docu);
        $this->display();
    }

    /**
     *检测账号是否存在
     */
    public function checkAccount($account)
    {
        $Promote = new PromoteApi();
        $res = $Promote->checkAccount($account);

        if ($res) {
            $this->ajaxReturn(true);
        } else {
            $this->ajaxReturn(false);
        }
    }

    public function checkAccountt($account)
    {
        $Promote = new PromoteApi();
        $res = $Promote->checkAccount($account);

        if ($res) {
            echo "true";
        } else {
            echo "false";
        }
    }

    public function isExistcheckAccount($account)
    {
        $Promote = new PromoteApi();
        $res = $Promote->checkAccount($account);

        if (!$res) {
            echo "true";
        } else {
            echo "false";
        }
    }


    /**
     * 关于我们
     */
    public function about()
    {
        $map1['name'] = 'tui_about';
        $map['status'] = 1;
        $map['create_time'] = array("elt", time());
        $map['deadline'] = array("not between", array(1, time()));
        $cid = M('category')->field('id')->where($map1)->find();
        $map['category_id'] = $cid['id'];
        $dataid = M('Document')->field('id')->where($map)->order("update_time desc")->find();
        $data = M('document_article')->where(array('id' => $dataid['id']))->find();
        $this->assign('data', $data);
        $this->display();
    }

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

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

    public function game_view($game_id = 0, $promote_id = 0)
    {
        $promote_id = I('get.promote_id');
        $game_id = I('get.game_id');

        if (empty($promote_id) && empty($game_id)) {
            $data_list = array(
                'game_name' => '剑斩江湖',
                'back_describe' => '',
            );
            $dow_icon = "http://" . $_SERVER['HTTP_HOST'] . "/Public/Home/images/H5Examples/jzjh_icon.ico";
            $back_map = "http://" . $_SERVER['HTTP_HOST'] . "/Public/Home/images/H5Examples/jzjh_bj.jpg";
            $examples = 0;
        } else {
            $map['id'] = $game_id;
            $data_list = M('game', 'tab_')->field('id,game_name,back_describe,dow_icon,back_map,game_status')->where($map)->find();
            $dow_icon = 'http://' . $_SERVER['HTTP_HOST'] . get_cover($data_list['dow_icon'], 'path');
            $back_map = 'http://' . $_SERVER['HTTP_HOST'] . get_cover($data_list['back_map'], 'path');
            $examples = 1;
            $this->assign('game_id', $game_id);
            $this->assign('promote_id', $promote_id);
        }

        $this->assign('data_list', $data_list);
        $this->assign('dow_icon', $dow_icon);
        $this->assign('back_map', $back_map);
        $this->assign('examples', $examples);
        $this->display();
    }

    public function qrcode($url = 'pc.vlcms.com', $level = 3, $size = 4)
    {
        Vendor('phpqrcode.phpqrcode');
        $errorCorrectionLevel = intval($level);//容错级别
        $matrixPointSize = intval($size);//生成图片大小
        //生成二维码图片
        ob_clean();
        $object = new \QRcode();
        echo $object->png($url, false, $errorCorrectionLevel, $matrixPointSize, 2);
    }

    /**
     *生成二维码
     */
    public function get_apply_url($game_id = 0, $promote_id = 0)
    {
        $https = "http://" . $_SERVER["HTTP_HOST"] . "/" . U('Down/down_file', array('game_id' => $game_id, 'promote_id' => $promote_id));
        $this->qrcode($https);
    }


    /**
     * [下载程序]
     * @author 幽灵[syt]
     */
    public function app_download()
    {
        $map['promote_id'] = I("promote_id");
        $map['app_id'] = I("app_id");
        $map['status'] = 1;
        $map['enable_status'] = 1;

        $data = M('AppApply', 'tab_')
            ->where($map)
            ->find();

        if (preg_match('/^(\.)?\/Uploads\//', $data['dow_url'])) {
            $data['dow_url'] = 'http://' . $_SERVER['HTTP_HOST'] . ltrim($data['dow_url'], '.');
        } elseif (!preg_match('/^(http)|(https)/', $data['dow_url'])) {
            $data['dow_url'] = 'https://' . $data['dow_url'];
        }

        $this->assign('data', $data);
        $this->display();
    }

    /**
     * 退出登录
     */
    public function logout()
    {
        $Promote = new PromoteApi();
        $Promote->logout();
        redirect(U('Index/index'));
    }

    public function phoneLogin() {
        $this->display();
    }

    /**
     * 发动手机验证码
     */
    public function telsafecode($phone = '',  $exceptExists=1, $delay = 10, $flag = true)
    {
        $exists = M('promote', 'tab_')->where(['login_phone'=>$phone])->find();
        if (!$exceptExists) {
            if ($exists) {
                return $this->ajaxReturn(['status'=>0,'msg'=>'手机号已被绑定']);
            }
        } else {
            if (!$exists) {
                return $this->ajaxReturn(['status'=>0,'msg'=>'手机号未被绑定']);
            }
        }
        $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 checksafecode($phone, $code)
    {
        $taskClient = new TaskClient();
        $result = $taskClient->checkSms($phone, $code);
        $data = [];
        if ($result && $result['code'] == TaskClient::SUCCESS) {
            return true;
        } else {
            return false;
        }
    }
}