<?php
/**
 * Created by PhpStorm.
 * User: leo
 * Date: 2018/4/11
 * Time: 下午1:10
 */

namespace common\helpers;

use backendApi\modules\v1\models\AdminRole;
use common\models\Config;
use common\models\OcrApi;
use common\models\DeclarationLevel;
use common\models\EmployLevel;
use common\models\Region;
use common\models\SmsApi;
use common\models\SmsTemplate;
use common\models\User;
use common\models\UserNetwork;
use common\models\UserRelation;
use common\models\WithdrawLevel;
use Yii;
use backendApi\modules\v1\models\Admin;
use common\models\UserInfo;

class Cache
{
    const SYSTEM_CONFIG_KEY = 'sys:config';
    const DEC_LEVEL_CONFIG_KEY = 'sys:decLevel';
    const DEC_ROLE_CONFIG_KEY = 'sys:decRole';
    const EMP_LEVEL_CONFIG_KEY = 'sys:empLevel';
    const ADMIN_ROLE_KEY = 'sys:adminRole';
    const SMS_TEMPLATE_DEC_KEY = 'sys:smsTemplateDec';
    const SMS_TEMPLATE_EMP_KEY = 'sys:smsTemplateEmp';
    const WITHDRAW_LEVEL_CONFIG_KEY = 'sys:withdrawLevel';
    const OCR_API_CONFIG_KEY = 'sys:ocrApi';
    const SMS_API_CONFIG_KEY = 'sys:smsApi';
    const REGION_CONFIG_KEY = 'sys:region';

    const ASYNC_KEY_PREFIX = 'async_';
    const SOCKET_KEY_PREFIX = 'socket_';
    const SOCKET_ADMIN = 'admin';
    const SOCKET_USER_PC = 'userPc';
    const SOCKET_USER_APP = 'userAPP';

    const USER_CLOSE_KEY_PREFIX = 'user:close_';
    const USER_INFO_KEY = 'user:baseInfo';
    const USER_NETWORK_PARENTS = 'user:networkParents';
    const USER_RELATION_PARENTS = 'user:relationParents';
    const USER_CREATED_AT_LIST = 'user:createdAtList_';

    /**
     * WebSocket的fd加入缓存
     * @param $app
     * @param $userId
     * @param $fd
     * @return mixed
     */
    public static function setWebSocketFd($app, $userId, $fd){
        if(isset($userId) && $userId != ''){
            if($app == self::SOCKET_ADMIN){
                $model = Admin::class;
                $field = 'ID';
            } elseif($app == self::SOCKET_USER_PC) {
                $model = UserInfo::class;
                $field = 'USER_ID';
                $app = self::SOCKET_USER_PC;
            } else {
                $model = UserInfo::class;
                $field = 'USER_ID';
                $app = self::SOCKET_USER_APP;
            }

            if($model::find()->where($field.'=:'.$field, [':'.$field=>$userId])->exists()){
                Yii::$app->redis->hset(self::SOCKET_KEY_PREFIX.$app, $userId, $fd);
            }
        }
        return $fd;
    }

    /**
     * 获取会员的WebSocket的fd
     * @param $app
     * @param $userId
     * @return mixed
     */
    public static function getWebSocketFd($app, $userId){
        return Yii::$app->redis->hget(self::SOCKET_KEY_PREFIX.$app, $userId);
    }

    /**
     * 获取系统配置信息
     * @return array|mixed|\yii\db\ActiveRecord[]
     */
    public static function getSystemConfig(){
        return Config::getFromCache();
    }

    /**
     * 更新系统配置
     * @return array|\yii\db\ActiveRecord[]
     */
    public static function updateSystemConfig(){
        return Config::updateToCache();
    }

    /**
     * 获取报单级别
     * @return array|mixed|\yii\db\ActiveRecord[]
     */
    public static function getDecLevelConfig(){
        return DeclarationLevel::getFromCache();
    }

    /**
     *  更新报单级别
     * @return array|\yii\db\ActiveRecord[]
     */
    public static function updateDecLevelConfig(){
        return DeclarationLevel::updateToCache();
    }

    /**
     * 获取地区
     * @return array|mixed|\yii\db\ActiveRecord[]
     */
    public static function getRegionConfig(){
        return Region::getFromCache();
    }

    /**
     *  更新地区
     * @return array|\yii\db\ActiveRecord[]
     */
    public static function updateRegionConfig(){
        return Region::updateToCache();
    }

    /**
     * 获取聘级
     * @return array|mixed|\yii\db\ActiveRecord[]
     */
    public static function getEmpLevelConfig(){
        return EmployLevel::getFromCache();
    }

