<?php

namespace App\Http\Controllers;

use App\Depository;
use App\Owner;
use App\Services\common\BatchUpdateService;
use App\Services\StoreService;
use App\Store;
use App\StoreItem;
use App\Warehouse;
use App\WMSReflectReceive;
use Carbon\Carbon;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Contracts\View\Factory;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Routing\Redirector;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Validator;
use Illuminate\View\View;
use App\Http\Controllers\api\thirdPart\flux\StoreController as FStoreController;

class StoreController extends Controller
{
    public function storage(Request $request)
    {
        if(!Gate::allows('入库管理-入库-查询')){ return redirect(url('/'));  }
        /** @var StoreService $storeService */
        $paginateParams=$request->input();
        $storeService=app(StoreService::class);
        $stores=$storeService->paginate($request->input());
        $warehouses=Warehouse::query()->get();
        $owners=app("OwnerService")->getIntersectPermitting();
        return view('store.inStorage.index',compact('stores','warehouses','owners','paginateParams'));
    }
    /**
     * Display a listing of the resource.
     *
     * @return Application|Factory|Response|View
     */
    public function index()
    {
        if(!Gate::allows('入库管理-快速入库-查询')){ return redirect(url('/'));  }
        $stores=Store::query()->with(['warehouse','owner'])
            ->where('is_fast_stored','快速入库')
            ->orderBy('id','DESC')->paginate(50);
        return view('store.fast.index',['stores'=>$stores]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return Application|Factory|Response|View
     */
    public function create()
    {
        if(!Gate::allows('入库管理-快速入库-录入')){ return redirect(url('/'));  }
        return view('store.fast.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param Request $request
     * @return RedirectResponse|Response|Redirector
     */
    public function store(Request $request)
    {
        if(!Gate::allows('入库管理-快速入库-录入')){ return redirect(url('/'));  }
        $this->validator($request);
        if ($request->test)$result = $this->quickStorage($request->input('asn_code'),$request->input('quality') == '正品' ? 'ZP' : 'CC',$request->input('depository_code'));
        else $result = $this->quickStorage_temp($request->input('asn_code'),$request->input('quality'),$request->input('depository_code'));
        $response = redirect('store/fast/create');
        if ($result['success'])return redirect('store/fast/create')->with('successTip',$result['data']);
        return $response->with('successError',$result['data']);
    }

    public function quickStorage_temp($asn,$quality,$depository_code){
        $WMSReflectReceive=WMSReflectReceive::with('skus')->where('ASNNO',$asn)->first();
        if (!$WMSReflectReceive)return ['success'=>false, 'data'=>"ASN编号不存在！"];
        $warehouse=Warehouse::query()->where('code',$WMSReflectReceive->WAREHOUSEID)->first();
        if (!$warehouse&&$WMSReflectReceive->WAREHOUSEID){
            $warehouse=new Warehouse([
                'name'=>$WMSReflectReceive->WAREHOUSEID,
                'code'=>$WMSReflectReceive->WAREHOUSEID
            ]);
            $warehouse->save();
        }
        $owner=Owner::query()->where('code',$WMSReflectReceive->CUSTOMERID)->first();
        if (!$owner&&$WMSReflectReceive->CUSTOMERID){
            $owner=new Owner([
                'name'=>$WMSReflectReceive->CUSTOMERID,
                'code'=>$WMSReflectReceive->CUSTOMERID
            ]);
            $owner->save();
        }
        $store=Store::query()->where('asn_code',$WMSReflectReceive->ASNNO)->first();
        if(!$store){
            $store=new Store([
                'asn_code'=>$WMSReflectReceive->ASNNO,
                'warehouse_id'=>$warehouse->id,
                'owner_id'=>$owner->id,
                'stored_method'=>'快速入库',
                'status'=>'未入库',
                'remark'=>$WMSReflectReceive->NOTES,
                'is_fast_stored'=>'快速入库',
            ]);
            $store->save();

            $customDepository=(function()use($depository_code){
                $customDepository=Depository::query()->where('code',$depository_code)->first();
                if($depository_code){
                    if (!$customDepository){
                        $depository=new Depository([
                            'name'=>$depository_code,
                            'code'=>$depository_code
                        ]);
                        $depository->save();
                    }
                }
                return $customDepository;
            })();

            if ($WMSReflectReceive->skus){
                foreach ($WMSReflectReceive->skus as $sku){
                    $depository=(function()use($sku,$customDepository){
                        if($customDepository)return $customDepository;
                        $depository=Depository::query()->where('code',$sku->LOTATT05)->first();
                        if (!$depository){
                            if (!$sku->LOTATT05)return $depository;
                            $depository=new Depository([
                                'name'=>$sku->LOTATT05,
                                'code'=>$sku->LOTATT05
                            ]);
                            $depository->save();
                        }
                        return $depository;
                    })();
                    $storeItem=new StoreItem([
                        'store_id'=>$store->id,
                        'asn_line_code'=>$sku->ASNLINENO,
                        'name'=>$sku->SKUDESCRC,
                        'sku'=>$sku->SKU,
                        'barcode'=>$sku->ALTERNATE_SKU1,
                        'quality'=>$quality,
                        'status'=>'未入库',
                    ]);
                    if ($depository)$storeItem->depository_id=$depository->id;
                    $storeItem->save();
                }
            }
        }
        /** @var Store $store */
        $store=Store::with('storeItems')->where('asn_code',$asn)->first();
        $storeApi=new FStoreController();
        $result=$storeApi->accomplishToWMS($store,[
            'quality'=>$quality,
            'depository_code'=>$depository_code,
            'follow_code'=>$store['id'],
        ]);
        if ($result){
            $store->status='已入库';
            $store->save();
            if ($store->storeItems){
                $store->storeItems->each(function ($storeItem)use($quality){
                    $storeItem->status='已入库';
                    $storeItem->quality=$quality;
                    $storeItem->save();
                });
            }
            return ['success'=>true, 'data'=>"成功！"];
        }
        return ['success'=>false, 'data'=>"失败！请检查错误日志"];
    }

    public function quickStorage($asnno,$quality,$depository_code,$isVerification = true)
    {
        $task = Store::query()->where("asn_code",$asnno)
            ->where(function ($query){
                /** @var Builder $query */
                $query->where("stored_method","快速入库")
                    ->orWhere('is_fast_stored','快速入库');
            })
            ->where("status","已入库")->first();
        if ($task)return ['success'=>false, 'data'=>"已被快速入库"];
        $db = DB::connection('oracle');
        $query = DB::raw("SELECT * FROM DOC_ASN_HEADER WHERE ASNNO = ?");
        $asn = $db->selectOne($query,[$asnno]);
        if (!$asn) return ['success'=>false, 'data'=>"单据号不存在"];
        if ($asn->asnstatus != '00')return ['success'=>false, 'data'=>'单据号状态非创建订单'];
        if ($isVerification){
            if (array_search($asn->customerid,array_values(config('stores.owners'))) === false)return ['success'=>false, 'data'=>"不允许该货主快速入库"];
            if (array_search($asn->asntype,array_values(config('stores.types'))) === false)return ['success'=>false, 'data'=>"该单据类型不允许被入库"];
        }
        $query = DB::raw("SELECT b.ALTERNATE_SKU1,h.WAREHOUSEID,h.asnno,d.ASNLINENO,d.SKUDESCRC,h.CUSTOMERID,d.SKU,d.PACKID,d.RECEIVEDQTY_EACH,d.EXPECTEDQTY_EACH,d.LOTATT01,d.LOTATT02,d.lotatt04,".
            "d.lotatt05,d.lotatt08,d.USERDEFINE1,d.USERDEFINE2,d.USERDEFINE3,d.USERDEFINE4,d.USERDEFINE5,d.RECEIVINGLOCATION FROM DOC_ASN_DETAILS d ".
            " LEFT JOIN BAS_SKU b ON d.CUSTOMERID = b.CUSTOMERID AND d.SKU = b.SKU INNER JOIN DOC_ASN_HEADER h ON d.ASNNO = h.ASNNO WHERE h.ASNNO = ?");
        $details = $db->select($query,[$asnno]);

        $username = config('database.connections.oracle.username');
        $password = config('database.connections.oracle.password');
        $host = config('database.connections.oracle.host');
        $service_name = config('database.connections.oracle.service_name');
        $conn = oci_connect($username, $password, $host . '/' . $service_name,"utf8");
        $sql_sp = "begin SPASN_Receiving_Process(:IN_Warehouse, :In_Process_Action, :In_ASNNo_C, :In_ASNLineNo_C, :In_FMTraceID_C, :In_New_TraceID_C, :In_ProductStatus," .
            ":In_ProductStatus_Descr, :In_HoldRejectCode_C, :In_HoldRejectReason_C, :In_PONo_C, :In_CustomerID, :In_SKU, :In_ReceivedQty, :In_RejectedQty,:In_UOM, :In_PackID," .
            " :In_ContainerID, :In_LotAtt01_C, :In_LotAtt02_C, :In_LotAtt03_C, :In_LotAtt04_C, :In_LotAtt05_C, :In_LotAtt06_C," .
            ":In_LotAtt07_C, :In_LotAtt08_C, :In_LotAtt09_C, :In_LotAtt10_C, :In_LotAtt11_C, :In_LotAtt12_C," .
            ":In_TotalCubic, :In_TotalGrossWeight, :In_TotalNetWeight, :In_TotalPrice, :In_UserDefine1, :In_UserDefine2,:In_UserDefine3, :In_UserDefine4, :In_UserDefine5, :In_FMLocation," .
            ":In_TOLocation_C,:In_QC_Type_C, :In_PlanToLoc_C,:In_ReceivingTime, :In_LPN, :In_Operator, :IN_RCVModule, :IN_RCVStation, :In_Language, :In_UserID, :OUT_Return_Code); end;";
        $items = [];
        $toDay = Carbon::now()->toDateTimeString();
        $depositories = [];
        $traceId = rand(100,999);
        foreach ($details as $detail) {
            $result = $this->executeSP($detail,$asnno,$depository_code,$db,$quality,$conn,$sql_sp,$traceId);
            if (substr($result, 0, 3) != '000') {
                oci_close($conn);
                app('LogService')->log(__METHOD__,"快速入库-FLUX收货失败","ASNNO：".$asnno."；ERROR：".$result);
                return ['success' => false, 'data' => $detail->asnlineno.'收货失败,错误代码：'.$result];
            }
            if (!isset($depositories[$detail->lotatt05]) && $detail->lotatt05){
                $depository = app('DepositoryService')->firstOrCreate(["code"=>$detail->lotatt05],["code"=>$detail->lotatt05,"name"=>$detail->lotatt05]);
                $depositories[$detail->lotatt05] = $depository->id;
            }
            $item = [
                "asn_line_code" => $detail->asnlineno,
                "name" => $detail->skudescrc,
                "sku" => $detail->sku,
                "barcode" => $detail->alternate_sku1,
                "amount" => $detail->expectedqty_each,
                "quality" => $quality == 'ZP' ? '正品' : '残次',
                "status" => "已入库",
                "created_at" => $toDay
            ];
            if (isset($depositories[$detail->lotatt05]))$item["depository_id"] = $depositories[$detail->lotatt05];
            $items[] = $item;
        }
        oci_close($conn);
        $warehouse = app('WarehouseService')->firstOrCreate(["code"=>$asn->warehouseid],["code"=>$asn->warehouseid,"name"=>$asn->warehouseid]);
        $owner = app('OwnerService')->firstOrCreate(['code'=>$asn->customerid],['code'=>$asn->customerid,"name"=>$asn->customerid]);
        $store = Store::query()->with("storeItems")->where("asn_code",$asnno)->first();
        if (!$store){
            $store = app('StoreService')->create([
                'asn_code'=>$asnno,
                'warehouse_id'=>$warehouse->id,
                'owner_id'=>$owner->id,
                'stored_method'=>'快速入库',
                'status'=>'已入库',
                'remark'=>$asn->notes,
            ]);
            app('LogService')->log(__METHOD__,"快速入库",json_encode($store));
            foreach ($items as &$item){
                $item["store_id"] = $store->id;
            }
            app('StoreItemService')->insert($items);
            app('LogService')->log(__METHOD__,"快速录入子项",json_encode($items));
        }else{
            $store->update([
                'asn_code'=>$asnno,
                'warehouse_id'=>$warehouse->id,
                'owner_id'=>$owner->id,
                'stored_method'=>'快速入库',
                'status'=>'已入库',
                'remark'=>$asn->notes,
            ]);
            $insertItem = [];
            if ($store->storeItems){
                $updateItem = [["id","asn_line_code","name","sku","barcode","amount","quality","status"]];
                $existItem = [];
                $store->storeItems->each(function ($item)use(&$existItem){
                    $existItem[$item->asn_line_code] = $item->id;
                });
                foreach ($items as $item){
                    if (isset($existItem[$item['asn_line_code']])){
                        $item["id"] = $existItem[$item['asn_line_code']];
                        $updateItem[] = $item;
                    }else {
                        $item["store_id"] = $store->id;
                        $insertItem[] = $item;
                    }
                }
                if (count($updateItem) > 1) app(BatchUpdateService::class)->batchUpdate("store_items",$updateItem);
            }else{
                foreach ($items as $item){
                    $item["store_id"] = $store->id;
                    $insertItem[] = $item;
                }
            }
            if ($insertItem)app('StoreItemService')->insert($items);
        }
        return ['success'=>true,"data"=>"已成功将“".$asnno."”入库"];
    }

    private function executeSP($detail, $asnno, $depository_code, $db, $quality, $conn, $sql_sp,$traceId){
        $IN_Warehouse = $detail->warehouseid ?? '';
        $In_Process_Action = '3';
        $In_ASNNo_C = $detail->asnno ?? '';
        $In_ASNLineNo_C = $detail->asnlineno ?? '';
        $In_FMTraceID_C = '';
        $In_New_TraceID_C = $traceId;
        $In_ProductStatus = '00';
        $In_ProductStatus_Descr = '正常';
        $In_HoldRejectCode_C = 'OK';
        $In_HoldRejectReason_C = '正常';
        $In_PONo_C = '';
        $In_CustomerID = $detail->customerid ?? '';
        $In_SKU = $detail->sku ?? '';
        $In_ReceivedQty = (string)((int)$detail->expectedqty_each - (int)$detail->receivedqty_each) ?? '';
        $In_RejectedQty = '';
        $In_UOM = 'EA';
        $In_PackID = $detail->packid ?? '';
        $In_ContainerID = '';
        $In_LotAtt01_C = $detail->lotatt01 ?? '';
        $In_LotAtt02_C = $detail->lotatt02 ?? '';
        $In_LotAtt03_C = '';
        $In_LotAtt04_C = $detail->lotatt04 ?? '';
        $In_LotAtt05_C = $detail->lotatt05 ?? '';
        $In_LotAtt06_C = '';
        $In_LotAtt07_C = '';
        $In_LotAtt08_C = $detail->lotatt08 ?? '';
        $In_LotAtt09_C = '';
        $In_LotAtt10_C = '';
        $In_LotAtt11_C = '';
        $In_LotAtt12_C = '';
        $In_TotalCubic = '0.00';
        $In_TotalGrossWeight = '0.00';
        $In_TotalNetWeight = '0.00';
        $In_TotalPrice = '0.00';
        $In_UserDefine1 = $detail->userdefine1 ?? '';
        $In_UserDefine2 = $detail->userdefine2 ?? '';
        $In_UserDefine3 = $detail->userdefine3 ?? '';
        $In_UserDefine4 = $detail->userdefine4 ?? '';
        $In_UserDefine5 = $detail->userdefine5 ?? '';
        $In_FMLocation = 'STAGE' . $detail->warehouseid;
        $In_TOLocation_C = 'STAGE' . $detail->warehouseid;
        $In_QC_Type_C = 'OK';
        $In_PlanToLoc_C = '';
        $In_ReceivingTime = '';
        $In_LPN = '*';
        $In_Operator = 'WCS';
        $IN_RCVModule = '';
        $IN_RCVStation = '';
        $In_Language = 'cn';
        $In_UserID = 'WCS';
        $result = '';
        if ($depository_code && (strtoupper($depository_code) != strtoupper($detail->receivinglocation))){
            $query = DB::raw("UPDATE DOC_ASN_DETAILS SET RECEIVINGLOCATION = ?  WHERE ASNNO = ? AND ASNLINENO = ?");
            $db->update($query,[$depository_code,$detail->asnno,$detail->asnlineno]);
            $db->commit();
            app('LogService')->log(__METHOD__,"快速入库-修改FULX属性仓","ASNNO：".$asnno."；原仓：".$detail->receivinglocation."；修改为：".$depository_code);
        }
        if ($quality && ($quality != $detail->lotatt08)){
            $query = DB::raw("UPDATE DOC_ASN_DETAILS SET LOTATT08 = ?  WHERE ASNNO = ? AND ASNLINENO = ?");
            $db->update($query,[$quality,$detail->asnno,$detail->asnlineno]);
            $db->commit();
            app('LogService')->log(__METHOD__,"快速入库-修改FULX质量状态","ASNNO：".$asnno."；原质量：".$detail->lotatt08."；修改为：".$quality);
            $In_LotAtt08_C = $quality;
        }
        $stmt = oci_parse($conn, $sql_sp);
        oci_bind_by_name($stmt, ':IN_Warehouse', $IN_Warehouse);
        oci_bind_by_name($stmt, ':In_Process_Action', $In_Process_Action);
        oci_bind_by_name($stmt, ':In_ASNNo_C', $In_ASNNo_C);
        oci_bind_by_name($stmt, ':In_ASNLineNo_C', $In_ASNLineNo_C);
        oci_bind_by_name($stmt, ':In_FMTraceID_C', $In_FMTraceID_C);
        oci_bind_by_name($stmt, ':In_New_TraceID_C', $In_New_TraceID_C);
        oci_bind_by_name($stmt, ':In_ProductStatus', $In_ProductStatus);
        oci_bind_by_name($stmt, ':In_ProductStatus_Descr', $In_ProductStatus_Descr);
        oci_bind_by_name($stmt, ':In_HoldRejectCode_C', $In_HoldRejectCode_C);
        oci_bind_by_name($stmt, ':In_HoldRejectReason_C', $In_HoldRejectReason_C);
        oci_bind_by_name($stmt, ':In_PONo_C', $In_PONo_C);
        oci_bind_by_name($stmt, ':In_CustomerID', $In_CustomerID);
        oci_bind_by_name($stmt, ':In_SKU', $In_SKU);
        oci_bind_by_name($stmt, ':In_ReceivedQty', $In_ReceivedQty);
        oci_bind_by_name($stmt, ':In_RejectedQty', $In_RejectedQty);
        oci_bind_by_name($stmt, ':In_UOM', $In_UOM);
        oci_bind_by_name($stmt, ':In_PackID', $In_PackID);
        oci_bind_by_name($stmt, ':In_ContainerID', $In_ContainerID);
        oci_bind_by_name($stmt, ':In_LotAtt01_C', $In_LotAtt01_C);
        oci_bind_by_name($stmt, ':In_LotAtt02_C', $In_LotAtt02_C);
        oci_bind_by_name($stmt, ':In_LotAtt03_C', $In_LotAtt03_C);
        oci_bind_by_name($stmt, ':In_LotAtt04_C', $In_LotAtt04_C);
        oci_bind_by_name($stmt, ':In_LotAtt05_C', $In_LotAtt05_C);
        oci_bind_by_name($stmt, ':In_LotAtt06_C', $In_LotAtt06_C);
        oci_bind_by_name($stmt, ':In_LotAtt07_C', $In_LotAtt07_C);
        oci_bind_by_name($stmt, ':In_LotAtt08_C', $In_LotAtt08_C);
        oci_bind_by_name($stmt, ':In_LotAtt09_C', $In_LotAtt09_C);
        oci_bind_by_name($stmt, ':In_LotAtt10_C', $In_LotAtt10_C);
        oci_bind_by_name($stmt, ':In_LotAtt11_C', $In_LotAtt11_C);
        oci_bind_by_name($stmt, ':In_LotAtt12_C', $In_LotAtt12_C);
        oci_bind_by_name($stmt, ':In_TotalCubic', $In_TotalCubic);
        oci_bind_by_name($stmt, ':In_TotalGrossWeight', $In_TotalGrossWeight);
        oci_bind_by_name($stmt, ':In_TotalNetWeight', $In_TotalNetWeight);
        oci_bind_by_name($stmt, ':In_TotalPrice', $In_TotalPrice);
        oci_bind_by_name($stmt, ':In_UserDefine1', $In_UserDefine1);
        oci_bind_by_name($stmt, ':In_UserDefine2', $In_UserDefine2);
        oci_bind_by_name($stmt, ':In_UserDefine3', $In_UserDefine3);
        oci_bind_by_name($stmt, ':In_UserDefine4', $In_UserDefine4);
        oci_bind_by_name($stmt, ':In_UserDefine5', $In_UserDefine5);
        oci_bind_by_name($stmt, ':In_FMLocation', $In_FMLocation);
        oci_bind_by_name($stmt, ':In_TOLocation_C', $In_TOLocation_C);
        oci_bind_by_name($stmt, ':In_QC_Type_C', $In_QC_Type_C);
        oci_bind_by_name($stmt, ':In_PlanToLoc_C', $In_PlanToLoc_C);
        oci_bind_by_name($stmt, ':In_ReceivingTime', $In_ReceivingTime);
        oci_bind_by_name($stmt, ':In_LPN', $In_LPN);
        oci_bind_by_name($stmt, ':In_Operator', $In_Operator);
        oci_bind_by_name($stmt, ':IN_RCVModule', $IN_RCVModule);
        oci_bind_by_name($stmt, ':IN_RCVStation', $IN_RCVStation);
        oci_bind_by_name($stmt, ':In_Language', $In_Language);
        oci_bind_by_name($stmt, ':In_UserID', $In_UserID);
        oci_bind_by_name($stmt, ':OUT_Return_Code', $result,300);
        oci_execute($stmt);
        return $result;
    }


    public function validator(Request $request){
        $validator=Validator::make($request->input(),[
            'asn_code'=>['required'],
            'quality'=>['required'],
            'depository_code'=>['nullable','string'],
        ],[
            'required'=>':attribute 为必填项',
            'unique'=>':attribute 已存在',
        ],[
            'asn_code'=>'ASN编号',
            'quality'=>'货物类型'
        ])->validate();
        return $validator;
    }

    /**
     * 缓存架入库表单
     */
    public function cacheRackStorage()
    {
        return \view("store.inStorage.cacheRackStorage");
    }
}
