<?php


namespace App\Models;


use App\Util;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class GamePhoneVerityCode extends Model
{
    public function addCode($UserID, $Code, $PhoneNum, $Ip)
    {

        $now = date('Y-m-d H:i:s');
        $query = DB::connection('write')->table('QPTreasureDB.dbo.GamePhoneVerityCode')
            ->where('PhoneNum',$PhoneNum)
            ->first();


        $pack=Util::getPackageByURL();
        ///// 如果发送过验证码，直接返回，更新手机号和过期时间
        if ($query) {
            DB::connection('write')->table('QPTreasureDB.dbo.GamePhoneVerityCode')
                ->where('PhoneNum',$PhoneNum)
                ->update(['UserID'=>$UserID,'Code'=>$query->Code,'CreateDate'=>$now,'Channel'=>$pack['channel']]);

        }else{
            $data = [
                'UserID' => $UserID,
                'PhoneNum' => $PhoneNum,
                'Code' => $Code,
                'CreateDate' => $now,
                'Ip' => $Ip,
                'Channel'=>$pack['channel']
            ];
            DB::connection('write')->table('QPTreasureDB.dbo.GamePhoneVerityCode')
                ->updateOrInsert(['PhoneNum'=>"$PhoneNum"],$data);
        }

        return true;
    }

    // 验证 一个手机号对应的IP，只能发10次OTP，超过10次，则这个IP，无论使用任何的手机号，在今日无法再次发送OTP，24点过后次日立即解除限制
    public function verifyIp($Ip)
    {
        $count = DB::connection('write')->table('QPTreasureDB.dbo.GamePhoneVerityCode')
            ->whereDate('CreateDate', date('Y-m-d'))
            ->where('Ip', $Ip)
            ->count();
        if ($count > 10) {
            return true;
        }
        return false;
    }

    //

    /**
     * 验证验证码 flag =》true 验证间隔日期  false=》验证验证码
     * @param $phone
     * @param string $code
     * @param bool $flag
     * @return int
     */
    public static function verifyCode($phone, $code = '', $flag = false)
    {

        if ($flag) {
            $first = DB::connection('write')->table('QPTreasureDB.dbo.GamePhoneVerityCode')
                ->where('PhoneNum', $phone)
                ->orderByDesc('CreateDate')
                ->first();

            if ($first) {
                // 60 秒后发送一次验证码
                if (time() - strtotime($first->CreateDate) < 60) {
                    return 2;
                }
            }

            return 0;

        } else {
            $first = DB::connection('write')->table('QPTreasureDB.dbo.GamePhoneVerityCode')
                ->where('PhoneNum', $phone)
                ->where('Code', $code)
                ->orderByDesc('CreateDate')
                ->first();

            // 验证码或手机号错误
            if (!$first) {
                return 1;
            }

            // 验证码过期
            if (time() - strtotime($first->CreateDate) > 600) {
                return 3;
            }

            return $first->Code;
        }
    }
}
