<?php
/**
 * Created by PhpStorm.
 * User: guanxl
 * Date: 2018/5/16
 * Time: 11:22
 * 访客可以访问的API接口
 */

namespace App\Http\Controllers;

use App\Libs\AppClient;
use App\Models\Activity;
use App\Models\User;
use App\Services\AccessToken;
use App\Services\BrainstormingService;
use App\Services\CookieService;
use App\Services\DepartmentService;
use App\Services\ErrorMessageService;
use App\Services\OnlineLimitService;
use App\Services\PkService;
use App\Services\PushMessageService;
use App\Services\QuestionService;
use App\Services\SmsService;
use App\Services\TopService;
use App\Services\UserService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Cookie;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;

use Laravel\Lumen\Routing\Controller as BaseController;

class ApiGuestController extends BaseController
{

    protected $userId;
    protected $activityId;
    protected $oauth;
    protected $corpId;
    protected $user;
    protected $browser;

    public function __construct(Request $request)
    {
        $this->oauth = CookieService::getOauth();

        try {
            $this->activityId = $request->get("activity_id");
            //判断是否已经登录
            $userData = CookieService::getBsAuthUser();
            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();
                        }
                    }
                }
            }
            $activity = BrainstormingService::getInstance()->get($this->activityId);
            if (empty($activity)) {
                Log::info("api not found activity {$this->activityId}");
                die(json_encode(["error" => 302, "message" => config("errormsg.not_found_activity"), "redirect" => env("NOT_FOUND_URL")]));
            }

            $openId = $request->cookie("oauth_open_id");
            if (empty($openId)) {
                Log::info(config("errormsg.not_oauth"));
                die(json_encode(["error" => 302, "message" => config("errormsg.not_oauth"), "redirect" => env("WEB_URL") . "/frontend?activity_id=" . $this->activityId]));
            }


            $browser = AppClient::browserType();

            $this->browser = $browser;

            switch ($activity["client_type"]) {

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

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

            $userData = CookieService::getBsAuthUser();
            if ($userData) {
                Log::info($userData);
                $user = UserService::getInstance()->getUser($userData["user_id"]);
                if ($user) {
                    if ($this->activityId == $userData["activity_id"]) {
                        $this->userId = $userData["user_id"];
                        $this->user = $user;
                        $this->corpId = $user["corp_id"];
                    } else {
                        CookieService::unsetBsAuth();
                    }
                }
            } else {
                //用openId身份去登录
                $openId = $this->oauth["oauth_open_id"];
                $avatar = $this->oauth["oauth_avatar"];
                $nickname = $this->oauth["oauth_nickname"];
                $platform = $this->oauth["oauth_platform"];
                $guid = $this->oauth["oauth_guid"];
                $department = $this->oauth["oauth_department"];
                $gCorpId = $this->oauth["oauth_gcorp_id"];

                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":
                            $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();
                                ErrorMessageService::forward("抱歉，你不在(".$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") {
                        //若$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::forward("登录认证失败！");
                            }
                        }
                    }

                    if ($user) {
                        $this->user = $user;
                        $accessToken = AccessToken::getInstance()->create($user);
                        //生成认证后的登录cookie
                        CookieService::setBsAuth($user, $accessToken);
                        Log::info($user);
                    }
                }

                $user = UserService::getInstance()->auth2($this->activityId, $openId, $avatar, $nickname, $platform);
                if ($user) {
                    $this->user = $user;
                    $accessToken = AccessToken::getInstance()->create($user);
                    CookieService::setBsAuth($user, $accessToken);
                }
            }
        } catch (\Exception $exception) {
            Log::info("api not found activity {$this->activityId} exception:" . $exception->getMessage());
            Log::info($exception->getTraceAsString());
            die(json_encode(["error" => 302, "message" => config("errormsg.not_found_activity"), "redirect" => env("NOT_FOUND_URL")]));
        }
    }

    /**
     * 获取活动基本信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function baseInfo(Request $request)
    {
        $data = BrainstormingService::getInstance()->get($this->activityId);
        if ($data) {
            $time = time();
            $data["is_activity_start"] = 0;
            $data["is_activity_end"] = 0;
            $data["is_job_time"] = 0;
            if ($data["start_time"] < $time || $data["start_time"] == 0) {
                $data["is_activity_start"] = 1;
            }
            if ($data["end_time"] < $time) {
                $data["is_activity_end"] = 1;
            }
            $data["limit_time"] = "";
            if ($data["is_jobtime_limit"] == 1) {
                $isWeekendLimit = true;
                if(isset($data["is_weekend_limit"])){
                    $isWeekendLimit = $data["is_weekend_limit"]? true:false;
                }
                $w = date("w");
                if (($w > 0 && $w < 6)||$isWeekendLimit) {
                    $jobTimes = json_decode($data["jobtimes"], true);
                    if (is_array($jobTimes)) {
                        foreach ($jobTimes as $jobTime) {
                            $startTime = strtotime($jobTime["start_time"]);
                            $endTime = strtotime($jobTime["end_time"]);
                            if ($time >= $startTime && $time <= $endTime) {
                                $data["is_job_time"] = 1;
                            }
                            $data["limit_time"] .= " " . $jobTime["start_time"] . "-" . $jobTime["end_time"];
                        }
                    }
                }
            }

            $data["level_star_config"] = json_decode($data["level_star_config"],true);

            $name = empty($this->user) ? "" : $this->user["name"];
            $data["share_home_title"] = $this->ubb($data["share_home_title"], $data, $name);
            $data["share_home_desc"] = $this->ubb($data["share_home_desc"], $data, $name);
            $data["share_pk_title"] = $this->ubb($data["share_pk_title"], $data, $name);
            $data["share_pk_desc"] = $this->ubb($data["share_pk_desc"], $data, $name);

            $data["app_name"] = env("APP_NAME");
            $data["app_support"] = env("APP_SUPPORT");


            switch ($data["client_type"]){
                case "yunzhijia":
                    $authExtend = json_decode($data["auth_extend"],true);
                    $data["yzj_app_id"] = $authExtend["yzj_app_id"];
                    break;
                case "cmb_mobile_oa":
                    $authExtend = json_decode($data["auth_extend"],true);
                    $data["cmb_app_code"] = $authExtend["cmb_app_code"];
                    break;
            }

            $data["activity_time"] = date("Y年m月d日 H:i", $data["start_time"]) . "至" . date("Y年m月d日 H:i", $data["end_time"]);


            $ws = substr(env("WEB_URL"),0,5)=="https"? "wss":"ws";
            $data["ws_server"] = $ws."://" . $_SERVER["HTTP_HOST"] . "/brainstorming/ws?userdata=".urlencode(Cookie::get("bs_access_user_data"))."&bs_access_token=".urlencode(Cookie::get("bs_access_token"));

            unset($data["is_jobtime_limit"]);
            unset($data["is_complete_set"]);
            unset($data["key"]);
            unset($data["app_id"]);
            unset($data["status"]);
            unset($data["auth_extend"]);
            $data["sponsor_corp"] = explode("/",$data["sponsor_corp"]);

            return response()->json([
                "error" => 0,
                "data" => $data
            ]);
        }

    }

    /**
     * 获得用户信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function userInfo(Request $request)
    {
        $userId = intval($request->get("user_id"));
        $userId = $userId > 0 ? $userId : $this->userId;
        if ($userId > 0) {
            $user = UserService::getInstance()->getUser($userId);
            if ($user) {
                //判断用户是否可用
                if ($user["status"] == 1) {
                    $data = [
                        "user_id" => $userId,
                        "name" => $user["name"],
                        "headpic_url" => $user["avatar"],
                        "nickname" => $user["nickname"],
                        "short_name" => mb_substr($user["name"], -2, 2, "utf-8"),
                        "department_id" => $user["department_id"],
                        "department_name" => DepartmentService::getInstance()->getDepartmentName($user["department_id"]),
                        "knowledge_money" => $user["knowledge_money"],
                        "is_blockade_success" => $user["is_blockade_success"],
                        "platform" => $user["platform"],
                        "is_white_list" => $user["is_white_list"],
                        "is_over_online" => false,
                        "online_limit_count" => 0
                    ];

                    if (OnlineLimitService::getInstance()->isOverOnline($this->activityId)) {
                        $data["is_over_online"] = true;

                    }
                    $data["online_limit_count"] = OnlineLimitService::getInstance()->onlineLimitCount($this->activityId);

                    TopService::getInstance()->updateUserTop($userId);

                    return response()->json([
                        "error" => 0,
                        "data" => $data
                    ]);
                }

            }
        }

        $data = [
            "user_id" => 0,
            "headpic_url" => $this->oauth["oauth_avatar"],
            "nickname" => $this->oauth["oauth_nickname"],
            "is_not_in_list" => 0,
            "platform" => $this->oauth["oauth_platform"]
        ];

        $brainstorming = BrainstormingService::getInstance()->get($this->activityId);
        if ($brainstorming["client_type"] != "wechat") {
            $data["is_not_in_list"] = 1;
            $data["message"] = "抱歉，你不在本次活动名单中！";
        }

        return response()->json([
            "error" => 0,
            "data" => $data
        ]);
    }

    public function otherActivitys()
    {
        $brainstorming = BrainstormingService::getInstance()->get($this->activityId);
        if ($brainstorming) {
            $activitys = DB::table("agh_activitys")->where("app_id", 1)
                ->where("corp_id", $brainstorming["corp_id"])
                ->where("status", 1)->get();
            $data = [];
            $time = time();
            foreach ($activitys as $activity) {
                $bs = BrainstormingService::getInstance()->get($activity->activity_id);
                $isActivityStart = 0;
                $sActivityEnd = 0;
                if ($bs["start_time"] < $time || $bs["start_time"] == 0) {
                    $isActivityStart = 1;
                }
                if ($bs["end_time"] < $time) {
                    $sActivityEnd = 1;
                }
                $topBanner = isset($bs["top_banner"]) ? $bs["top_banner"] : "";
                $sponsorCorp = isset($bs["sponsor_corp"]) ? $bs["sponsor_corp"] : "";
                $data[] = [
                    "activity_id" => $bs["activity_id"],
                    "title" => $bs["title"],
                    "top_banner" => $topBanner,
                    "sponsor_corp" => $sponsorCorp,
                    "is_activity_start" => $isActivityStart,
                    "is_activity_end" => $sActivityEnd,
                    "activtiy_tims" => date("Y年m月d日 H:i", $bs["start_time"]) . "至" . date("Y年m月d日 H:i", $bs["end_time"])
                ];
            }

            return response()->json([
                "error" => 0,
                "data" => $data
            ]);
        } else {
            return response()->json([
                "error" => 404,
                "message" => "找不到活动信息"
            ]);
        }
    }

    /**
     * 获取题库分类
     */
    public function getClass(Request $request){
        $activity_id = $this -> activityId;
        try {
            $class_direct = QuestionService::getInstance() ->getClassDirect($activity_id);
            $class_not_direct = QuestionService::getInstance() ->getClassNotDirect($activity_id);
            if ($class_direct || $class_not_direct){
                $direct = array();
                $not_direct = array();
                $tmp_direct = array();
                $tmp_not_direct = array();
                foreach ($class_direct as $key => $c) {
                    $tmp = json_decode($c,256);
                    array_push($direct,$tmp);
                    $tmp_direct[$key] = $tmp["category_id"];
                }
                array_multisort($tmp_direct,SORT_ASC ,SORT_REGULAR ,$direct);
                foreach ($class_not_direct as $key => $c) {
                    $tmp = json_decode($c,256);
                    array_push($not_direct,$tmp);
                    $tmp_not_direct[$key] = $tmp["category_id"];
                }
                array_multisort($tmp_not_direct,SORT_ASC ,SORT_REGULAR ,$not_direct);
                return response()->json([
                    "error" => 0,
                    "direct" => $direct,
                    "not_direct" => $not_direct
                ]);
            }return response()->json([
                "error" => 1000,
                "message" => "暂无题库!"
            ]);
        }catch (\Exception $exception) {
            Log::info($exception->getTraceAsString());
            return response()->json([
                "error" => 500,
                "message" => "服务器内部错误"
            ]);
        }
    }

    /**
     * 获取PK房间信息
     */
    public function room(Request $request)
    {
        $roomId = intval($request->get("room_id"));
        if ($roomId > 0) {
            try {
                $room = PkService::getInstance()->getRoomInfo($roomId);
                if ($room) {
                    if ($this->userId > 0) {
                        Redis::sadd("bs_pk_room_joins:" . $roomId, $this->userId);
                    }
                    $pkUserInfo = PkService::getInstance()->getPkUserInfo($room["sponsor_user_id"], $room["challenger_user_id"]);
                    $data = [
                        "room_id" => $roomId,
                        "knowledge_money" => $room["knowledge_money"],
                        "sponsor_score" => $room["sponsor_score"],
                        "challenger_score" => $room["challenger_score"],
                        "win_user_id" => $room["win_user_id"],
                        "status" => $room["status"],
                        "create_time" => $room["create_time"]
                    ];
                    $data = array_merge($data, $pkUserInfo);

                    return response()->json([
                        "error" => 0,
                        "data" => $data
                    ]);
                } else {
                    return response()->json([
                        "error" => 17000,
                        "message" => "PK已经结束"
                    ]);
                }
            } catch (\Exception $exception) {
                Log::info("get Room Info {$roomId} exception:" . $exception->getMessage());
                Log::info($exception->getTraceAsString());
                return response()->json([
                    "error" => 500,
                    "message" => "服务器内部错误"
                ]);
            }
        } else {
            return response()->json([
                "error" => 404,
                "message" => "PK房间不存在"
            ]);
        }
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function sendsms(Request $request)
    {
        try {
            $phone = $request->json("phone");
            $user = User::where("activity_id", $this->activityId)->where("phone", $phone)->where("status", 1)->first();
            if ($user) {
                if (empty($user->open_id)) {

                    \Aliyun\Core\Config::load();
                    $verifyCode = random_int(100000, 999999);
                    $ret = SmsService::sendSms($phone, $verifyCode);
                    //Log::info($ret);
                    Log::info(CookieService::getOauth());
                    Log::info($phone);

                    //todo send sms
                    Redis::set("bs_sms_verify_code:" . $phone, $verifyCode);
                    Redis::expire("bs_sms_verify_code:" . $phone, 900);

                    return response()->json([
                        "name" => $user['name'],
                        "error" => 0,
                        "message" => "OK"
                    ]);
                } else {
                    return response()->json([
                        "error" => 1000,
                        "message" => "工号：{$phone}已经被绑定!"
                    ]);
                }
            } else {
                return response()->json([
                    "error" => 1000,
                    "message" => "工号：{$phone}不在此次活动名单内!"
                ]);
            }
        } catch (\Exception $exception) {
            Log::info("Send sms exception:" . $exception->getMessage());
            Log::info("Trace message:" . $exception->getTraceAsString());
            return response()->json([
                "error" => 500,
                "message" => config("errMsg.server_error")
            ]);
        }

    }

    public function userbind(Request $request)
    {

        $phone = $request->json("phone");
        $openId = $request->cookie("oauth_open_id");

//        $verifycode = $request->json("verifycode");
        $user = User::where("activity_id", $this->activityId)->where("phone", $phone)->where("status", 1)->first();
        if ($user) {
            if (empty($user->open_id)) {
                        $user->open_id = $openId;
                        $user->save();

                        //添加到agh_wechats
                        DB::select("replace into agh_wechats set open_id='{$openId}',phone='{$phone}'");

                        return response()->json([
                            "error" => 0,
                            "message" => "OK"
                        ]);

            } else {
                return response()->json([
                    "error" => 1000,
                    "message" => "工号：{$phone}已经被绑定!"
                ]);
            }
        } else {
            return response()->json([
                "error" => 1000,
                "message" => "工号：{$phone}不在此次活动名单内!"
            ]);
        }

    }

    protected function ubb($str, $brainstorming, $name)
    {
        $str = str_replace("[活动标题]", $brainstorming["title"], $str);
        $str = str_replace("[姓名]", $name, $str);
        return $str;
    }
}