    /**
     *  更新管理员角色
     * @return array|\yii\db\ActiveRecord[]
     */
    public static function updateAdminRole(){
        return AdminRole::updateToCache();
    }


    /**
     * 获取管理员角色
     * @return array|mixed|\yii\db\ActiveRecord[]
     */
    public static function getAdminRole(){
        return AdminRole::getFromCache();
    }

    /**
     *  更新聘级
     * @return array|\yii\db\ActiveRecord[]
     */
    public static function updateEmpLevelConfig(){
        return EmployLevel::updateToCache();
    }

    /**
     * 获取用户基本信息
     * @param $userId
     * @return array|null|\yii\db\ActiveRecord
     */
    public static function getUserBaseInfo($userId){
        return User::getBaseInfoFromRedis($userId);
    }

    /**
     * 执行异步任务时往缓存中把要传递的参数都存起来，方便在异步方法中直接调用
     * @param $params
     * @return string
     * @throws \yii\base\Exception
     */
    public static function setAsyncParams($params){
        // 生成一个随机key
        $taskKey = self::createRandomKey(self::ASYNC_KEY_PREFIX);
        Yii::$app->cache->set($taskKey, $params);
        return $taskKey;
    }

    /**
     * 获取异步参数
     * @param $taskKey
     * @return mixed
     */
    public static function getAsyncParams($taskKey){
        $result = Yii::$app->cache->get($taskKey);
        Yii::$app->cache->delete($taskKey);
        return $result;
    }

    /**
     * 获取异步参数但不删除异步参数缓存
     * （用于临时获取一下，但还不影响正式获取后删除的逻辑）
     * @param $taskKey
     * @return mixed
     */
    public static function getAsyncParamsWithoutDel($taskKey){
        return Yii::$app->cache->get($taskKey);
    }

    /**
     * @param $key
     * @return bool
     */
    public static function deleteAsyncParams($key){
        return Yii::$app->cache->delete($key);
    }

    /**
     * 生成一个随机不重复的key
     * @param $prefix
     * @return string
     * @throws \yii\base\Exception
     */
    public static function createRandomKey($prefix){
        $key = Yii::$app->security->generateRandomString(20);
        if(Yii::$app->cache->exists($prefix.$key)){
            self::createRandomKey($prefix);
        }
        return $prefix.$key;
    }

    /**
     * 获取短信模板通过报单级别
     * @return array|mixed
     */
    public static function getSmsTemplateByDec(){
        return SmsTemplate::getDecFromCache();
    }

    /**
     * 获取短信模板通过聘级
     * @return array|mixed
     */
    public static function getSmsTemplateByEmp(){
        return SmsTemplate::getEmpFromCache();
    }

    /**
     * 获取提现等级
     * @return array|mixed|\yii\db\ActiveRecord[]
     */
    public static function getWithdrawLevel(){
        return WithdrawLevel::getFromCache();
    }

    /**
     * 获取报单级别
     * @return array|mixed|\yii\db\ActiveRecord[]
     */
    public static function getOcrApiConfig(){
        return OcrApi::getFromCache();
    }

    /**
     *  更新报单级别
     * @return array|\yii\db\ActiveRecord[]
     */
    public static function updateOcrApiConfig(){
        return OcrApi::updateToCache();
    }

    /**
     * 获取短信接口设置
     * @return array|mixed|\yii\db\ActiveRecord[]
     */
    public static function getSmsApiConfig(){
        return SmsApi::getFromCache();
    }

    /**
     *  更新短信接口设置
     * @return array|\yii\db\ActiveRecord[]
     */
    public static function updateSmsApiConfig(){
        return SmsApi::updateToCache();
    }

    /**
     * 设置上传token
     * @return string
     * @throws \yii\base\Exception
     */
    public static function setUploadToken(){
        $token = Yii::$app->security->generateRandomString(32);
        Yii::$app->cache->set($token, 1, 5 * 60);
        return $token;
    }

    /**
     * 用上传token获取上传资格
     * @param $token
     * @return mixed
     */
    public static function getUploadToken($token){
        $result = Yii::$app->cache->get($token);
        Yii::$app->cache->delete($token);
        return $result;
    }

    /**
     * 获取全部安置网络上级
     * @param $userId
     * @return array|mixed
     */
    public static function getAllNetworkParents($userId){
        return UserNetwork::getAllParentsFromRedis($userId);
    }

    /**
     * 获取全部推荐网络的上级
     * @param $userId
     * @return array|mixed
     */
    public static function getAllRelationParents($userId){
        return UserRelation::getAllParentsFromRedis($userId);
    }

}