<?php

namespace App\Modules\Book\Services;

use App\Modules\Book\Models\BookConfig;
use App\Modules\Book\Models\NewBookTest;
use Redis;

class TestBookService
{
    const gu_yan = [
        '穿越重生',
        '经商种田',
        '古代虐情',
    ];

    /**
     * @param $sex 1:男 2:女
     * @param array $filter_bids
     */
    static function getTestBook($sex,$user_type='ALL')
    {
        $current_test_book = NewBookTest::where('status', 1)->select('id', 'bid', 'plan_push_user_num')->where('sex', $sex)->where('user_type',$user_type)->orderby('test_weight', 'desc')->orderby('id', 'asc')->first();
        //当前如果有测试中图书 直接返回
        if ($current_test_book) return $current_test_book;

        $to_test_book = NewBookTest::where('status', 0)->select('id', 'bid', 'plan_push_user_num')->where('sex', $sex)->where('user_type',$user_type)->orderby('test_weight', 'desc')->orderby('id', 'asc')->first();
        if ($to_test_book) {
            //当前如果无测试中图书 但有等待测试图书 修改为测试中
            $current_time = date('Y-m-d H:i:s');
            if (NewBookTest::where('id', $to_test_book->id)->update(['test_begin_time' => $current_time, 'status' => 1])) {
                return $to_test_book;
            }
        }

        return null;
    }

    static function finishTest($bid)
    {
        $book_config_res = BookConfig::where('bid', $bid)->where('test_status', 1)->update(['test_status' => 2, 'test_update_time' => date('Y-m-d H:i:s')]);
        $test_res = NewBookTest::where('bid', $bid)->where('status', 1)->update(['status' => 2, 'test_end_time' => date('Y-m-d H:i:s')]);
        return true;
    }

    static function record($test_id, $uid)
    {
        $current_time = time();
        return Redis::zadd('NewBookTestUserDetail:' . $test_id, $current_time, $uid);
    }
}