<?php
/**
 * User Service
 * Created by PhpStorm.
 * User: guanxl
 * Date: 2018/3/23
 * Time: 19:20
 */

namespace App\Services;

use App\Models\Corp;
use App\Models\Department;
use App\Models\User;
use App\Traits\Singleton;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;

class UserService
{

    use Singleton;

    const REDIS_USERS = "bs_users";
    const REDIS_USERS_OPEN_ID = "bs_users_open_id";
    const REDIS_AGH_GCORP = "agh_gcorp";
    const WHITE_LIST = "bs_white_list";
    const REDIS_USERS_GUID = "bs_user_guid";
    const REDIS_AGH_GUID = "agh_guid";
    const USER_CURRENT_WORK = "bs_user_current_work";
    const WEBSOCKET_USERS = "bs_websocket_users";

    public function auth2($activityId, $openid, $avatar, $nickname, $platform)
    {

        try {
            $key = self::REDIS_USERS_OPEN_ID . ":" . $activityId . ":" . $openid;
            $userId = Redis::get($key);
            if (empty($userId)) {
                $user = User::where("activity_id", $activityId)->where("open_id", $openid)->where("status", 1)->first();
                if (empty($user)) {
                    //此微信之前是否有绑定过手机号码
                    $phones = DB::table("agh_wechats")->where("open_id", $openid)->pluck("phone")->toArray();
                    if (!empty($phones)) {
                        $user = User::where("activity_id", $activityId)->whereIn("phone", $phones)->first();
                    }
                }

                if (!empty($user)) {
                    if (!empty($openid)) $user->open_id = $openid;
                    if (!empty($avatar)) $user->avatar = $avatar;
                    if (!empty($nickname)) $user->nickname = $nickname;
                    $user->platform = $platform;
                    $user->save();
                    $user = collect($user)->toArray();
                    $user["department_name"] = DepartmentService::getInstance()->getDepartmentName($user["department_id"]);
                    Redis::hMset(self::REDIS_USERS . ":" . $user["user_id"], $user);
                    Redis::expire(self::REDIS_USERS . ":" . $user["user_id"], 600);
                    Redis::set($key, $user["user_id"]);
                    Redis::expire($key, 600);
                    return $user;
                }

            } else {
                return $this->getUser($userId);
            }
        } catch (\Exception $exception) {
            Log::info($exception->getMessage());
        }
        return null;

    }

    /**
     * 判断是否在白名单里面
     */
    public function isWhiteList($ystId)
    {
        return Redis::sismember(self::WHITE_LIST, $ystId);
    }

    /**
     * 获得用户信息
     * @param $userId
     * @param string $hashKey
     * @param bool $force 强制从数据库里面获取
     * @return mixed
     */
    public function getUser($userId, $hashKey = "", $force = false)
    {
        $key = self::REDIS_USERS . ":" . $userId;
        if (!Redis::exists($key) || $force) {
            $user = User::find($userId);
            if ($user) {
                $user = collect($user)->toArray();
                $user["department_name"] = DepartmentService::getInstance()->getDepartmentName($user["department_id"]);
                Redis::hMset($key, $user);
                Redis::expire($key, 600);
            } else {
                return null;
            }
        }
        if (empty($hashKey)) {
            return Redis::hGetAll(self::REDIS_USERS . ":" . $userId);
        } else {
            return Redis::hGet(self::REDIS_USERS . ":" . $userId, $hashKey);
        }
    }

    /**
     * 根据openId增加用户
     * @param $activityId
     * @param $openid
     * @param $avatar
     * @param $nickname
     * @param $platform
     * @param string $departmentName
     * @return bool
     */
    public function addUserByOpenId($activityId, $openid, $avatar, $nickname, $platform, $departmentName = "")
    {
        $activity = BrainstormingService::getInstance()->get($activityId);
        $departmentId = 0;

        if (!empty($departmentName)) {
            $department = Department::where("activity_id", $activityId)->where("department_name", $departmentName)->first();
            if (empty($department)) {
                $data = [];
                $data['activity_id'] = $activityId;
                $data["corp_id"] = $activity["corp_id"];
                $data["department_name"] = $departmentName;
                $department = Department::create($data);
            } else {
                if ($department->status == 0) {
                    $department->status = 1;
                    $department->save();
                }
            }
            $departmentId = empty($department) ? 0 : $department->department_id;
        }


        $user = User::where("activity_id", $activityId)
            ->where("open_id", $openid)->where("status", 1)->first();

        if (empty($user)) {
            $query = [];
            $query['activity_id'] = $activityId;
            $query["corp_id"] = $activity["corp_id"];
            $query['open_id'] = $openid;
            $query['guid'] = $openid;
            $query['name'] = $nickname;
            $query['nickname'] = "";
            $query['department_id'] = $departmentId;
            $query['email'] = "";
            $query['phone'] = "";
            $query['avatar'] = $avatar;
            $query['platform'] = $platform;

            User::create($query);
        } else {
            if ($departmentId != $user->department_id) {
                $user->department_id = $departmentId;
                $user->save();
            }
        }
        return true;
    }

