<?php

namespace app\admin\controller;

use think\facade\Db;
use think\facade\Session;
use think\facade\View;
use think\Request;
use app\admin\validate\LoginValidate;

/**
 * 登录控制器
 * Class Login
 * @package app\admin\controller
 */
class Login
{
    /**
     * 登录方法
     * @return mixed
     */
    public function login(Request $r)
    {
        if (Session::has('cust_info')) {
            return redirect(adminUrl('admin/index/index'));
        }

        if ($r->isAjax() && $r->isPost()) {
            $data = $r->post();
            $validate = new LoginValidate();

            if (!$validate->check($data)) {
                return json(['code' => 300, 'data' => $validate->getError()]);
            }

            $tomerInfo = Db::name('im_customer')
                ->where('uname', $data['uname'])->find();
            if ($tomerInfo) {
                $upass = $tomerInfo['upass'];
                $salt  = $tomerInfo['salt'];
                if (md5($data['upass'].$salt) == $upass) {
                    Session::set('cust_info', [
                        'cuid'  => $tomerInfo['id'],
                        'uname' => $tomerInfo['uname'],
                        'nick'  => $tomerInfo['nick']
                    ]);
                    Db::name('im_customer')
                        ->save(['id' => $tomerInfo['id'], 'login_time' => time(), 'state' => 1]);
                    return json(['code' => 200, 'data' => '登录成功']);
                }
            }
            return json(['code' => 300, 'data' => '用户名或者密码错误']);
        }

        return View::fetch();
    }
}