<?php

namespace App\Http\Controllers;

use App\Commodity;
use App\Imports\CommodityImport;
use Exception;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Validator;
use Maatwebsite\Excel\Facades\Excel;

class CommodityController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function index()
    {
        if(!Gate::allows('商品信息-查询')){ return redirect(url('/'));  }
        $commodities=Commodity::orderBy('id','desc')->paginate(50);
        return view('maintenance.commodity.index',['commodities'=>$commodities]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return Response
     */
    public function create()
    {
        if(!Gate::allows('商品信息-录入')){ return redirect(url('/'));  }
        return view('maintenance.commodity.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param Request $request
     * @return Response
     */
    public function store(Request $request)
    {
        if(!Gate::allows('商品信息-录入')){ return redirect(url('/'));  }
        $this->validatorCreate($request->all())->validate();
        $commodity=new Commodity($request->all());
        $commodity->save();
        $commodity->newBarcode($request->input('barcode'));

        $this->log(__METHOD__,__FUNCTION__,json_encode($request->toArray()),Auth::user()['id']);
        return redirect('maintenance/commodity/create')->with('successTip',"成功录入商品信息：“{$request->input('name')}”");
    }
    protected function validatorCreate(array $data)
    {
        return Validator::make($data, [
            'name' => ['required', 'string', 'max:50'],
//            'barcode' => ['required', 'string', 'max:50', 'unique:commodities'],
        ]);
    }
    protected function validatorUpdate(array $data)
    {
        return Validator::make($data, [
            'name' => ['required', 'string', 'max:50'],
            'barcode' => ['required', 'string', 'max:50'],
        ]);
    }
    /**
     * Display the specified resource.
     *
     * @param Commodity $commodity
     * @return Response
     */
    public function show(Commodity $commodity)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param Commodity $commodity
     * @return Response
     */
    public function edit(Commodity $commodity)
    {
        if(!Gate::allows('商品信息-编辑')){ return redirect(url('/'));  }
        return view('maintenance.commodity.edit',['commodity'=>$commodity]);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param Request $request
     * @param Commodity $commodity
     * @return Response
     */
    public function update(Request $request, Commodity $commodity)
    {
        if(!Gate::allows('商品信息-编辑')){ return redirect(url('/'));  }
        $this->validatorUpdate($request->all())->validate();
        $commodity->fill($request->all());
        $commodity->update();
        $this->log(__METHOD__,__FUNCTION__,json_encode($request->toArray()),Auth::user()['id']);
        return redirect('maintenance/commodity/')->with('successTip',"成功修改商品信息：“{$commodity['name']}”！");
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param Commodity $commodity
     * @return array|Response
     * @throws Exception
     */
    public function destroy(Commodity $commodity)
    {
        if(!Gate::allows('商品信息-删除')){ return redirect(url('/'));  }
        $this->log(__METHOD__,__FUNCTION__,$commodity->toJson(),Auth::user()['id']);
        $re=$commodity->delete();
        return ['success'=>$re];
    }
    public function import()
    {
        return view('maintenance.commodity.import');
    }

    public function importExcel(Request $request)
    {
        $isOverride = $request->input('isOverride');
        try{
            ini_set('max_execution_time',2500);
            ini_set('memory_limit','1526M');
            $extension=$request->file()['file']->getClientOriginalExtension();
            $extension[0] = strtoupper($extension[0]);
            Excel::import(new CommodityImport($isOverride), $request->file()['file']->path(),null,$extension);
            return '<h1 class="text-success">导入成功</h1>';
        }catch (Exception $e){
            if(strstr($e->getMessage(),'No ReaderType')){return '<h1 class="text-danger">没有上传写权限，请修改php.ini 对应的upload_tmp_dir 目录或其权限</h1>'.$e->getMessage();}
            if(strstr($e->getMessage(),'SQLSTATE')){return '<h1 class="text-danger">数据库插入错误，数据不支持，可能有重复或异常字符</h1>'.$e->getMessage();}
            if(strstr(strtolower($e->getMessage()),'sku')){return '<h1 class="text-danger">请在第一行将 商品编码 字段名改成“SKU”，不支持中文字段名，并且必须有该列</h1>'.$e->getMessage();}
            if(strstr(strtolower($e->getMessage()),'name')){return '<h1 class="text-danger">请在第一行将 商品名称 字段名改成“name”，不支持中文字段名，并且必须有该列</h1>'.$e->getMessage();}
            if(strstr(strtolower($e->getMessage()),'barcode')){return '<h1 class="text-danger">请在第一行将 商品条码 字段名改成“barcode”，不支持中文字段名，并且必须有该列</h1>'.$e->getMessage();}
            if(strstr(strtolower($e->getMessage()),'owner')){return '<h1 class="text-danger">请在第一行将 货主 字段名改成“owner”，不支持中文字段名，并且必须有该列</h1>'.$e->getMessage();}
            return '<h1 class="text-danger">失败</h1>'.$e->getMessage();
        }
    }


    public function apiGetCommodityByBarcode(Request $request)
    {
        $barcode=$request->input('barcode');
        $name = '';
        if($barcode){
            $commodity=Commodity::whereHas('barcodes', function (Builder $query)use($barcode){
                $query->where('code',$barcode);
            })->first();
            if($commodity&&$commodity['name']) $name=$commodity['name'];
        }
        return ['success'=>'true','name'=>$name];
    }
}
