<?php
/**
 * Created by PhpStorm.
 * User: tandunzhao
 * Date: 2018/1/19
 * Time: 上午10:01
 */

namespace App\Modules\Book\Services;


use App\Modules\Book\Models\ChapterImage;
use DB;
use GuzzleHttp\Client;

class ChapterImageService
{

    public static function save($bid, $cid, $cid_sequence, $sequence, $image_url) {
        $data = [
            'bid' => $bid,
            'cid' => $cid,
            'cid_sequence' => $cid_sequence,
            'sequence' => $sequence,
            'image_url' => $image_url,
        ];
        $client = new Client();
        $imageInfo = $client->request('GET', $image_url.'?x-oss-process=image/info')->getBody()->getContents();
        $imageInfo = json_decode($imageInfo,true);
        $data['file_size'] = isset($imageInfo['FileSize']['value'])?$imageInfo['FileSize']['value']:'';
        $data['image_height'] = isset($imageInfo['ImageHeight']['value'])?$imageInfo['ImageHeight']['value']:'';
        $data['image_width'] = isset($imageInfo['ImageWidth']['value'])?$imageInfo['ImageWidth']['value']:'';
        ChapterImage::create($data);
    }

    public static function delete($bid, $cid = '') {
        ChapterImage::deleteChapterImage($bid, $cid);
    }

    /**
     * @param $bid
     * @param string $cids [1,2,3,4,5]
     * @return mixed
     */
    public static function getChapterImage($bid, $cids = '') {
        return ChapterImage::getChapterImage($bid, $cids);
    }

    /**
     * 获取当前图书生成到第几章
     */
    public static function getChapterImgCount($bid){
        $sql = "SELECT COUNT(DISTINCT cid) as `count` FROM chapter_images WHERE bid = ".$bid;
        $res = DB::select($sql);
        return $res[0]->count;
    }

    public static function updateChapterImage($id,Array $param){
        return ChapterImage::where('id',$id)->update($param);
    }
}