<?php

namespace App\Http\Controllers;

use App\Commodity;
use App\Imports\CommodityImport;
use App\Services\CommodityBarcodeService;
use App\Services\CommodityService;
use App\Services\OracleBasSkuService;
use App\Services\OwnerService;
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('denied'));  }
        $commodities=Commodity::query()->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('denied'));  }
        $ownerService=app(OwnerService::class);
        $owners = $ownerService->getIntersectPermitting();
        return view('maintenance.commodity.create',compact('owners'));
    }

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

        app('LogService')->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, [
            'sku'=>['required', 'string', 'max:50'],
            'name' => ['required', 'string', 'max:50'],
            'barcode' => ['required', 'string', 'max:50'],
            'owner_id' => ['required', 'string', 'max:50'],
        ]);
    }
    protected function validatorUpdate(array $data)
    {
        return Validator::make($data, [
            'sku'=>['required', 'string', 'max:50'],
            'name' => ['required', 'string', 'max:50'],
            'barcode' => ['required', 'string', 'max:50'],
            'owner_id' => ['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('denied'));  }
        $ownerService=app(OwnerService::class);
        $owners = $ownerService->getIntersectPermitting();
        return view('maintenance.commodity.edit',['commodity'=>$commodity,'owners'=>$owners]);
    }

    /**
     * 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();
        app('LogService')->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('/'));  }
        app('LogService')->log(__METHOD__,__FUNCTION__,$commodity->toJson(),Auth::user()['id']);
        $re=$commodity->delete();
        return ['success'=>$re];
    }
    public function import()
    {
        return view('maintenance.commodity.import');
    }

    public function isExist(Request $request)
    {
        if (app('CommodityService')->isExist($request->input()))
            return ["success"=>true];
        else return ["success"=>false];
    }

    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');
        $owner_id=$request->input('owner_id');
//        $name = '';
        $commodity=[];
        if($barcode){
            $commodity=Commodity::query()->where('owner_id',$owner_id)->whereHas('barcodes', function (Builder $query)use($barcode){
                $query->where('code',$barcode);
            })->first();
            if (!$commodity)$commodity=Commodity::query()->whereNotNull('owner_id')->whereHas('barcodes', function (Builder $query)use($barcode){
                $query->where('code',$barcode);
            })->first();
//            if($commodity&&$commodity['name']) $name=$commodity['name'];
        }
        return ['success'=>'true','commodity'=>$commodity];
    }

    public function syncWMS(Request $request){
        if(!Gate::allows('商品信息-编辑')){ return redirect(url('/'));  }
        $owner_code = $request->owner_code ?? false;
        $owner_id = $request->owner_id ?? false;
        if (!$owner_code || !$owner_id)return ['success'=>false, 'data'=>"未指定货主"];
        $this->syncOwnerCommodities($owner_id,$owner_code);
        return ['success'=>true];
    }

    //通过货主与SKU同步 WMS商品至本地 有则比对修正，无则录入
    public function syncOwnerCommodities($owner_id,$owner_code,$sku = null, $barcode = null){
        ini_set('max_execution_time', '0');
        $params = ['customerid' => $owner_code];
        if ($sku) $params['sku'] = $sku;
        if ($barcode) $params['alternate_sku1'] = $barcode;

        /** @var OracleBasSkuService $oracleBasSkuService */
        $oracleBasSkuService = app('OracleBasSkuService');
        $amount = 1000;
        $sum = $oracleBasSkuService->count($params);
        $number = ceil($sum/$amount);
        for ($i = 0;$i<$number; $i++){
            $wmsCommodities = $oracleBasSkuService->getPiece($params,($i*$amount),$amount);
            if (!$wmsCommodities)continue;
            $this->execute($owner_id,$wmsCommodities);
        }
    }

    private function execute($owner_id,array $wmsCommodities){
        if (count($wmsCommodities) < 1)return;
        $today = date('Y-m-d H:i:s');
        $map = [];
        $skus = [];
        foreach ($wmsCommodities as $index => $wmsCommodity){
            $map[$wmsCommodity->sku] = $index;
            $skus[] = $wmsCommodity->sku;
            $trimSku = rtrim($wmsCommodity->sku,"*");
            if ($trimSku != $wmsCommodity->sku){
                $skus[] = $trimSku;
                $map[$trimSku] = $index;
            }
        }
        /** @var CommodityService $commodityService */
        $commodityService = app('CommodityService');
        /** @var CommodityBarcodeService $commodityBarcodeService */
        $commodityBarcodeService = app('CommodityBarcodeService');

        $commodities = $commodityService->getOwnerCommodities(['owner_id' => $owner_id, 'sku'=>$skus]);
        $updateCommodities = [];
        $updateCommodities[] = [
            'id', 'sku', 'name', 'length', 'width', 'height', 'volumn',"pack_spec","remark"
        ];
        $barcodeMap = [];
        $commoditiesId = [];
        $barcodes = [];
        foreach ($commodities as $commodity){
            if (!isset($map[$commodity->sku]))continue;
            $wms = $wmsCommodities[$map[$commodity->sku]];
            $trimSku = rtrim($wms->sku,"*");
            if (($commodity->sku != $trimSku) || ($commodity->length != $wms->skulength)
                || ($commodity->width != $wms->skuwidth) || ($commodity->name != $wms->descr_c)
                || ($commodity->height != $wms->skuhigh) || ($commodity->volumn != $wms->cube)
                || ($commodity->pack_spec === null)){
                $updateCommodities[] = [
                    'id'=>$commodity->id,
                    'sku'=>$trimSku,
                    'name' => $wms->descr_c,
                    'length' => $wms->skulength,
                    'width' => $wms->skuwidth,
                    'height' => $wms->skuhigh,
                    'volumn' => $wms->cube,
                    "pack_spec"  => $wms->packid == 'STANDARD' ? 0 : explode("/",$wms->packid)[1],
                    'remark' => $wms->notes,
                ];
            }
            if ($wms->alternate_sku1){
                $wmsCode = rtrim($wms->alternate_sku1,"*");
                $barcodeMap[$wmsCode] = $commodity->id;
                $barcodes[] = $wmsCode;
            }
            if ($wms->alternate_sku2){
                $wmsCode = rtrim($wms->alternate_sku2,"*");
                $barcodeMap[$wmsCode] = $commodity->id;
                $barcodes[] = $wmsCode;
            }
            $commoditiesId[] = $commodity->id;
            unset($wmsCommodities[$map[$commodity->sku]]);
            if (isset($map[$wms->sku]))unset($map[$commodity->sku]);
            if (isset($map[$trimSku]))unset($map[$trimSku]);
        }
        unset($commodities,$skus);

        if (count($updateCommodities) > 1){
            $commodityService->batchUpdate($updateCommodities);
            app('LogService')->log(__METHOD__,"同步商品-批量更新",json_encode($updateCommodities));
            $commodityBarcodes = $commodityBarcodeService->get(['commodity_id'=>$commoditiesId, 'code'=>$barcodes]);

            unset($commoditiesId,$barcodes);
            foreach ($commodityBarcodes as $barcode){
                if (($barcodeMap[$barcode->code]  ?? false) && $barcodeMap[$barcode->code] == $barcode->commodity_id){
                    unset($barcodeMap[$barcode->code]);
                }
            }
            if (count($barcodeMap) > 0){
                $barcodeInsert = [];
                foreach ($barcodeMap as $key => $value){
                    $barcodeInsert[] = [
                        'commodity_id'=>$value,
                        'code' => $key,
                        'created_at' => $today
                    ];
                }
                $commodityBarcodeService->insert($barcodeInsert);
                app('LogService')->log(__METHOD__,"同步商品-录入条码",json_encode($barcodeInsert));
            }
        }

        $createCommodities = [];
        $barcodeMap = [];
        $skus = [];
        $barcodes = [];
        $barcodeIndex = [];

        foreach ($map as $sku => $index){
            if (substr($sku,-1) == "*")continue;
            $wms = $wmsCommodities[$index];
            $createCommodities[] = [
                'owner_id' => $owner_id,
                'sku' => $wms->sku,
                'name' => $wms->descr_c,
                'length' => $wms->skulength,
                'width' => $wms->skuwidth,
                'height' => $wms->skuhigh,
                'volumn' => $wms->cube,
                "pack_spec"  => $wms->packid == 'STANDARD' ? 0 : explode("/",$wms->packid)[1],
                'remark' => $wms->notes,
                "created_at" => $today,
            ];
            $barcodeMap[$wms->sku] = [];
            if ($wms->alternate_sku1){
                $code = rtrim($wms->alternate_sku1,"*");
                $barcodeMap[$wms->sku][] = $code;
                $barcodes[] = $code;
                $barcodeIndex[$code] = count($createCommodities) - 1;
            }
            if ($wms->alternate_sku2){
                $code = rtrim($wms->alternate_sku2,"*");
                $barcodeMap[$wms->sku][] = $code;
                $barcodes[] = $code;
                $barcodeIndex[$code] = count($createCommodities) - 1;
            }
            $skus[] = $wms->sku;
            unset($wmsCommodities[$index]);
        }

        if (count($barcodes) > 0){
            // ownerBarcodeSeekCommodityGet可指定第三个参数为true 默认无差别覆盖 如若指定该布尔值true代表仅覆盖SKU空值项
            $commodities = $commodityService->ownerBarcodeSeekCommodityGet(['id'=>$owner_id], $barcodes);
            $updateCommodities = [];
            $updateCommodities[] = [
                'id', 'sku', 'name', 'length', 'width', 'height', 'volumn','pack_spec','remark'
            ];
            foreach ($commodities as $commodity){
                foreach ($commodity->barcodes as $code){
                    if (isset($barcodeIndex[$code->code])){
                        $goods = $createCommodities[$barcodeIndex[$code->code]] ?? false;
                        if (!$goods)continue;
                        $updateCommodities[] = [
                            "id" => $commodity->id,
                            'sku'=>$goods['sku'],
                            'name' => $goods['name'],
                            'length' => $goods['length'],
                            'width' => $goods['width'],
                            'height' => $goods['height'],
                            'volumn' => $goods['volumn'],
                            "pack_spec" => $goods["pack_spec"],
                            'remark' => $goods["notes"],
                        ];
                        unset($createCommodities[$barcodeIndex[$code->code]]);
                        break;
                    }
                }
            }
            if (count($updateCommodities) > 0){
                $commodityService->batchUpdate($updateCommodities);
                app('LogService')->log(__METHOD__,"同步商品-批量更新",json_encode($updateCommodities));
            }
        }

        if (count($createCommodities) > 0){
            $commodityService->insert($createCommodities);
            app('LogService')->log(__METHOD__,"同步商品-录入商品",json_encode($createCommodities));
            $commodities = $commodityService->get(['owner_id'=>$owner_id , 'sku'=>$skus]);
            $barcodeInsert = [];
            foreach ($commodities as $commodity){
                foreach ($barcodeMap[$commodity->sku] as $code){
                    $barcodeInsert[] = [
                        'commodity_id'=>$commodity->id,
                        'code' => $code,
                        'created_at' => $today
                    ];
                }
            }
            $commodityBarcodeService->insert($barcodeInsert);
            app('LogService')->log(__METHOD__,"同步商品-录入条码",json_encode($barcodeInsert));
        }
    }
}
