<?php

namespace app\home\controller;

use think\Controller;
use think\Lang;
use think\Validate;

class Login extends Controller
{

    public function _initialize()
    {
        parent::_initialize();
        Lang::load(APP_PATH . 'home/lang/' . config('default_lang') . '/login.lang.php');
    }

    /**
     * 登录
     * @return mixed
     */
    public function index()
    {
        if (session('service_id')) {
            $this->success('已经登录', 'home/Index/index');
        }
        if (request()->isPost()) {

            $service_name = input('post.service_name');
            $service_password = input('post.service_password');
            $captcha = input('post.captcha');

            $data = array(
                'service_name' => $service_name,
                'service_password' => $service_password,
                'captcha' => $captcha,
            );

            //验证数据  BEGIN
            $rule = [
                ['service_name', 'require|min:2', '帐号为必填|帐号长度至少为2位'],
                ['service_password', 'require|min:2', '密码为必填|帐号长度至少为2位'],
                ['captcha', 'require|min:3', '验证码为必填|帐号长度至少为3位'],
            ];
            $validate = new Validate($rule);
            $validate_result = $validate->check($data);

            if (!$validate_result) {
                $this->error($validate->getError());
            }
            //验证数据  END
            if (!captcha_check(input('post.captcha'))) {
                //验证失败
                $this->error('验证码错误');
            }

            $condition['service_name'] = $service_name;
            $condition['service_password'] = md5($service_password);

            $service_info = db('service')->where($condition)->find();
            if (is_array($service_info) and !empty($service_info)) {
                //更新 member 最新信息
                $update_info = array(
                    'service_login_num' => ($service_info['service_login_num'] + 1),
                    'service_login_time' => TIMESTAMP
                );
                db('service')->where('service_id', $service_info['service_id'])->update($update_info);

                //设置 session
                session('service_id', $service_info['service_id']);
                session('service_name', $service_info['service_name']);
                session('service_group_id', $service_info['service_group_id']);
                session('service_is_super', $service_info['service_is_super']);
                session('service_pid', $service_info['service_pid']);

                return $this->redirect('home/Index/index');
            } else {
                $this->success('帐号密码错误');
            }
        } else {
            return $this->fetch();
        }
    }

    /**
     * 退出登录
     */
    public function logout()
    {
        //设置 session
        session(null);
        return $this->redirect('home/Login/index');
        exit;
    }

}


?>
