<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2018/8/16
 * Time: 17:00
 */
namespace App\Http\Controllers\Manage\RecommendBook;

use App\Http\Controllers\Manage\BaseController;
use App\Modules\RecommendBook\Models\Recommend;
use App\Modules\RecommendBook\Models\RecomVersion;
use Illuminate\Http\Request;
use PhpOffice\PhpSpreadsheet\IOFactory;
use DB;

class RecoBookInputController extends BaseController {

    public function uploadRecommendBooks(Request $request) {
        if(!$request->has('channel')) {
            return response()->error('PARAM_EMPTY');
        }
        $channel = $request->input('channel');
        if(!in_array($channel,['1','2',1,2])){
            return response()->error('PARAM_ERROR');
        }
        $file_obj = $request->file('file');
        $spreadsheet = IOFactory::load($file_obj->path());
        $sheetData = $spreadsheet->getActiveSheet(0)->toArray(null, true, true, true);
        $arr_length = count($sheetData);
        $valid_data = array();
        $hayStack = array('loop','hot','live','recom','new_recom');
        /*var_dump($sheetData);
        die;*/
        DB::beginTransaction();
        try{
            $version = RecomVersion::create(array(
                'channel' => $channel,
                'status'=>0
            ));

            for($i=2;$i<=$arr_length;$i++) {
                if(!in_array($sheetData[$i]['A'],$hayStack)) {
                    DB::rollBack();
                    return ['code'=>300,'msg'=>'A'.($i+1).'单元格数据有误，请更正！'];
                }
                $valid_data[] = array(
                    'bid'=>$sheetData[$i]['C'],
                    'channel'=>$channel,
                    'sequence'=>$sheetData[$i]['D'],
                    'subject'=>$sheetData[$i]['A'],
                    'version_id'=>$version->id,
                    'is_show'=>0,
                    'created_at'=>date('Y-m-d H:i:s'),
                    'updated_at'=>date('Y-m-d H:i:s')
                );
            }
            Recommend::insert($valid_data);
            DB::commit();
        }catch (\Exception $e){
            DB::rollBack();
            return ['code'=>301,'msg'=>$e->getMessage()];
        }
        return response()->success();
    }

    public function getRecentRecommend(Request $request) {
        if(!$request->has('channel')) {
            return response()->error('PARAM_EMPTY');
        }
        $channel = $request->input('channel');
        if(!in_array($channel,['1','2',1,2])){
            return response()->error('PARAM_ERROR');
        }
        $recom_ver = RecomVersion::where([
            ['channel','=',$channel],
            ['status','=',0],
        ])
        ->orderBy('created_at','desc')
        ->first();
        $recommend = array();
        if($recom_ver){
            $recommend = Recommend::leftjoin('book_configs','book_configs.id','=','recommend_books.bid')
                ->select('recommend_books.bid','recommend_books.channel','recommend_books.sequence','recommend_books.subject','recommend_books.is_show','book_configs.book_name')
                ->where('recommend_books.version_id',$recom_ver->id)
                ->get();
        }
        $recommend_valid = array();
        foreach ($recommend as $key=>$value) {
            $subject = '';
            switch ($value->subject){
                case 'loop':$subject = '轮播图';break;
                case 'hot':$subject = '热门推荐';break;
                case 'live':$subject = '神书直播';break;
                case 'recom':$subject = '编辑推荐';break;
                case 'new_recom':$subject = '新书推荐';break;
                default:;
            }
            $channel= '';
            switch ($value->channel){
                case '1':$channel = '男频';break;
                case '2':$channel = '女频';break;
                default: ;
            }
            $recommend_valid[] = array(
                'book_name'=>$value->book_name,
                'subject'=>$subject,
                'channel'=>$channel,
                'bid'=>$value->bid,
                'sequence'=>$value->sequence
            );
        }
        $res = ['version'=>$recom_ver?$recom_ver->id:'','recommend'=>$recommend_valid];
        return response()->success($res);
    }

    public function setRecommend(Request $request) {
        if(!$request->has('channel')) {
            return response()->error('PARAM_EMPTY');
        }
        if(!$request->has('version')) {
            return response()->error('PARAM_EMPTY');
        }
        $channel = $request->input('channel');
        $version = $request->input('version');
        if(!in_array($channel,['1','2',1,2])){
            return response()->error('PARAM_ERROR');
        }
        $recom_version = RecomVersion::where([
            ['channel','=',$channel],
            ['id','=',$version]
        ])->first();
        if(!$recom_version){
            return response()->error('PARAM_ERROR');
        }
        DB::beginTransaction();
        try{
            $recommend_old = Recommend::where([['is_show','=',1],['channel','=',$channel]])->get();
            foreach($recommend_old as $item) {
                $item->is_show = 0;
                $item->save();
            }
            $recommends = Recommend::where('version_id',$version)->get();
            foreach ($recommends as $recommend) {
                $recommend->is_show = 1;
                $recommend->save();
            }
            $recom_version->status= 1;
            $recom_version->save();
            $unResured = RecomVersion::where([['status','=',0],['channel','=',$channel]])->get();
            foreach ($unResured as $each)
            {
                $each->status = 1;
                $each->save();
            }
            DB::commit();
        }catch (\Exception $e){
            DB::rollBack();
            return ['code'=>301,'msg'=>$e->getMessage()];
        }
        return response()->success();
    }

    public function getEnsuredList(Request $request){
        if(!$request->has('channel')) {
            return response()->error('PARAM_EMPTY');
        }
        $channel = $request->input('channel');
        if(!in_array($channel,['1','2',1,2])){
            return response()->error('PARAM_ERROR');
        }
        $recommend = Recommend::leftjoin('book_configs','book_configs.id','=','recommend_books.bid')
            ->select('recommend_books.bid','recommend_books.channel','recommend_books.sequence','recommend_books.subject','recommend_books.is_show','book_configs.book_name')
            ->where([
                ['recommend_books.is_show','=',1],
                ['recommend_books.channel','=',$channel],

            ])
            ->get();
        $recommend_valid = array();
        foreach ($recommend as $key=>$value) {
            $subject = '';
            switch ($value->subject){
                case 'loop':$subject = '轮播图';break;
                case 'hot':$subject = '热门推荐';break;
                case 'live':$subject = '神书直播';break;
                case 'recom':$subject = '编辑推荐';break;
                case 'new_recom':$subject = '新书推荐';break;
                default:;
            }
            $channel= '';
            switch ($value->channel){
                case '1':$channel = '男频';break;
                case '2':$channel = '女频';break;
                default: ;
            }
            $recommend_valid[] = array(
                'book_name'=>$value->book_name,
                'subject'=>$subject,
                'channel'=>$channel,
                'bid'=>$value->bid,
                'sequence'=>$value->sequence
            );
        }
        return response()->success($recommend_valid);
    }
}