<?php

namespace App\Http\Controllers;

use App\Batch;
use App\Components\AsyncResponse;
use App\Order;
use App\OrderBin;
use App\Services\WaveService;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Http;

class WaveController extends Controller
{
    use AsyncResponse;
    public function __construct()
    {
        app()->bind("WaveService",WaveService::class);
    }

    // 主页
    public function index(Request $request){
        if(!Gate::allows('订单管理-波次-查询')){ return redirect(url('/'));  }
        $waveService = app("WaveService");
        $waves = $waveService->queryWave($request);
        $param =  $waveService->getPageParameter($request);
        $search = $waveService->getSearchCondition($request);
        foreach ($waves as $index=>$wave){
            $wave->pickerPrint = '';
            $wave->pickerPrintTime = '';
            $wave->expressPrinting = '';
            $wave->expressPrintTime = '';
            if(!is_null($wave->userdefine1)){
                $str = $wave->userdefine1;
                $index = strpos($str,'-PK');
                $wave->pickerPrint = substr($str,0,$index);
                $wave->pickerPrintTime = substr($str,$index+3);
            }
            if(!is_null($wave->userdefine2)){
                $str = $wave->userdefine2;
                if(strpos($str,'-EX')){
                    $index = strpos($str,'-EX');
                    $wave->expressPrinting = substr($str,0,$index);
                    $wave->expressPrintTime = substr($str,$index+3);
                }else if(strpos($str,'-Auto')){
                    $index = strpos($str,'-Auto');
                    $wave->expressPrinting = substr($str,0,$index);
                    $wave->expressPrintTime = substr($str,$index+5);
                }
            }
        }
        return view("order/wave/search",compact('waves','param','search'));
    }

    public function cancelPrinting(Request $request){
        if(!Gate::allows('订单管理-波次-重置打印')){ return ['success'=>false,'fail_info'=>'没有权限，请联系管理员'];  }
        $waveService = app("WaveService");
        $ids = $request->input("ids");
        /** @var WaveService $waveService */
        $meg = $waveService->cancelPrint($ids);
        if($meg['fail_info']){
            return $meg;
        }
        app('LogService')->log(__METHOD__,'重置打印标记'.__FUNCTION__,json_encode($request->toArray()),Auth::user()['id']);
        return $meg;
    }

    public function exportExcelOnParams(Request $request){
        $sql = app("WaveService")->getSql($request);
        $post = Http::post(config('go.export.url'),['type'=>'orderWave','sql'=>$sql]);
        if ($post->status() == 500){
            throw new Exception($post->header("Msg"));
        }
        return response($post,200, [
            "Content-type"=>"application/octet-stream",
            "Content-Disposition"=>"attachment; filename=波次记录-".date('ymdHis').'.xlsx',
        ]);
    }
    public function repairBatch()
    {
        $error = [];
        foreach (\request("codes") as $code){
            if (!$code)continue;
            $wave = DB::connection("oracle")->selectOne(DB::raw("select * from DOC_WAVE_HEADER where WAVENO = ?"),[$code]);
            if (!$wave){
                $error[] = $code."FLUX无波次";
                continue;
            }
            $owner = app("OwnerService")->codeGetOwner($wave->customerid);
            $obj = [
                "wms_status" => $this->wms_status($wave),
                "wms_type"=>$wave->descr,
                "created_at"=>date("Y-m-d H:i:s"),
                "wms_created_at"=>$wave->addtime,
                "updated_at"=>$wave->edittime,
                "owner_id"=>$owner->id,
            ];
            $wave = Batch::query()->where("code",$code)->first();
            if (!$wave){
                $error[] = $code."本地无波次";
                $obj["code"] = $code;
                $wave = Batch::query()->create($obj);
            }else{
                Batch::query()->where("code",$code)->update($obj);
            }
            $ordernos = array_column(DB::connection("oracle")->select(DB::raw("select orderno from DOC_WAVE_DETAILS where WAVENO = ?"),[$code]),"orderno");
            $count = Order::query()->whereIn("code",$ordernos)->count();
            if (count($ordernos)!=$count)$error[] = $code."本地订单缺失";
            Order::query()->whereIn("code",$ordernos)->update([
                "batch_id"=>$wave->id
            ]);
            Order::query()->with(["batch","bin"])->whereIn("code",$ordernos)->get()->each(function ($order){
                if (!$order->bin){
                    $bin = DB::connection("oracle")->selectOne(DB::raw("select seqno from DOC_WAVE_DETAILS where waveno = ? and orderno = ?"),[$order->batch->code,$order->code]);
                    if ($bin){
                        OrderBin::query()->create([
                            'order_id' => $order->id,
                            'number' => $bin->seqno,
                        ]);
                    }
                }
            });
        }
        $this->success($error);
    }
    /**
     * @param $wave
     * @return string
     */
    private function wms_status($wave): string
    {
        switch ($wave->wavestatus) {
            case 00:
                $wms_status = '创建';
                break;
            case 40:
                $wms_status = '部分收货';
                break;
            case 90:
                $wms_status = '取消';
                break;
            case 99:
                $wms_status = '完成';
                break;
            case 62:
                $wms_status = '部分装箱';
                break;
            default:
                $wms_status = (string)$wave->wavestatus;
        }
        return $wms_status;
    }

}
