<?php

namespace App\Http\Controllers;


use App\Imports\PaperBoxesImport;
use App\Owner;
use App\PaperBox;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Validator;
use Maatwebsite\Excel\Facades\Excel;
class PaperBoxController extends Controller
{
    /**
     * Display a listing of the resource.
     * @param  \Illuminate\Http\Request
     * @return \Illuminate\Http\Response
     */
    public function indexModel()
    {
        if(!Gate::allows('纸箱-查询')){ return redirect(url('/'));  }
        $paperBoxes=PaperBox::with('owners')->orderBy('id','DESC')->paginate(50);
        return view('maintenance.paperBox.index',['paperBoxes'=>$paperBoxes]);

    }
    public function indexOwner()
    {
        if(!Gate::allows('纸箱-查询')){ return redirect(url('/'));  }
        $paperBoxes_owner=Owner::with('paperBoxes')->orderBy('id','DESC')->paginate(50);
        return view('maintenance.paperBox.indexOwner',['paperBoxes_owner'=>$paperBoxes_owner]);

    }

    /**
     * Show the form for creating a new resource.
     *
     * @return
     */
    public function create()
    {
        if(!Gate::allows('纸箱-录入')){ return redirect(url('/'));  }
        $owners=Owner::get();
        return view('maintenance.paperBox.create',['owners'=>$owners]);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        if(!Gate::allows('纸箱-录入')){ return redirect(url('/'));  }
        $id=false;
        $this->validator($request,$id)->validate();
        $length=$request->input('length');
        $width=$request->input('width');
        $height=$request->input('height');
        $max=($length>=($width>=$height?$width:$height)?$length:($width>=$height?$width:$height));
        if ($max==$length){
            $centre=$width>=$height?$width:$height;
            $min=$width<$height?$width:$height;
        }elseif ($max==$width){
            $centre=$length>=$height?$length:$height;
            $min=$length<$height?$length:$height;
        }else{
            $centre=$width>=$length?$width:$length;
            $min=$width<$length?$width:$length;
        }
        $paperBox=new PaperBox([
            'model'=>$request->input('model'),
            'length'=>$max,
            'width'=>$centre,
            'height'=>$min,
        ]);
        $paperBox->save();
        $owner_id=$request->input('owner_id');
        if ($owner_id){
            $paperBox->owners()->sync($owner_id);
        }
        app('LogService')->log(__METHOD__,__FUNCTION__,json_encode($request->toArray()),Auth::user()['id']);
        return redirect('maintenance/paperBox/index/model')->with('successTip','新纸箱'.$request->input('model').'录入成功');
    }


    /**
     * Show the form for editing the specified resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        if(!Gate::allows('纸箱-编辑')){ return redirect(url('/'));  }
        $paperBox=PaperBox::with('owners')->find($id);
        $owners=Owner::get();
        return view('maintenance/paperBox/edit',['paperBox'=>$paperBox,'owners'=>$owners]);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request,$id)
    {
        if(!Gate::allows('纸箱-编辑')){ return redirect(url('/'));  }
        $this->validator($request,$id)->validate();
        $length=$request->input('length');
        $width=$request->input('width');
        $height=$request->input('height');
        $max=($length>=($width>=$height?$width:$height)?$length:($width>=$height?$width:$height));
        if ($max==$length){
            $centre=$width>=$height?$width:$height;
            $min=$width<$height?$width:$height;
        }elseif ($max==$width){
            $centre=$length>=$height?$length:$height;
            $min=$length<$height?$length:$height;
        }else{
            $centre=$width>=$length?$width:$length;
            $min=$width<$length?$width:$length;
        }
        $paperBox=PaperBox::find($id);
        $paperBox->model=$request->input('model');
        $paperBox->length=$max;
        $paperBox->width=$centre;
        $paperBox->height=$min;
        $paperBox->save();
        $owner_id=$request->input('owner_id');
        if ($owner_id){
            $paperBox->owners()->sync($owner_id);
        }
        app('LogService')->log(__METHOD__,__FUNCTION__,json_encode($request->toArray()),Auth::user()['id']);
        return redirect('maintenance/paperBox/index/model')->with('successTip','纸箱'.$request->input('model').'信息更新成功');
    }

    /**
     * Remove the specified resource from storage.
     *
     */
    public function destroy($id)
    {
        if(!Gate::allows('纸箱-删除')){ return redirect(url('/'));  }
        $paperBox=PaperBox::find($id);
        app('LogService')->log(__METHOD__,__FUNCTION__,json_encode($paperBox),Auth::user()['id']);
        if ($paperBox->delete()){
            $paperBox->owners()->detach();
            app('LogService')->log(__METHOD__,__FUNCTION__,json_encode($paperBox),Auth::user()['id']);
            return ['success'=>true];
        }else{
            return ['success'=>false];
        }
    }

    public function import(Request $request){
        if(!Gate::allows('纸箱-录入')){ return redirect(url('/'));  }
        $fileSuffix=$request->file('file')->getClientOriginalExtension();
        if ($fileSuffix=='xlsx'||$fileSuffix=='xlsm'||$fileSuffix=='xltx'||$fileSuffix=='xltm'||$fileSuffix=='xls'||$fileSuffix=='xlt'||$fileSuffix=='ods'||$fileSuffix=='ots'||$fileSuffix=='slk'
            ||$fileSuffix=='xml'||$fileSuffix=='gnumeric'||$fileSuffix=='htm'||$fileSuffix=='html'||$fileSuffix=='csv'||$fileSuffix=='tsv'){
            $isOverride = $request->input('isOverride');
            ini_set('max_execution_time',2100);
            ini_set('memory_limit','512M');
            $extension=$request->file()['file']->getClientOriginalExtension();
            $extension[0] = strtoupper($extension[0]);
            Excel::import(new PaperBoxesImport($isOverride),$request->file()['file']->path(),null,$extension);
            if (Cache::has('error')){
                return '<h1 class="text-danger">导入Excel失败<br><p style="color: red">'.Cache::pull('error').'</p></h1>';
            }else{
                $exception=Cache::get('exception');
                $a='';
                for ($i=0;$i<count($exception);$i++){$a.=implode(',',$exception[$i]).'&#10'; };
                app('LogService')->log(__METHOD__,__FUNCTION__,json_encode($request->toArray()),Auth::user()['id']);
                return '<h1 class="text-danger">导入Excel成功<br><textarea style="width: 50%;height: 50%">'.$a.'</textarea></h1>';
            }
        }else{
            return '<h1 class="text-danger">失败<br><p style="color: red">不支持该文件类型</p></h1>';
        }
    }

    public function validator(Request $request,$id){
        if ($id){$model=$id;}
        $validator=Validator::make($request->input(),[
            'model'=>['max:50','required',isset($model)?"unique:paper_boxes,model,$model":'unique:paper_boxes,model'],
            'length'=>'required|min:0|numeric|max:999999',
            'width'=>'required|min:0|numeric|max:999999',
            'height'=>'required|min:0|numeric|max:999999',
        ],[
            'required'=>':attribute 不应为空',
            'min'=>':attribute 不得为0或为负',
            'numeric'=>':attribute 必须为数字',
            'unique'=>':attribute 已存在',
            'max'=>':attribute 输入值过大',
        ],[
            'model'=>'型号',
            'length'=>'长（cm）',
            'width'=>'宽（cm）',
            'height'=>'高（cm）',
        ]);
        return $validator;
    }
}
