<?php
/**
 * Created by PhpStorm.
 * User: z-yang
 * Date: 2020/12/15
 * Time: 15:20
 */

namespace App\Modules\User\Services;

use App\Modules\User\Models\UserBookCombinationConfig;

class UserBookCombinationConfigService
{
    public static function getLongBookFromShortBook($uid,$short_bid)
    {
        return UserBookCombinationConfig::where('uid',(int)$uid)->where('short_bid',(int)$short_bid)->where('is_enable',1)->first();
    }

    public static function getShortBookFromLongBook($uid,$long_bid)
    {
        return UserBookCombinationConfig::where('uid',(int)$uid)->where('long_bid',(int)$long_bid)->where('is_enable',1)->first();
    }

    public static function getShortBookFromLongBid($uid,$long_bid)
    {
        $info =  UserBookCombinationConfig::where('uid',(int)$uid)->where('long_bid',(int)$long_bid)->where('is_enable',1)->first();
        if($info) return $info->short_bid;
        return 0;
    }

    public static function getAllLongBids($uid){
        return UserBookCombinationConfig::where('uid',$uid)->select('long_bid')->get()->pluck('long_bid')->all();
    }

    public static function create($uid,$short_bid,$long_bid,$is_enable = 1){
        return UserBookCombinationConfig::create(compact('uid','short_bid','long_bid','is_enable'));
    }


    public static function selectLongBook($uid)
    {
        $bid_pool = redisEnv('SHORT_PUSH_LANG_BID');
        if(!$bid_pool) return '';
        $bid_pool_array = explode(',',$bid_pool);
        $read_record = ReadRecordService::getSimpleReadRecord($uid);
        if(!$read_record) return '';
        $result = array_values(array_diff($bid_pool_array,$read_record));
        $has_select_long_bid = self::getAllLongBids($uid);
        if($has_select_long_bid){
            $result = array_values(array_diff($result,$has_select_long_bid));
        }
        if($result){
            return $result[array_rand($result)];
        }
        return '';
    }

    public static function selectAndSave($uid,$short_bid)
    {
        $result = self::getLongBookFromShortBook($uid,$short_bid);
        if($result) {
            return $result->long_bid;
        }
        $result = self::selectLongBook($uid);
        if($result) {
            self::create($uid,$short_bid,$result);
            return $result;
        }
        return 0;
    }
}