<?php

namespace App\Modules\Book\Services;

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

class NewBookTestService
{
    /**
     * 待测试
     */
    const wait_test = 0;
    /**
     * 测试中
     */
    const testing = 1;
    /**
     * 测试完毕
     */
    const complete = 2;
    /**
     * 手动停止
     */
    const stop = 3;

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

    public static function updateTestBook($bid, $status, $plan_push_user_num = 30000)
    {
        $book_config = BookConfig::where('bid', $bid)->first();
        $origin_book = Book::find($bid);
        if ($origin_book) {
            $category = BookCategory::where('id', $origin_book->category_id)->first();
            $sex = $category->channel_name == '男频' ? '1' : '2';
            $user_type = 'ALL';//in_array($category->category_name, self::gu_yan) ? 'GUYAN' :'ALL';
            return NewBookTest::create([
                'bid' => $bid,
                'category' => $category->category_name,
                'user_type' => $user_type,
                'book_name' => $book_config->book_name,
                'sex' => $sex,
                'status' => 0,
                'test_weight' => '0',
                'plan_push_user_num' => $plan_push_user_num,
            ]);
        } else {
            return '';
        }
    }

    public static function newBookTests(array $wheres, $is_page = true)
    {
        $obj = NewBookTest::orderBy('updated_at', 'desc');
        if ($wheres['status'] != '') {
            $obj->where('new_book_tests.status', $wheres['status']);
        }
        if ($wheres['bid']) {
            $obj->where('new_book_tests.bid', $wheres['bid']);
        }
        if ($wheres['sex']) {
            $obj->where('new_book_tests.sex', $wheres['sex']);
        }
        if ($is_page) {
            return $obj->paginate();
        } else {
            return $obj->get();
        }
    }

    /**
     * 重新开始新书测试
     */
    public static function reNewBookTest(int $bid)
    {
        Redis::hDel('SmartPushBookUserNum', $bid);
    }

    public static function updateNewBookTest(int $bid, array $columns)
    {
        $columns['updated_at'] = now();
        return NewBookTest::where('bid', $bid)->update($columns);
    }
}
