<?php
/**
 * Created by PhpStorm.
 * User: ChiaHsiang
 * Date: 2018/8/1
 * Time: 20:39
 */

namespace app\api\model;

use think\Db;
use think\Model;

class User extends Model
{
    protected $table = 'user';
    protected $dateFormat = false;

    public static function build() {
        return new self();
    }


    public function saveInfo($requestData, $uuid)
    {
        return self::build()->where(['uuid' => $uuid])->update($requestData);
    }

    /**
     * @author: Airon
     * @time:   2018年5月
     * description 验证码登录
     * @param $mobile
     * @param $oauth_uuid
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function login($requestData)
    {
        $user = self::build()->where(['mobile' => $requestData['mobile'],'password' => md5(md5($requestData['password']))])
            ->field(['password'],true)->find();

        if ($user) {
//            if ($user['is_banned']) {
//                ResponseDirect('当前账号已被禁用',403);
//            }
//            if(!empty($oauth_uuid)){
//                $oauth= UserOauth::build()->where(['uuid'=>$oauth_uuid])->find();
//                if(!empty($oauth)){
//                    UserOauth::build()->where(['user_uuid'=>$user['uuid']])->update(['user_uuid'=>""]);
//                    UserOauth::build()->where(['uuid'=>$oauth_uuid])->update(['user_uuid'=>$user['uuid']]);
//
//                }
//            }
            $token = Token::storeToken($user['uuid']);
        }else{
            return false;
        }

        $users['token'] = $token;
        $users['user_info'] = self::build()
            ->where(['mobile' => $requestData['mobile'],'password' => md5(md5($requestData['password']))])
            ->field(['name'],false)
            ->find();
        return $users;

    }

    /**
     * @author:
     * @time:   2019年3月
     * description 注册
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function register($request)
    {
        Db::startTrans();
        //创建新用户
        $user['uuid'] = uuid();
        $user['mobile'] = $request['mobile'];
        $user['name'] = replaceToStar($request['mobile']);
        $user['create_time'] = timeToDate(time());
        $user['password'] = md5(md5($request['password']));
        self::build()->insert($user);
        $result = $this->login(['mobile' => $request['mobile'],'password' => $request['password']]);
        if (!$result) {
            Db::rollback();
            return false;
        }

        Db::commit();
        return $result;
    }



}