<?php
/**
 * Created by PhpStorm.
 * User: tandunzhao
 * Date: 2017/12/4
 * Time: 上午11:49
 */

namespace App\Modules\Book\Services;


use App\Modules\Book\Models\BookCategory;
use App\Modules\Book\Models\Book;
use App\Modules\Book\Models\BookTags;
use DB;

class BookTagsService
{
    public static function getBookTags($bid){
        $res = [];
        $tags = BookTags::getBookTags($bid);
        foreach ($tags as $tag){
            $res[] = $tag->tags;
        }
        return $res;
    }
    public static function getSearchBooks($tags,$offset=0,$limit='') {
        $tags = explode(',',str_replace('，',',',$tags));
        //return BookTags::getSearchBooks($tags);
        //$sql1 = "select `book_configs`.`bid`, `book_configs`.`roles`, `book_configs`.`force_subscribe_chapter_seq`, `book_configs`.`cp_source`, `book_configs`.`vip_seq`, `book_configs`.`price`, `book_configs`.`cover`, `book_configs`.`book_name`, `book_configs`.`copyright`, `book_configs`.`charge_type`, `book_configs`.`is_on_shelf`, `books`.`author`, `books`.`intro`, `books`.`category_name`, `category_id`, `status`, `chapter_count`, `book_configs`.`click_count`, `first_cid`, `last_cid`, `books`.`size`, `last_chapter`, `books`.`keyword`, `book_configs`.`recommend_index`, `book_configs`.`is_show_index_content`, `book_configs`.`product_id`, `book_categories`.`channel_name`, `books`.`last_cid`, `books`.`last_chapter`, `book_configs`.`product_id`, `book_configs`.`copyright_limit_data`, `books`.`updated_at` as `last_update_time`, `book_configs`.`promotion_domain`, `books`.`name` as `old_name`, `book_configs`.`recommend_cid`, `book_configs`.`is_high_quality` from `book_configs` inner join `books` on `book_configs`.`bid` =`books`.`id` left join `book_categories` on `books`.`category_id` = `book_categories`.`id` where";
        $sql = "SELECT bid FROM book_tags bt1 
 where bt1.status=1 and bt1.tags='".$tags[0]."'";
        $arr_length = count($tags);
        if($arr_length >1){
            for($i=1;$i<$arr_length;$i++){
                $sql .=" and exists (select id from book_tags bt".($i+1)." where bt".($i+1).".tags='".$tags[$i]."' and bt".($i+1).".bid=bt1.bid and bt".($i+1).".status=1)";
            }
        }
        //$sql .=')';
        if($limit && $offset){
            $sql .= ' limit '.$offset.','.$limit;
        }
        $res = DB::select($sql);
        $finnal = [];
        foreach ($res as $item) {
            $finnal[] = $item->bid;
        }
        //\Log::info('finnal:'.json_encode($finnal));
        return $finnal;
    }
}