<?php
/**
 * Created by PhpStorm.
 * User: guanxl
 * Date: 2018/3/18
 * Time: 23:25
 */

namespace App\Http\Controllers;

use App\Libs\AppClient;
use App\Services\AccessToken;
use App\Services\BrainstormingService;
use App\Services\CookieService;
use App\Services\ErrorMessageService;
use App\Services\TopService;
use App\Services\UserService;
use Laravel\Lumen\Routing\Controller as BaseController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

use Illuminate\Support\Facades\Cookie;

class WebController extends BaseController
{
    protected $user;
    protected $activityId;
    protected $oauth;

    public function __construct(Request $request)
    {
        Log::info("1");
        $this->activityId = $request->get("activity_id");
        $this->oauth = CookieService::getOauth();
        Log::info($this -> oauth);
        //判断是否已经登录
        $userData = CookieService::getBsAuthUser();
        Log::info($userData);
        if ($userData) {
            $user = UserService::getInstance()->getUser($userData["user_id"]);
            if ($user) {
                if ($this->activityId == $userData["activity_id"]) {
                    if (AccessToken::getInstance()->getAccessToken($user["user_id"]) != CookieService::getBsAccessToken()) {
                       CookieService::unsetBsAuth();
                    }
                }
            }
        }

        try {
            //获取活动信息
            $activity = BrainstormingService::getInstance()->get($this->activityId);
            if(isset($activity["qy_corp_id"])){
                CookieService::setQyCorpId($activity["qy_corp_id"]);
            }

            if (empty($activity)) {
                ErrorMessageService::redirect("您要参加的活动不存在！");
                die;
            }


            $browser = AppClient::browserType();
            switch ($activity["client_type"]) {

                case "wechat":
                    if ($browser != AppClient::BROWSER_TYPE_WECHAT) {
                        ErrorMessageService::redirect("请在微信客户端打开链接！");
                        die;
                    }
                    break;
                case "wesuit":
                    if ($browser != AppClient::BROWSER_TYPE_WESUITAPP) {
                        ErrorMessageService::redirect("请在企业微信客户端打开链接！");
                        die;
                    }
                    break;
                case "cmb_mobile_oa":
                    /*if($browser!=AppClient::BROWSER_TYPE_CMB_MOBILE_OA){
                        ErrorMessageService::redirect("请在招行移事通打开链接！");
                        die;
                    }*/
                    break;
                case "pingan":

                    break;
                case "pingan_zhiniao":
                    if ($browser != AppClient::BROWSER_TYPE_PINGAN_ZHINIAO) {
                        header("location:http://a.app.qq.com/o/simple.jsp?pkgname=com.pingan.xueyuan");
                        die;
                    }
                    break;
                case "yunzhijia":
                    if ($browser != AppClient::BROWSER_TYPE_YUNZHIJIA || !AppClient::isMobile()) {
                        ErrorMessageService::redirect("请在云之家移动端打开链接！");
                    }
                    break;
                case "kara":
                    /*if ($browser != AppClient::BROWSER_TYPE_KARA || !AppClient::isMobile()) {
                        ErrorMessageService::redirect("请在信部落移动端打开链接！");
                    }*/
                    break;
                case "dingtalk":
                    if ($browser != AppClient::BROWSER_TYPE_DINGTALK || !AppClient::isMobile()) {
                        ErrorMessageService::redirect("请在钉钉移动端打开链接！");
                    }
                    break;
                /*default:
                    if (!AppClient::isWxBrowser()) {
                        ErrorMessageService::redirect("请在企业微信或微信客户端打开链接！");
                        die;
                    }
                    break;*/
            }

            $openId = $this->oauth["oauth_open_id"];
            $avatar = $this->oauth["oauth_avatar"];
            $nickname = $this->oauth["oauth_nickname"];
            $platform = $this->oauth["oauth_platform"];
            $department = $this->oauth["oauth_department"];
            $guid = $this->oauth["oauth_guid"];
            $gCorpId = $this->oauth["oauth_gcorp_id"];

            $userData = CookieService::getBsAuthUser();
            if ($userData) {
                if ($this->activityId != $userData["activity_id"]) {
                    CookieService::unsetBsAuth();
                }
            }

            if (!empty($this->oauth["oauth_open_id"])) {
                Log::info("oauth_open_id:" . $openId);
                //校验活动进行方式  wechat 纯微信(导入人员名单)  agh_import 微信+企业微信(导人员入名单)  agh 微信+企业微信(不导入人员名单) agh_corps 多企业使用


                //根据认证方式去处理是否需要新增人员或者单位信息。
                switch ($activity['auth_type']) {
                    case "wechat_auto_add":
                        UserService::getInstance()->addUserByOpenId($this->activityId, $openId, $avatar, $nickname, $platform);
                        $user = UserService::getInstance()->auth2($this->activityId, $openId, $avatar, $nickname, $platform);
                        break;
                    case "cmb_mobile_oa_add":
                        UserService::getInstance()->addUserByOpenId($this->activityId, $openId, $avatar, $nickname, $platform);
                        $user = UserService::getInstance()->auth2($this->activityId, $openId, $avatar, $nickname, $platform);
                        break;
                    case "cmb_mobile_oa":
                        //UserService::getInstance()->addUserByGuid($this->activityId, $guid, $gCorpId);
                        $user = UserService::getInstance()->authByGuid($this->activityId, $openId, $avatar, $nickname, $platform, $guid);
                        break;
                    case "yunzhijia_add":
                        UserService::getInstance()->addUserByOpenId($this->activityId, $openId, $avatar, $nickname, $platform);
                        $user = UserService::getInstance()->auth2($this->activityId, $openId, $avatar, $nickname, $platform);
                        break;
                    case "yunzhijia":
                        $user = UserService::getInstance()->authByGuid($this->activityId, $openId, $avatar, $nickname, $platform, $guid);
                        break;
                    case "dingtalk_add":
                        UserService::getInstance()->addUserByOpenId($this->activityId, $openId, $avatar, $nickname, $platform);
                        $user = UserService::getInstance()->auth2($this->activityId, $openId, $avatar, $nickname, $platform);
                        break;
                    case "dingtalk":
                        $user = UserService::getInstance()->authByGuid($this->activityId, $openId, $avatar, $nickname, $platform, $guid);
                        break;
                    case "kara_sbu_add":
                        UserService::getInstance()->addUserByOpenId($this->activityId, $openId, $avatar, $nickname, $platform,$department);
                        $user = UserService::getInstance()->auth2($this->activityId, $openId, $avatar, $nickname, $platform);
                        break;
                    case "kara_add":
                        UserService::getInstance()->addUserByOpenId($this->activityId, $openId, $avatar, $nickname, $platform);
                        $user = UserService::getInstance()->auth2($this->activityId, $openId, $avatar, $nickname, $platform);
                        break;
                    case "kara":
                        $user = UserService::getInstance()->authByGuid($this->activityId, $openId, $avatar, $nickname, $platform, $guid);
                        break;
                    case "pingan_zhiniao_add":
                        UserService::getInstance()->addUserByOpenId($this->activityId, $openId, $avatar, $nickname, $platform);
                        $user = UserService::getInstance()->auth2($this->activityId, $openId, $avatar, $nickname, $platform);
                        break;
                    case "pingan_zhiniao":
                        $user = UserService::getInstance()->authByGuid($this->activityId, $openId, $avatar, $nickname, $platform, $guid);
                        break;
                    case "agh":
                        $ret = UserService::getInstance()->addUserByGuid($this->activityId, $guid, $gCorpId);
                        if($ret["error"]>0){
                            CookieService::unsetOauth();
                            Log::info($_COOKIE);
                            ErrorMessageService::redirect("抱歉，你不在(".$ret["corp_short_name"].")活动名单中");
                        }
                        $user = UserService::getInstance()->authByGuid($this->activityId, $openId, $avatar, $nickname, $platform, $guid);
                        break;
                    case "agh_corps":
                        UserService::getInstance()->addUserByGuid($this->activityId, $guid, $gCorpId, true);
                        $user = UserService::getInstance()->authByGuid($this->activityId, $openId, $avatar, $nickname, $platform, $guid);
                        break;
                    default:
                        $user = UserService::getInstance()->auth2($this->activityId, $openId, $avatar, $nickname, $platform);
                        break;
                }
                //如果认证为纯微信认证
                if ($activity['auth_type'] == "agh"||$activity["client_type"]=="yunzhijia") {
                    //若$user为空，则清除原有cookie信息，重新设置cookie
                    if (empty($user)) {
                        if (CookieService::getLoginTrialNum() < 3) {
                            //清除Oauth的cookie
                            CookieService::unsetOauth();
                            CookieService::incrLoginTrialNum();
                            $this->oauth["oauth_open_id"] = null;
                        } else {
                            CookieService::unsetLoginTrialNum();
                            ErrorMessageService::redirect("抱歉，你不在活动名单中！");
                        }
                    }
                }

                if ($user) {
                    $this->user = $user;
                    $accessToken = AccessToken::getInstance()->create($user);
                    //生成认证后的登录cookie
                    CookieService::setBsAuth($user, $accessToken);
                    Log::info($user);
                }
            }
        } catch (\Exception $exception) {
            Log::info("NOT found activity_id" . $exception->getMessage());
            Log::error($exception->getTraceAsString());
            ErrorMessageService::redirect("您要参加的活动不存在！");
            exit;
        }
    }

