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

namespace common\helpers;

use Yii;
use common\models\Config;
use common\models\OcrApi;
use common\models\DeclarationLevel;
use common\models\EmployLevel;
use common\models\Region;
use common\models\User;
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;
    }

    /**
     * @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 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|\yii\db\ActiveRecord[]
     */
    public static function getOcrApiConfig(){
        return OcrApi::getFromCache();
    }

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