<?php

namespace App\Http\Controllers\Manage\Book;

use App\Http\Controllers\Controller;
use App\Http\Controllers\Manage\Book\Transformers\SuperiorHistoryBookTransformer;
use App\Modules\Book\Services\SuperiorHistoryBookService;
use App\Modules\Book\Services\SuperiorNewBookService;
use Illuminate\Http\Request;
use PhpOffice\PhpSpreadsheet\IOFactory;
use DB;


class SuperiorBookController extends Controller
{
    public function getSuperiorNewBook(Request $request){
        $channel = $request->input('channel','');
        $book_name = $request->input('book_name','');
        $bid=$request->input('bid','');
        $serach = [];
        if($book_name){
            $serach[] = ['book_configs.book_name','like','%'.$book_name.'%'];
        }
        if($bid){
            $serach[] = ['book_configs.bid',$bid];
        }
        $list = SuperiorNewBookService::getSuperiorList($channel,$serach);
        foreach ($list as $item){
            $list->gender=$item->pid==1?'男':'女';
        }
        return response()->success($list);
    }

    public function getSuperiorHistoryBook(Request $request){
        $channel = $request->input('channel','');
        $book_name = $request->input('book_name','');
        $bid=$request->input('bid','');
        $serach = [];
        if($book_name){
            $serach[] = ['book_configs.book_name','like','%'.$book_name.'%'];
        }
        if($bid){
            $serach[] = ['book_configs.bid','=',$bid];
        }
        $paginate = $request->input('paginate',15);
        $list = SuperiorHistoryBookService::getSuperiorList($channel,$paginate,$serach);
        return response()->pagination(new SuperiorHistoryBookTransformer(),$list);
    }

    /**
     * 导出历史优质书库
     * @param Request $request
     */
    public function exportSuperiorHistoryBook(Request $request) {
        $channel = $request->input('channel','');
        $list = SuperiorHistoryBookService::getSuperiorList($channel,'',[],false);
        $res = collectionTransform(new SuperiorHistoryBookTransformer(),$list);
        //$superior_books = json_decode(json_encode($res),true);
        //$total = count($res);
        $superiors = [];
        foreach ($res as $key=>$superior_book){
            $superiors[] = array(
                $key+1,
                $superior_book['add_time'],
                $superior_book['bid'],
                $superior_book['book_name'],
                $superior_book['gender'],
                $superior_book['register_uv_rate'],
                $superior_book['pay_uv_rate'],
                $superior_book['charge_uv_rate'],
            );
        }
        $header = ['序号','入库时间','书籍id','书名','男女频','注册/UV','付费/UV','充值/UV'];
        saveExcelData($header,$superiors,'');
    }

    public function sortSuperiorHistoryBooks(Request $request){
        if(!$request->hasFile('superior_books_sort')) {
            return response()->error('PARAM_ERROR');
        }
        $file_obj = $request->file('superior_books_sort');
        $spreadsheet = IOFactory::load($file_obj->path());
        $sheetData = $spreadsheet->getActiveSheet(0)->toArray(null, true, true, true);
        //$sequence = $sheetDataLength = count($sheetData)-1;
        \Log::info($sheetData);
        DB::beginTransaction();
        try{
            foreach ($sheetData as $key=>$value) {
                if($key==1){
                    continue;
                }
                if(!intval($value['A'])) throw new \Exception('第'.$key.'序号错误');
                SuperiorHistoryBookService::updateOne(intval($value['C']),['order_index'=>intval($value['A'])]);
               // $sequence;
            }
        }catch (\Exception $e){
            \Log::error('sort history superior books failed:'.($e->getMessage()));
            DB::rollback();
            return response()->error('UPLOAD_FAILED',$e->getMessage());
        }
        DB::commit();
        return response()->success();
    }

    public function adjustHistorySuperiorBooksSequence(Request $request) {
        $bid = $request->input('bid','');
        $sequence = $request->input('sequence','');
        if(empty($bid) && !intval($sequence)) {
            return response()->error('PARAM_EMPTY');
        }
        DB::beginTransaction();
        try{
            SuperiorHistoryBookService::adjustSequence($bid,$sequence);
        }catch (\Exception $e){
            DB::rollback();
            if($e->getCode()==10001) return ['code'=>10001,'msg'=>'序号超出范围'];
            return ['code'=>'304','msg'=>$e->getMessage()];
        }
        DB::commit();
        return response()->success();
    }

    public function modifySuperiorNewBook(Request $request) {
        $action = $request->input('action');
        $bid = $request->input('bid');
        if(!$bid){
            return response()->error('PARAM_EMPTY');
        }
        if(!in_array($action,['delete','set_top'])){
            return response()->error('PARAM_ERROR');
        }
        if($action == 'delete') {
            SuperiorNewBookService::deleteOne($bid);
        }
        if($action =='set_top') {
            SuperiorNewBookService::setTop($bid);
        }

        return response()->success();
    }
    public function modifySuperiorHistoryBook(Request $request) {
        $action = $request->input('action');
        $bid = $request->input('bid');
        if(!$bid){
            return response()->error('PARAM_EMPTY');
        }
        if(!in_array($action,['delete','set_top'])){
            return response()->error('PARAM_ERROR');
        }
        if($action == 'delete') {
            SuperiorHistoryBookService::deleteOne($bid);
            SuperiorHistoryBookService::resortSuperiorBooks();
        }
        if($action =='set_top') {
            SuperiorHistoryBookService::setTop($bid);
        }
        return response()->success();
    }
}

