<?php
namespace app\user\controller;

use app\common\controller\UserBaseController;
use app\common\model\UserModel;
use app\common\validate\UserValidate;
use think\Db;

class AuthController extends UserBaseController
{
    public function login()
    {
        return $this->fetch();
    }

    public function doLogin()
    {
        if ($this->request->isPost()) {
            $name = $this->request->param('username', '');
            $pass = $this->request->param('password','');

            $result = Db::name('user')->where('mobile', $name)->find();

            if (!empty($result)) {
                if (compare_password($pass, $result['login_pwd'])) {

                    unset($result['login_pwd']);

                    session('user', $result);

                    $update['id'] = $result['id'];
                    $update['last_login_ip'] = $this->request->ip();
                    $update['last_login_time'] = time();

                    Db::name('user')->update($update);

                    $this->success('验证通过', url('user/index/index'));
                } else {
                    $this->error('密码不正确');
                }
            } else {
                $this->error('账号不存在');
            }
        } else {
            $this->error('非法请求');
        }
    }

    public function register()
    {
        return $this->fetch();
    }

    public function doRegister()
    {
        if ($this->request->isPost()) {

            $data = $this->request->only(['mobile','login_pwd']);

            $validate = new UserValidate();
            $result = $validate->check($data);

            if (!$result)
                $this->error($validate->getError());

            $data['login_pwd'] = password($data['login_pwd']);

            $data['create_time'] = time();
            $data['create_ip'] = $this->request->ip();

            Db::startTrans();
            try {
                $user = UserModel::create($data);

                $uid = $user->id;

                $spread_uid = $this->request->param('spread_uid', 0);

                UserModel::setSpread($spread_uid, $uid);

                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
            }
            $this->success('注册成功', url('login'));
        } else {
            $this->error('非法请求');
        }
    }

}