<?php
/**
 * 分销商城常用通用方法集合类
 * ============================================================================
 * * 版权所有 蜘蛛出行 * *
 * 网站地址: http://www.zhizhuchuxing.com
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和
 * 使用；不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * Author By: 倪宗锋
 * PhpStorm ShopUtil.php
 * Create By 2017/3/1 19:10 $
 */


namespace shop\util;

use common\util\Util;
use common\models\ShUser;
use common\util\WeChatPay;
use common\util\WeChatService;
use Yii;
use yii\helpers\ArrayHelper;

class ShopUtil
{
    private static $siteConfig = null;//自定义配置文件信息
    private static $unLoginConfig = null;//非强制登录接口配置
    public static $uid = 1;//用户ID
    private static $fx_uid = 0;//分销商户ID  不可直接读取该属性

    /**
     * Des:获取当前应用配置参数
     * Name: getSiteConfig
     * @return array
     * @author 倪宗锋
     */
    public static function getSiteConfig()
    {
        if (static::$siteConfig == null) {
            static::$siteConfig = ArrayHelper::merge(
                require APP_PATH . '/config/siteConfig.php',
                Util::getSiteConfig()
            );
        }
        return static::$siteConfig;
    }

    /**
     * Des: 获取分销商户ID
     * Name: getFxUid
     * @return int
     * @author 倪宗锋
     */
    public static function getFxUid()
    {
        $cookies = $_COOKIE;
        //验证分销商户的合法性
        if (isset($cookies['fx_uid']) && Util::checkPattern('intVal', $cookies['fx_uid'])) {
            return $cookies['fx_uid'];
        }
        return static::$fx_uid;
    }

    /**
     * Des:获取未登录可访问接口路径配置
     * Name: getUnLoginConfig
     * @return array
     * @author 倪宗锋
     */
    public static function getUnLoginConfig()
    {
        if (static::$unLoginConfig == null) {
            static::$unLoginConfig = require APP_PATH . '/config/unLoginConfig.php';
        }
        return static::$unLoginConfig;
    }

    /**
     * Des:用户登录
     * Name: checkLogin
     * @return array
     * @author 倪宗锋
     */
    public static function checkLogin()
    {
        $cookies = $_COOKIE;
        /**如果用户未登录**/
        $siteConfig = ShopUtil::getSiteConfig();
        $showUrl = $siteConfig['host_name'] . $siteConfig['shop_authLoginRedirectUrl'] . '&redirect=';
        if (empty($cookies['shop_token'])) {
            return Util::returnArrEr('用户未登录!', '', $showUrl, 'SHOP-100001');
        } else {
            //将token进行解密
            $tokenInfo = Util::authCode($cookies['shop_token'], 'DECODE');
            $uid = strstr($tokenInfo, '=', true);
            /**获取用户token并校验token的正确性**/
            $cache = Yii::$app->cache;
            $tokenKey = 'SHOP_LOGIN_' . YII_ENV . '_' .  $uid;
            $userToken = $cache->get($tokenKey);
            if ($userToken != $cookies['shop_token']) {
                return Util::returnArrEr('用户未登录!', '', $showUrl, 'SHOP-100001');
            }
            $cache->set($tokenKey, $userToken, 2592000);
            static::$uid = $uid;
        }
        return Util::returnArrSu();
    }

    /**
     * Des:设置用户登录状态
     * Name: setLoginByOpenid
     * @param $openid
     * @return array
     * @author 倪宗锋
     */
    public static function setLoginByOpenid($openid)
    {
        $ShUser = new ShUser();
        $uid = $ShUser->getUidByOpenid($openid);
        if (empty($uid)) {
            $weChatInfo['openid'] = $openid;
            $weChatInfo['fx_uid'] = static::getFxUid();//获取分销商户ID
            $ShUser->addUserFromWeChat($weChatInfo);
            $uid = $ShUser->getUidByOpenid($openid);
            if (empty($uid)) {
                return Util::returnArrEr('授权登录失败!');
            }
        }
        static::$uid = $uid;
        $userToken = Util::authCode($uid . '=' . microtime(true), 'ENCODE');
        $cache = Yii::$app->cache;
        $tokenKey = 'SHOP_LOGIN_' . YII_ENV . '_' . $uid;
        $cache->set($tokenKey, $userToken, 2592000);
        setcookie('shop_token', $userToken, time() + 3600000, "/");
        return Util::returnArrSu('');
    }

    /**
     * Des:获取用户信息
     * Name: getUserInfo
     * @return array
     * @author 倪宗锋
     */
    public static function getUserInfo()
    {
        if (empty(static::$uid)) {
            $siteConfig = ShopUtil::getSiteConfig();
            $showUrl = $siteConfig['host_name'] . $siteConfig['shop_authLoginRedirectUrl'] . '&redirect=';
            return Util::returnArrEr('未登录，不能获取用户信息', '', $showUrl, 'FX-100001');
        }
        $fx_user = new ShUser();
        $userInfo = $fx_user->getUserInfoByUid(static::$uid);
        return Util::returnArrSu('', $userInfo);
    }
    /**
     * Des:获取当前页面的授权登录地址授权登录
     * Name: getAuthLoginUrl
     * @return string
     * @author 倪宗锋
     */
    public static function getAuthLoginUrl($showUrl)
    {
        $WxPayConfig = WeChatPay::getAuthWeChatConfig();
        $siteConfig = static::getSiteConfig();
        $redirect_uri = $siteConfig['weChatAuthLoginUrl'];
        $setLoginUrl = $siteConfig['host_name'] . $siteConfig['shop_authLoginUrl'] . '&redirect=' . urlencode($showUrl);
        $urlObj["appid"] = $WxPayConfig['appid'];
        $urlObj["redirect_uri"] = $redirect_uri . '&redirect=' . urlencode($setLoginUrl);
        $urlObj["response_type"] = "code";
        $urlObj["scope"] = "snsapi_base";//授权登录
        $urlObj["state"] = rand(10, 99) . "#wechat_redirect";
        $bizString = http_build_query($urlObj);
        $url = $siteConfig['authorizeUrl'] . $bizString;
        return $url;
    }



}