<?php
/**
 * Created by PhpStorm.
 * User: tandunzhao
 * Date: 2018/1/19
 * Time: 下午3:15
 */

namespace App\Http\Controllers\Channel\Book;

use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use Hashids;
use Illuminate\Http\Request;
use App\Http\Controllers\Channel\BaseController;
use App\Http\Controllers\Channel\Book\Transformers\ChapterImageTransformer;
use App\Libs\ChapterToImage;
use App\Modules\Book\Services\ChapterImageService;
use App\Modules\Book\Services\ChapterService;
use Psr\Http\Message\ResponseInterface;

class ChapterImageController extends BaseController
{

    /**
     * @apiDefine promotion 推广
     */

    /**
     * @apiVersion 1.0.0
     * @apiDescription 获取章节图片列表
     * @api {GET} api/book/fiveChapterImage 获取章节图片列表
     * @apiGroup promotion
     * @apiName api/book/fiveChapterImage
     * @apiParam   {String}  bid  图书ID
     * @apiSuccessExample {json} Success-Response:
     *
     *     {
     *         "code": 0,
     *         "msg": "",
     *         "data":[
     *              {
     *               }
     *          ]
     *     }
     */
    public function getTopFiveChapter(Request $request) {
        $bid = $request->has('bid') ? $request->input('bid') : '';
        if (empty($bid)) return response()->error("PARAM_EMPTY");
        $bid = Hashids::decode($bid)[0];
        $chapter_count = ChapterImageService::getChapterImgCount($bid);
        $chapters = ChapterService::getTopFiveChapter($bid);
        $result = ChapterImageService::getChapterImage($bid);
        if(empty($result) || sizeof($result) == 0 || $chapter_count < sizeof($chapters)) {
            ChapterToImage::createChapterImage($bid,'',$chapters);

            $result = ChapterImageService::getChapterImage($bid);
        }

        $resultAA = array();
        if($result && sizeof($result) > 0) {
            foreach ($result as $rr) {
                $cid = $rr['cid'];
                $resultAA[$cid][] = ['image_url'=>$rr['image_url'],'height'=>$rr['image_height'],'id'=>$rr['id']];
            }
        }
        $resultBB = array();
        $client = new Client();
        if($resultAA && sizeof($resultAA) > 0) {
            foreach ($resultAA as $key => $value) {
                //$resultBB[] = $value;
                $temp = [];
                foreach ($value as $img){
                    $height = $img['height'];
                    //$imageInfo = @file_get_contents($img.'?x-oss-process=image/info');
                    if(!$height){
                        preg_match("/(\w+:\/\/)([^\/:]+)([^?]+)?([\/s\/S]*)/",$img['image_url'],$matches);
                        $imageInfo = $client->request('GET', env('OSS_INTERNAL_DOMAIN').$matches[3].'?x-oss-process=image/info')->getBody()->getContents();

                        //\Log::info($imageInfo);
                        if($imageInfo){
                            $imageInfo = json_decode($imageInfo,true);
                            if(isset($imageInfo['ImageHeight']['value'])){
                                $height = $imageInfo['ImageHeight']['value'];
                                $param = array(
                                    'file_size'=>$imageInfo['FileSize']['value'],
                                    'image_height'=>$imageInfo['ImageHeight']['value'],
                                    'image_width'=>$imageInfo['ImageWidth']['value']
                                );
                                ChapterImageService::updateChapterImage($img['id'],$param);
                            }
                        }
                        if(!$height){
                            $height = 300;
                        }
                    }

                    $temp[] = ['image_url'=>$img['image_url'],'height'=>$height];
                }
                $resultBB[] = $temp;
            }
        }

//        return response()->collection(new ChapterImageTransformer(), $result);
        return response()->success($resultBB);
    }
}