    /**
     * 使用Guid的用户信息，新增用户
     * @param $activityId int 活动ID
     * @param $guid int 爱关怀的用户ID
     * @param $gCorpId
     * @param bool $hasDepartment 是否需要新增部门
     * @return mixed
     */
    public function addUserByGuid($activityId, $guid, $gCorpId, $hasDepartment = false)
    {

        $gUser = Redis::get(self::REDIS_AGH_GUID . ":" . $guid);
        $brainstorming = BrainstormingService::getInstance()->get($activityId);
        $gCorp = $this->getCorpByGcorpId($gCorpId);
        $corpId = isset($gCorp["corp_id"]) ? $gCorp["corp_id"] : 0;
        if ($brainstorming["corp_id"] != $corpId) {
            return ["error" => 1000, "corp_short_name" => $brainstorming["corp_short_name"]];
        }

        if ($gUser) {
            $gUser = json_decode($gUser, true);
            $departmentId = 0;
            if ($hasDepartment) {
                if (!empty($gCorp)) {
                    $department = Department::where("activity_id", $activityId)
                        ->where("corp_id", $gCorp["corp_id"])->first();
                    if (empty($department)) {
                        $department = Department::create([
                            "activity_id" => $activityId,
                            "corp_id" => $gCorp["corp_id"],
                            "department_name" => $gCorp["corp_short_name"]
                        ]);
                    }
                    if ($department) {
                        $departmentId = $department->department_id;
                    }
                }
            }


            $user = User::where("activity_id", $activityId)
                ->where("guid", $guid)->where("status", 1)->first();

            if (empty($user)) {
                foreach ($gUser["subUids"] as $subUser) {
                    if ($subUser["corpId"] == $gCorpId) {
                        $query = [];
                        $query['corp_id'] = $gCorp["corp_id"];
                        $query['activity_id'] = $activityId;
                        $query['guid'] = $guid;
                        $query['name'] = $subUser['realName'];
                        $query['nickname'] = "";
                        $query['department_id'] = $departmentId;
                        $query['email'] = $subUser['email'];
                        $query['phone'] = $subUser['mobile'];
                        $query['avatar'] = "";
                        $query['platform'] = "";

                        User::create($query);
                        break;
                    }
                }
            }

        }
        return ["error" => 0, "corp_name" => $brainstorming["corp_name"]];
    }

    /**
     * @param $gCorpId
     * @return mixed
     */
    public function getCorpByGcorpId($gCorpId)
    {
        $redisKey = self::REDIS_AGH_GCORP . ":" . $gCorpId;
        $gcorp = Redis::get($redisKey);
        if (empty($gcorp)) {
            $gcorp = Corp::where("source_id", $gCorpId)->where("source_type", "agh")->first();
            if ($gcorp) {
                $gcorp = collect($gcorp)->toArray();
                Redis::set($redisKey, json_encode($gcorp));
                Redis::expire($redisKey, 300);
            }
        } else {
            $gcorp = json_decode($gcorp, true);
        }
        return $gcorp;
    }

    /**
     * 使用guid认证
     * @param $activityId
     * @param $openid
     * @param $avatar
     * @param $nickname
     * @param $platform
     * @param $guid
     * @return array|mixed|null
     */

    public function authByGuid($activityId, $openid, $avatar, $nickname, $platform, $guid)
    {

        try {
            $key = self::REDIS_USERS_GUID . ":" . $activityId . ":" . $guid;
            $userId = Redis::get($key);
            if (empty($userId)) {
                $user = User::where("activity_id", $activityId)->where("guid", $guid)->where("status", 1)->first();
                if (!empty($user)) {
                    if (!empty($avatar)) $user->avatar = $avatar;
                    if (!empty($nickname)) $user->nickname = $nickname;
                    if ($user->name == "***") $user->name = $nickname;
                    $user->open_id = $openid;
                    $user->platform = $platform;
                    $user->save();
                    $user = collect($user)->toArray();
                    $user["department_name"] = DepartmentService::getInstance()->getDepartmentName($user["department_id"]);
                    Redis::hMset(self::REDIS_USERS . ":" . $user["user_id"], $user);
                    Redis::expire(self::REDIS_USERS . ":" . $user["user_id"], 600);
                    Redis::set($key, $user["user_id"]);
                    Redis::expire($key, 600);
                    return $user;
                }

            } else {
                return $this->getUser($userId);
            }
        } catch (\Exception $exception) {
            Log::info($exception->getMessage());
        }
        return null;

    }

    /**
     * 获得用户在线信息
     * @param $userId
     * @return mixed
     */
    public function getOnlineInfo($userId)
    {
        return Redis::hGetAll(self::WEBSOCKET_USERS . ":" . $userId);
    }


    /**
     * 设置现在用户正在进行的事项，如答题，PK
     * @param $userId
     * @param $channel
     * @param $id
     * @param int $timeout
     */
    public function setUserCurrentWork($userId, $channel, $id, $timeout = 600)
    {
        Redis::hMset(self::USER_CURRENT_WORK . ":" . $userId, [
            "channel" => $channel,
            "id" => $id
        ]);
        Redis::expire(self::USER_CURRENT_WORK . ":" . $userId, $timeout);
    }

    /**
     * 清除用户的工作项
     * @param $userId
     */
    public function unsetUserCurrentWork($userId)
    {
        Redis::del(self::USER_CURRENT_WORK . ":" . $userId);
    }

    /**
     * 获取用户当前正在工作项
     * @param $userId
     * @return mixed
     */
    public function getUserCurrentWork($userId)
    {
        return Redis::hGetAll(self::USER_CURRENT_WORK . ":" . $userId);
    }
}