<?php

namespace App\Modules\Book\Models;

use Illuminate\Database\Eloquent\Model;

class BookTags extends Model
{
    protected $table = 'book_tags';
    protected $fillable = ['id','bid','tags','tags_id','status'];

    public static function getBookTags($bid) {
        return self::where([['bid','=',$bid],['status','=',1]])->get();
    }

    public static function addBookTag($bid,$tags) {
        $pre_book_bags = BookTags::where('bid',$bid)->get();
        foreach ($pre_book_bags as $pre_book_bag){
            $pre_book_bag->status = 0;
            $pre_book_bag->save();
        }
        $tags_arr =  explode(',',str_replace('，',',',$tags));
        foreach ($tags_arr as $item) {
            $tags_obj = Tags::where('tags',$item)->first();
            if(!$tags_obj){
                $tags_obj = Tags::create(['tags'=>$item]);
            }
            BookTags::updateOrCreate(['tags'=>$item,'bid'=>$bid],['tags_id'=>$tags_obj->id,'status'=>1]);
        }
    }

    public static function getSearchBooks(Array $tags) {
        return self::leftJoin('books','books.id','=','book_tags.bid')
            ->select('book_tags.bid','books.name')
            ->where('book_tags.status',1)
            ->whereIN('book_tags.tags',$tags)
            ->get();
    }

    public static function deleteTagBook($bid,$tags){
        $book_tags = BookTags::where([['bid','=',$bid],['tags','=',$tags]])->get();
        foreach ($book_tags as $book_tag){
            $book_tag->status = 0;
            $book_tag->save();
        }
        return $book_tags;
    }
}
