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


namespace fx\util;

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

class FxUtil
{
    private static $siteConfig = null;//自定义配置文件信息
    private static $unLoginConfig = null;//非强制登录接口配置
    public static $uid = 6;//分销用户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:获取未登录可访问接口路径配置
     * 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($checkPhone = true)
    {
        $cookies = $_COOKIE;
        /**如果用户未登录**/
        $siteConfig = FxUtil::getSiteConfig();
        $showUrl = $siteConfig['host_name'] . $siteConfig['fx_authLoginRedirectUrl'] . '&redirect=';
        if (empty($cookies['fx_token'])) {
            return Util::returnArrEr('用户未登录!', '', $showUrl, 'FX-100001');
        } else {
            //将token进行解密
            $tokenInfo = Util::authCode($cookies['fx_token'], 'DECODE');
            $uid = strstr($tokenInfo, '=', true);
            /**获取用户token并校验token的正确性**/
            $cache = Yii::$app->cache;
            $tokenKey = 'FX_LOGIN_' . YII_ENV . '_' . $uid;
            $userToken = $cache->get($tokenKey);
            if ($userToken['fx_token'] != $cookies['fx_token']) {
                return Util::returnArrEr('用户未登录!', '', $showUrl, 'FX-100001');
            }

            if (empty($userToken['phone']) && $checkPhone) {
                return Util::returnArrEr('请绑定手机号!', '', $showUrl, 'FX-100002');
            }
            $cache->set($tokenKey, $userToken, 2592000);
            static::$uid = $uid;
        }
        return Util::returnArrSu();
    }

    /**
     * Des:设置用户登录状态
     * Name: setLoginByOpenid
     * @param $openid
     * @param $accessToken
     * $params $uid 用户ID
     * @return array
     * @author 倪宗锋
     */
    public static function setLoginByOpenid($openid, $accessToken, $uid = '')
    {
        $fxUser = new FxUser();
        if (empty($uid)) {
            $userInfo = $fxUser->getInfoByOpenid($openid);
            if (empty($userInfo['uid'])) {
                $weChatInfo = WeChatService::getAuthWeChatInfo($openid, $accessToken);
                $weChatInfo['openid'] = $openid;
                $fxUser->addUserFromWeChat($weChatInfo);
                $userInfo = $fxUser->getInfoByOpenid($openid);
                if (empty($userInfo['uid'])) {
                    return Util::returnArrEr('授权登录失败!');
                }
            }
        } else {
            $userInfo = $fxUser->getUserInfoByUid($uid);
            if (empty($userInfo['uid'])) {
                return Util::returnArrEr('用户不存在！');
            }
        }
        if ($userInfo['status'] == 3) {
            return Util::returnArrEr('您的账户正在审核中,请耐心等候...');
        }
        if ($userInfo['status'] == 1) {
            return Util::returnArrEr('您的账户已停用,请联系客服！');
        }

        static::$uid = $userInfo['uid'];
        $userToken = Util::authCode($userInfo['uid'] . '=' . microtime(true), 'ENCODE');
        $cache = Yii::$app->cache;
        $tokenKey = 'FX_LOGIN_' . YII_ENV . '_' . $userInfo['uid'];
        $cache->set($tokenKey, ['fx_token' => $userToken, 'phone' => $userInfo['phone']], 2592000);
        setcookie('fx_token', $userToken, time() + 3600000, "/");
        return Util::returnArrSu('');
    }

    /**
     * Des:获取用户信息
     * Name: getUserInfo
     * @return array|null|string|\yii\db\ActiveRecord
     * @author 倪宗锋
     */
    public static function getUserInfo()
    {
        if (empty(static::$uid)) {
            $siteConfig = FxUtil::getSiteConfig();
            $showUrl = $siteConfig['host_name'] . $siteConfig['fx_authLoginRedirectUrl'] . '&redirect=';
            return Util::returnArrEr('未登录，不能获取用户信息', '', $showUrl, 'FX-100001');
        }
        $fx_user = new FxUser();
        $userInfo = $fx_user->getUserInfoByUid(static::$uid);
        return Util::returnArrSu('', $userInfo);

    }

    /**
     * Des:获取当前页面的授权登录地址授权登录
     * Name: getAuthLoginUrl
     * @param $showUrl string 展示页面地址
     * @return string
     * @author 倪宗锋
     */
    public static function getAuthLoginUrl($showUrl)
    {
        $WxPayConfig = WeChatPay::getAuthWeChatConfig();
        $siteConfig = static::getSiteConfig();
        $redirect_uri = $siteConfig['weChatAuthLoginUrl'];
        $setLoginUrl = $siteConfig['host_name'] . $siteConfig['fx_authLoginUrl'] . '&redirect=' . urlencode($showUrl);
        $urlObj["appid"] = $WxPayConfig['appid'];
        $urlObj["redirect_uri"] = $redirect_uri . '&redirect=' . urlencode($setLoginUrl);
        $urlObj["response_type"] = "code";
        $urlObj["scope"] = "snsapi_userinfo";//授权登录
        $urlObj["state"] = rand(10, 99) . "#wechat_redirect";
        $bizString = http_build_query($urlObj);
        $url = $siteConfig['authorizeUrl'] . $bizString;
        return $url;
    }


    /**
     * Des:获取当前用户的分析二维码
     * Name: getFXQrCode
     * @return array
     * @author 倪宗锋
     */
    public static function getFXQrCode()
    {

        $result = WeChatService::getFxQrCode(self::$uid);
        $newUrl = WeChatService::getFxNewQrCode(self::$uid);
        if ($newUrl['flag'] == true) {
            $result['data']['newUrl'] = $newUrl['data']['url'];
        }
        return $result;
    }



}