<?php
/**
 * Created by PhpStorm
 * User: 林志杰
 * Email: 598287049@qq.com
 * Time: 2020/1/2 12:58
 */

namespace app\admin\controller;

use app\admin\business\AdminUser as AdminUserBusiness;
use app\admin\validate\AdminUser as AdminUserValidate;
use think\facade\View;


class Login extends AdminBase
{
    public function initialize()
    {
        if ($this->isLogin()) {
            return $this->redirect(url('index/index'), 302);
        }
    }

    public function index()
    {
        return View::fetch();
    }

    public function md5()
    {
        halt(session(config('admin.session_admin')));
        echo md5('admin_singwa_abc');
    }

    public function check()
    {
        if (!$this->request->isPost()) {
            return show(config('status.error'), '请求方式错误');
        }

        // 参数校验 1、原生方式  2、TP6 验证机制
        $username = $this->request->param('username', '', 'trim');
        $password = $this->request->param('password', '', 'trim');
        $captcha = $this->request->param('captcha', '', 'trim');

        $data = [
            'username' => $username,
            'password' => $password,
            'captcha' => $captcha,
        ];
        $validate = new AdminUserValidate();
        if (!$validate->check($data)) {
            return show(config('status.error'), $validate->getError());
        }
//        if (empty($username) || empty($password) || empty($captcha)) {
//            return show(config('status.error'), '参数不能为空');
//        }
        // 验证码校验
//        if (!captcha_check($captcha)) {
//            // 验证码校验失败
//            return show(config('status.error'), '验证码不正确');
//        }

        try {
            $result = AdminUserBusiness::login($data);
        } catch (\Exception $e) {
            return show(config('status.error'), $e->getMessage());
        }
        if ($result) {
            return show(config('status.success'), '登录成功');
        } else {
            return show(config('status.error'), '登录失败');
        }
    }
}