<?php
namespace Passport\Src;

use Dever;
use Passport\Src\Lib\Base;

class User extends Base
{
    private $user;
    public function __construct()
    {
        parent::__construct();
        $this->init();
    }

    public function init()
    {
        if (!$this->user) {
            $this->user = $this->info();
        }

        return $this->user;
    }

    public function data()
    {
        if ($this->user) {
            $this->user['link'] = Dever::url('user/info', 'main');
            $this->user['link'] = Dever::url('forum/list?uid=' . $this->user['id'], 'main');
        }
        return $this->user;
    }

    public function checkLogin()
    {
        if (!$this->user) {
            Dever::alert('请先登录', true);
        }
    }

    public function updateInfo()
    {
        $this->checkLogin();

        //$update['set_mobile'] = Dever::input('mobile');
        $update['set_username'] = Dever::input('username');
        $update['set_avatar'] = Dever::input('avatar') ? Dever::input('avatar') . '?v=' . time() : false;
        $update['where_id'] = $this->user['id'];
        $sex = Dever::input('sex', 0);
        $update['set_sex'] = $this->saveSex($sex);
        $update['set_avatar'] = $this->saveAvatar($update['set_avatar']);

        Dever::load('passport/user-update', $update);

        $this->user = $this->save($this->user['id']);

        return true;
    }

    public function updateAvatar()
    {
        $this->checkLogin();

        $update['set_avatar'] = Dever::input('avatar') ? Dever::input('avatar') . '?v=' . time() : false;
        $update['where_id'] = $this->user['id'];

        if ($update['set_avatar']) {
            $update['set_avatar'] = $this->saveAvatar($update['set_avatar']);

            Dever::load('passport/user-update', $update);

            $this->user = $this->save($this->user['id']);
        }

        return true;
    }

    public function updateWeixin()
    {
        $this->checkLogin();

        Dever::load('passport/user-update', array('where_id' => $this->user['id'], 'set_weixin' => 1));

        return true;
    }
}
