<?php

namespace app\admin\controller\index;

use app\admin\controller\BaseController;
use app\admin\server\index\IndexServer;
use app\admin\server\index\LoginServer;
use Gregwar\Captcha\CaptchaBuilder;
use support\Redis;
use support\Request;

class Login extends BaseController
{
    /**
     * Notes:管理员登录
     * User: yym
     * Date: 2022/8/02
     */
    public function login()
    {
        $user_name = (string)$this->request->post('user_name');//账户
        $password  = (string)$this->request->post('password');//密码
        $captcha   = $this->request->post('captcha', '');//验证码
        $this->validateCheck('index\LoginValidate',['user_name' => $user_name, 'password' => $password], 'login_admin');
        return json_success(LoginServer::login($user_name, $password, $captcha), '登录成功');
    }

    /**
     * Notes:获取图形验证码
     * @return \support\Response
     * User: yym
     * Date: 2022/8/2
     */
    public function getCaptcha()
    {
        // 初始化验证码类
        $builder = new CaptchaBuilder();
        // 生成验证码
        $builder->build();
        // 将验证码的值存储到session中
        $this->request->session()->set('captcha', strtolower($builder->getPhrase()));
        // 获得验证码图片二进制数据
        $img_content = $builder->get();
        // 输出验证码二进制数据
        return response($img_content, 200, ['Content-Type' => 'image/jpeg']);
    }

    /**
     * Notes:管理员修改密码
     * @return \support\Response
     * @throws \Exception
     * User: yym
     * Date: 2022/8/3
     */
    public function updatePwd()
    {
        $old_pwd     = (string)$this->request->post('old_pwd');//旧密码
        $new_pwd     = (string)$this->request->post('new_pwd');//新密码
        $confirm_pwd = (string)$this->request->post('confirm_pwd');//确认密码
        $admin_id    = (int)$this->request->admin_id;
        $this->validateCheck('index\IndexValidate', ['old_pwd' => $old_pwd, 'new_pwd' => $new_pwd, 'confirm_pwd' => $confirm_pwd], 'up_pwd');
        IndexServer::updatePwd($admin_id, $old_pwd, $new_pwd, $confirm_pwd);
        return json_success([], '修改成功');
    }

    /**
     * Notes:退出登录
     * @return \support\Response
     * User: yym
     * Date: 2022/8/3
     */
    public function loginOut()
    {
        LoginServer::loginOut($this->request->admin_token);
        return json_success([], '退出成功');
    }
}
