<?php

/***************************************************************\
|                                                               |
|   彩纸屋（彩纸屋编程系统）                                    |
|                                                               |
|   © 2019-2022 淮南市银泰软件科技有限公司 All rights reserved  |
|                                                               |
|   https://www.kidssteam.cn/                                   |
|                                                               |
|   QQ号：984784483                                             |
|                                                               |
\***************************************************************/

namespace app\api\controller\v1\student;

use app\common\controller\RestBaseController;
use think\Db;
use think\facade\Validate;
use app\org\model\OrgModel;
use app\user\model\UserModel;


class PublicController extends RestBaseController
{


    // 用户登录 TODO 增加最后登录信息记录,如 ip
    public function login()
    {
    	//参数验证
		$validate = new \think\Validate([
            'username' => 'require',
            'password' => 'require'
        ]);
        $validate->message([
            'username.require' => '请输入手机号,邮箱或用户名!',
            'password.require' => '请输入您的密码!'
        ]);

        $data = $this->request->param();
        if (!$validate->check($data)) {
            $this->error($validate->getError());
        }

        

    	//用户查询
        $userQuery = Db::name("user");
        $where['delete_time'] = 0;
        if (Validate::is($data['username'], 'email')) {
            $where['user_email'] = $data['username'];
            $userQuery = $userQuery->where($where);
        } else if (checkMobile($data['username'])) {
            $where['mobile'] = $data['username'];
            $userQuery = $userQuery->where($where);
        } else {
            $where['user_login'] = $data['username'];
            $userQuery = $userQuery->where($where);
        }

        $findUser = $userQuery->find();


        if (empty($findUser)) {
            $this->error("用户不存在!");
        } else {

        	// 判断用户类似 1 平台 2 学校 3 学生
        	if ($findUser['user_type'] != 3) {
                $this->error("用户不存在!");
            }


            $orgId = $findUser['org_id'];

            $OrgModel = new OrgModel();

            $OrgFind = $OrgModel->where('id',$orgId)->find();

            if(empty($OrgFind)){
                $this->error('学校异常!');
            }

            if($OrgFind['org_status'] != 1){
                $this->error('学校已停用!');
            }

            switch ($findUser['user_status']) {
                case 0:
                    $this->error('您已被拉黑!');
                case 2:
                    $this->error('账户还没有验证成功!');
            }


            if (!comparePassword($data['password'], $findUser['user_pass'])) {
                $this->error("密码不正确!");
            }
        }

        $allowedDeviceTypes = ['mobile', 'android', 'iphone', 'ipad', 'web', 'pc', 'mac'];

        if (empty($this->deviceType) && (empty($data['device_type']) || !in_array($data['device_type'], $this->allowedDeviceTypes))) {
            $this->error("请求错误,未知设备!");
        } else if(!empty($data['device_type'])) {
            $this->deviceType = $data['device_type'];
        }

        


        $token = generateUserToken($findUser['id'],$data['device_type']);

        $this->success("登录成功!", ['token' => $token]);
    }

    public function smsLogin()
    {
    	
    }

    // 用户退出
    public function logout()
    {
    	$deviceType = $this->deviceType;
    	$token = $this->token;

        $userId = $this->getUserId();

        Db::name('user_token')->where([
            'token'       => $this->token,
            'user_id'     => $userId,
            'device_type' => $this->deviceType
        ])->update(['token' => '']);

        $this->success("退出成功!");
    }





	/**
     * 获取基础信息jfour
     * @return json
     */
	public function getSiteInfo()
	{

		$data = getOption('site_info','overall');
		$data['logo'] = '/static/logo-2.png';

        $subDomain = $this->request->subDomain();
        if(isset($subDomain)){
            $data['subDomain'] = $subDomain;
            $orgFind = Db::name('org')
                    ->where([
                        'org_domain'       => $subDomain,
                    ])
                    ->find();

            if($orgFind){
                $data['logo'] = $orgFind['org_logo'];
                $data['site_name'] = $orgFind['org_name'];
            }
        }

        $this->success('ok!',$data);
	}

}
