<?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($mobile,$oauth_uuid)
    {
        $user = self::build()->where(['mobile' => $mobile])
            ->field(['nickname','is_deleted','ban_time'],true)->find();

        Db::startTrans();
        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 = UserToken::storeToken($user['uuid']);
        } else {
            //创建新用户
            $user['uuid'] = uuid();
            $user['mobile'] = $mobile;
            $user['name'] = replaceToStar($mobile);
            $user['create_time'] = timeToDate(time());
//            $user['invite_code'] = $this->get_unique_invite_code();
            $result = self::build()->insert($user);
            if ($result) {
                //创建token
                $token = UserToken::storeToken($user['uuid']);

                if(!empty($oauth_uuid)){
                    $oauth= UserOauth::build()->where(['uuid'=>$oauth_uuid])->find();
                    if(!empty($oauth)){
                        UserOauth::build()->where(['uuid'=>$oauth_uuid])->update(['user_uuid'=>$user['uuid']]);
                    }
                }
            } else {
                Db::rollback();
                return false;
            }
        }

        Db::commit();

        $users['token'] = $token;
        $users['user_info'] = self::build()
            ->where(['mobile'=>$mobile])
            ->field(['nickname','is_deleted','ban_time'],true)
            ->find();
        return $users;

    }

}