<?php
/**
 * Created by PhpStorm.
 * User: tandunzhao
 * Date: 2017/12/4
 * Time: 下午1:43
 */

namespace App\Modules\Book\Services;

use App\Modules\Book\Models\SuperiorNewBooks;
use DB;

class SuperiorNewBookService
{
    public static function getSuperiorCount($pid){
        return SuperiorNewBooks::getSuperiorTotal($pid);
    }

    public static function getLastSuperiorItem($pid) {
        return SuperiorNewBooks::getLastSuperiorItem($pid);
    }

    public static function addSuperiorItem($param) {
        $count = self::getSuperiorCount($param->pid);
        $sign = ['bid'=>$param->bid];
        $data = array(
            'category_id'=>$param->category_id,
            'pid'=>$param->pid,
            'status'=>1,
            'recommend_index'=>$param->recommend_index,
            'updated_at'=>date('Y-m-d H:i:s')
        );
        //var_dump($data);
        \Log::info('superior_count:'.$count);
        $book = SuperiorNewBooks::where('bid',$param->bid)->first();
        //if(!$book) {
            if($count<20){
                SuperiorNewBooks::updateOrCreate($sign,$data);
            }else{
                $book_to_add = SuperiorNewBooks::where('bid',$param->bid)->first();
                if(!$book_to_add || ($book_to_add && $book_to_add->status==0)) {
                    $last_item = self::getLastSuperiorItem($param->pid);
                    $last_item->status = 0;
                    $last_item->save();
                }
                SuperiorNewBooks::updateOrCreate($sign,$data);
            }
        //}
    }

    public static function getSuperiorList($pid='',$search=''){
        return SuperiorNewBooks::getSuperiorList($pid,$search);
    }

    public static function getSupriorBidList(){
        $books = SuperiorNewBooks::getSuperiorList('');
        $res = [];
        foreach ($books as $book){
            $res[] = $book->bid;
        }
        return $res;
    }
    public static function deleteOne($bid){
        return SuperiorNewBooks::where('bid',$bid)->update(['status'=>0]);
    }

    public static function setTop($bid){
        $item = SuperiorNewBooks::where('bid',$bid)->first();
        $max = SuperiorNewBooks::select(DB::raw('max(order_index) as max_index'))
            ->where('pid',$item->pid)
            ->first();
        $max_index = intval($max->max_index)+1;
        $item->order_index = $max_index;
        $item->save();
    }
}