<?php

namespace app\index\controller;

use app\model\Category;
use app\model\Nav;
use app\model\Post;
use think\facade\Cache;
use think\facade\Session;
use think\facade\View;
use think\helper\Str;
use UserHub\Client;

class Common extends BaseController
{
  public function initialize()
  {
    parent::initialize();


    $list_nav_slide = Nav::where('type', 3)->cache('type_list_3')->order('sort asc')->where('status', 1)->select();

    View::assign('list_nav_slide', $list_nav_slide);

    $list_nav_friend_url = Nav::where('type', 2)->cache('type_list_2')->order('sort asc')->where('status', 1)->select();
    View::assign('list_nav_friend_url', $list_nav_friend_url);

    $list_header_nav = Nav::where('type', 11)->cache('type_list_11')->order('sort asc')->where('status', 1)->select();
    View::assign('list_header_nav', $list_header_nav);

    $list_category_first_level = Category::where('level', 1)->where('status', 1)->where('type', 3)->cache('category_type_list_3')->order('sort asc')->select();
    View::assign('list_category_first_level', $list_category_first_level);
    $list_nav_more = Nav::where('type', 8)->cache('type_list_8')->order('sort asc')->where('status', 1)->select();
    View::assign('list_nav_more', $list_nav_more);

    $top_posts = Post::where('is_top', 1)->limit(8)->where('type', 3)->cache('top_post')->select();
    View::assign('top_posts', $top_posts);

    $this->userHubLogin();
  }

  public function userHubLogin()
  {
    $user_uid = Session::get('user_uid');
    $user_info = [];
    if (empty($user_uid)) {
      $code = $this->request->param('code');

      // 实例化客户端,传入相关参数
      $user_hub_client = new Client([
        'key' => get_system_config('user_hub_key'),
        'secret' => get_system_config('user_hub_secret'),
        'host' => get_system_config('user_hub_host'),     
      ]);
      if (empty($code)) {
        // 跳转登录
        $url = $user_hub_client->getBowserRedirectUrl($this->request->url(true));
        View::assign('login_url',$url);
      } else {
        // 获取用户信息
        $user_info = $user_hub_client->getUserinfoByCode($code);
        Session::set('user_uid', $user_info['uid']);
        
      }
    }else{
      $user_info = self::getUserInfo($user_uid);
    }
    View::assign('user_info',$user_info);
  }

  public static function getUserInfo($uid)
  {
    $cache_key = 'user_uid_'.$uid;
    $user_info = Cache::get($cache_key);

    if(is_null($user_info)){
      // 实例化客户端,传入相关参数
      $user_hub_client = new Client([
        'key' => get_system_config('user_hub_key'),
        'secret' => get_system_config('user_hub_secret'),
        'host' => get_system_config('user_hub_host'),     
      ]);

      $user_info = $user_hub_client->getUserinfoByUid($uid);

      Cache::set($cache_key,$user_info);
    }

    return $user_info;
  }
}