    public function room($id)
    {
        $getData = $_GET;
        unset($getData["_url_"]);
        $redirectUrl = env("WEB_URL") . "/pk/room/{$id}?".http_build_query($getData);
        $frontendRedirectUrl = env("WEB_URL") . "/static/v1/#/beatdown?room_id=" . $id . "&activity_id={$this->activityId}&time=" . time();
        $this->sso($redirectUrl, $frontendRedirectUrl);
    }

    public function index(Request $request)
    {
        if(!empty($request->get("token"))){
            //return $request->get("token");
        }

        $getData = $_GET;
        unset($getData["_url_"]);
        $redirectUrl = env("WEB_URL") . "?".http_build_query($getData);

        $frontendRedirectUrl = env("WEB_URL") . "/static/#/?useOpenApi=1&activity_id={$this->activityId}&time=" . time();
        Log::info($frontendRedirectUrl);
        $this->sso($redirectUrl, $frontendRedirectUrl);
    }

    public function frontend(Request $request)
    {
        $redirectUrl = env("WEB_URL") . "/frontend?activity_id=" . $this->activityId . "&redirect=" . urlencode($request->get("redirect"));
        $frontendRedirectUrl = $request->get("redirect");
        $this->sso($redirectUrl, $frontendRedirectUrl);
    }



    /**
     * 单点登录，生成cookie信息
     * @param $redirectUrl
     * @param $frontRedirectUrl
     */
    protected function sso($redirectUrl, $frontRedirectUrl)
    {

        if (empty($this->oauth["oauth_open_id"])) {
            $queryData = $_GET;
            unset($queryData["_url_"]);
            //如果是知鸟APP
            if(AppClient::browserType()==AppClient::BROWSER_TYPE_PINGAN_ZHINIAO){
                $queryData["useOpenApi"] = 1;
            }
            $queryData["action"] = "login";
            $queryData["redirect"] = $redirectUrl;
            $brainstroming = BrainstormingService::getInstance()->get($this->activityId);
            if (isset($brainstroming["gcorp_id"])) {
                $queryData["gcorp_id"] = $brainstroming["gcorp_id"];
            }

            $url = env("SSO_URL") . "?" . http_build_query($queryData);
            Log::info($url);
            header("location: " . $url);
        } else {
            header("location:" . $frontRedirectUrl);
        }

    }

}
