<?php


namespace App\Models;


use App\Facade\RedisConnect;
use App\Facade\TableName;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class AccountsSource extends Model
{
    public $connection = 'write';

    public $table = 'QPAccountsDB.dbo.AccountsSource';

    public $timestamps = false;

    // 用户来源添加【不存在添加】
    public function notExistsInsert($UserID, $Source)
    {

        $AdChannel = 0;
        preg_match('/\*\d+/', $Source, $result);
        if (isset($result[0])) {
            $AdChannel = explode('*', $result[0])[1] ?? 0;
            if(strlen($AdChannel)==10){
                $AdChannel  = substr($AdChannel,-9);
            }
        }

        // 用户来源添加
        if (!self::query()->where('UserID', $UserID)->first()) {
            self::query()->insert([
                'UserID' => $UserID,
                'Source' => $Source,
                'AdChannel' => $AdChannel
            ]);
        }

        // 类别添加
        $key = 'adChannel_' . $AdChannel;
        $redisConnect = (new RedisConnect())->redis();
        if (!$redisConnect->exists($key)) {
            $count = DB::table(TableName::agent() . 'account_source_class')
                ->where('ad_channel', $AdChannel)->count();
            if (!$count) {
                DB::table(TableName::agent() . 'account_source_class')
                    ->insert([
                        'ad_channel' => $AdChannel,
                        //'Source' => $Source
                    ]);
            }
            $redisConnect->set($key, $AdChannel);
        }

        return true;
    }

    // 获取用户来源
    public function getUserSource($UserID)
    {
        $list = cache()->remember($UserID . '_getUserSource', (60 * 24 * 10), function () use ($UserID) {

            return self::query()->where('UserID', $UserID)->value('Source');

        });

        return $list;
    }

    // 获取用户来源渠道
    public function getUserAdChannel($UserID)
    {
        $list = cache()->remember($UserID . '_getUserAdChannel', (60 * 24 * 10), function () use ($UserID) {

            return self::query()->where('UserID', $UserID)->value('AdChannel');

        });

        return $list;
    }
}
