<?php
/**
 * Created by PhpStorm.
 * User: tandunzhao
 * Date: 2018/3/23
 * Time: 上午11:10
 */

namespace App\Modules\Channel\Services;


use App\Modules\Channel\Models\CompanySpecialBook;

class CompanySpecialBookService
{


    /**
     * 查询
     * @param $bid
     * @param $company_id
     * @return mixed
     */
    public static function findBookCompany($bid, $company_id) {
        return CompanySpecialBook::where('bid', $bid)->where('company_id', $company_id)->first();
    }

    /**
     * @param $bid
     * @param $company_id
     * @return mixed
     */
    public static function addBook($bid, $company_id) {
        $obj = self::findBookCompany($bid, $company_id);
        if(!$obj) {
            $data = ['bid' => $bid, 'company_id' => $company_id];
            return CompanySpecialBook::create($data);
        }
        return $obj;
    }

    /**
     * @param $bid
     * @param $company_id
     */
    public static function rmBook($bid, $company_id) {
        $obj = self::findBookCompany($bid, $company_id);
        if($obj) {
            $obj->delete();
        }
    }

    /**
     * 删除公司对应所有书籍信息
     * @param $company_id
     */
    public static function rmCompany($company_id) {
        CompanySpecialBook::where('company_id', $company_id)->delete();
    }

    /**
     * 删除所有
     * @param $bid
     */
    public static function rmAllBook($bid) {
        CompanySpecialBook::where('bid', $bid)->delete();
    }

    /**
     * 更具书籍获取公司
     * @param $bid
     * @return mixed
     */
    public static function findCompanyToBid($bid) {
        $sqlObj = CompanySpecialBook::select('companies.id', 'companies.name', 'companies.is_important', 'companies.created_at')
            ->leftJoin('companies', 'companies.id', '=', 'company_special_books.company_id')
            ->where('company_special_books.bid', $bid);

        return $sqlObj->get();
    }

    /**
     * 根据company_id获取图书
     * @param $company_id
     * @return array
     */
    public static function getBidByCompany($company_id){
        $data= CompanySpecialBook::where('company_id', $company_id)->select('bid')->get();
        $bids=[];
        foreach ($data as $item){
            $bids[]=$item->bid;
        }
        return $bids;
    }

    /**
     * 获取内部上架书籍ID
     * @return array|null
     */
    public static function getBidByFirst() {
//        $data = CompanySpecialBook::first();
//        if($data) {
//            return self::getBidByCompany($data->company_id);
//        }
//        return null;
        $data= CompanySpecialBook::groupBy('bid')->orderBy('bid')->get();
        $bids=[];
        foreach ($data as $item){
            $bids[]=$item->bid;
        }
        return $bids;
    }
}