<?php

namespace app\index\controller;

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

class Common extends BaseController
{
  public $modelUser = null;

  public function initialize()
  {
    parent::initialize();

    $user_id = Session::get('user_id');

    if (!empty($user_id)) {
      $this->modelUser = User::find($user_id);
      View::assign('user', $this->modelUser);
    }else{
      $this->tempLogin();
    }

    $this->ulthonLogin();
  }

  public function tempLogin()
  {
    if (empty($this->modelUser)) {
      $temp_user = [];
      $temp_user['account'] = uniqid();

      $temp_user['type'] = 'temp';

      $model_user = User::create($temp_user);

      $this->modelUser = $model_user;
      Session::set('user_id', $model_user->id);
      View::assign('user', $this->modelUser);

    }
  }

  public function ulthonLogin()
  {

    if (empty($this->modelUser) || $this->modelUser->type != 'ulthon') {
      $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('ulthon_login_url',$url);

      } else {
        $user_info = $user_hub_client->getUserinfoByCode($code);

        $model_user = User::where('uid', $user_info['uid'])->find();

        if (empty($model_user)) {
          unset($user_info['id']);
          // TODO:处理数据,或者中转数据
          // TODO:下载头像

          $user_info['type']  = 'ulthon';

          $model_user = User::create((array)$user_info);
        }

        $this->modelUser = $model_user;
      }
      Session::set('user_id', $this->modelUser->id);
      View::assign('user', $this->modelUser);
    }
  }

}
