<?php

namespace App\Http\Controllers\Api\thirdPart\flux;


use App\Commodity;
use App\OracleBasSKU;
use App\OracleDOCASNDetail;
use App\OracleDOCMovementDetail;
use App\OracleDOCMovementHeader;
use App\OracleDOCOrderDetail;
use App\Http\Controllers\Controller;
use App\Owner;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class ProcessController extends Controller
{
    public function getProcessContent(Request $request){
        $wms_code=$request->input('wms_code');
        if (!$wms_code)return ['error'=>'提交的单据号为空'];
        try{
            $docASNs=OracleDOCASNDetail::where("ASNNo",$wms_code)->get();   //入库单
        }
        catch (\Exception $e){
            return ['error'=>'数据库连接失败！'];
        }
        if (count($docASNs)>0){
            $owner=Owner::where("code",$docASNs[0]->customerid)->first();
            if (!$owner)$owner=$this->storeOwner($docASNs[0]->customerid);
            if (!$owner)return ['error'=>'找到了入库单，但未查询到货主代码！'];
            /*$basSKUs=['owner_code'=>[],'sku'=>[]];
            $commodities=[];
            $i=0;
            $docAsnSKUs=array_column($docASNs->toArray(),'sku');
            $docAsnOwnerCodes=array_column($docASNs->toArray(),'customerid');
            $commoditiesTem=Commodity::with(['barcodes','owner'=>function($query)use($docAsnOwnerCodes){
                return $query->whereIn('code',$docAsnOwnerCodes);
            }])->whereIn('sku',$docAsnSKUs)->get();
            $commoditiesData=[];
            foreach ($commoditiesTem as $commodityTem){
                $commoditiesData[$commodityTem->sku."_".$commodityTem->owner_code]=$commodityTem;
            }
            foreach ($docASNs as $docASN){
                $commodity=isset($commoditiesData[$docASN->sku."_".$docASN->customerid])?$commoditiesData[$docASN->sku."_".$docASN->customerid]:null;
                if (!$commodity){
                    array_push($basSKUs['owner_code'],$docASN->customerid);
                    array_push($basSKUs['sku'],$docASN->sku);
                    $i++;
                    continue;
                }
                $commodity->amount=$docASN->expectedqty;
                array_push($commodities,$commodity->toArray());
                unset($docASNs[$i]);
                $i++;
            }
            unset($docAsnOwnerCodes,$docAsnSKUs,$commoditiesTem,$commoditiesData);
            if (count($basSKUs['sku'])>0 && count($basSKUs['owner_code'])>0){
                $this->storeCommodity($basSKUs);
                $docAsnSKUs=array_column($docASNs->toArray(),'sku');
                $docAsnOwnerCodes=array_column($docASNs->toArray(),'customerid');
                $commoditiesTem=Commodity::with(['barcodes','owner'=>function($query)use($docAsnOwnerCodes){
                    return $query->whereIn('code',$docAsnOwnerCodes);
                }])->whereIn('sku',$docAsnSKUs)->get();
                $commoditiesData=[];
                foreach ($commoditiesTem as $commodityTem){
                    $commoditiesData[$commodityTem->sku."_".$commodityTem->owner_code]=$commodityTem;
                }
                foreach ($docASNs as $docASN){
                    $commodity=$commoditiesData[$docASN->sku."_".$docASN->customerid];
                    if (!$commodity){
                        continue;
                    }
                    $commodity->amount=$docASN->expectedqty;
                    array_push($commodities,$commodity->toArray());
                }
            }*/
            $commodities=$this->resetData($docASNs,"sku","customerid","expectedqty","asnlineno");
            $processContent=[
                'wms_code'=>$wms_code,
                'owner_name'=>$owner->name,
                'owner_id'=>$owner->id,
                'commodities'=>$commodities,
                'bill_type'=>'入库单',
            ];
            return json_encode($processContent);
        }
        $docOrders=OracleDOCOrderDetail::where("OrderNo",$wms_code)->get();//出库单
        if (count($docOrders)>0){
            $owners=Owner::withTrashed()->where("code",$docOrders[0]->customerid)->get();
            if ($owners->isEmpty()){
                $owner=$this->storeOwner($docOrders[0]->customerid);
            }else{
                $owner=$owners->first();
            }
            if (!$owner)return ['error'=>'找到了入库单，但未查询到货主代码！'];
            $commodities=$this->resetData($docOrders,"sku","customerid","qtyordered",'orderlineno');
            $processContent=[
                'wms_code'=>$wms_code,
                'owner_name'=>$owner->name,
                'owner_id'=>$owner->id,
                'commodities'=>$commodities,
                'bill_type'=>'出库单',
            ];
            return json_encode($processContent);
        }
        $docMovementDetails=OracleDOCMovementDetail::where("MDOCNO",$wms_code)->get();//移库单
        if (count($docMovementDetails)>0){
            $docMovementHeaders=OracleDOCMovementHeader::select('CustomerID')->where('MDOCNO',$wms_code)->get();
            if (count($docMovementHeaders)<1)return ['error'=>'找到了移库单，但未查询移库单表头！'];
            $owner=Owner::where("code",$docMovementHeaders[0]->customerid)->first();
            if (!$owner)$owner=$this->storeOwner($docMovementHeaders[0]->customerid);
            if (!$owner)return ['error'=>'找到了入库单，但未查询到货主代码！'];
            $commodities=$this->resetData($docMovementDetails,"sku","customerid","toqty","mdoclineno",$docMovementHeaders);
            /*$commodities=[];
            foreach ($docMovementDetails as $docMovementDetail){
                $commodity=Commodity::where('sku',$docMovementDetail->sku)->first();
                if (!$commodity)$commodity = $this->storeCommodity($owner->code,$docMovementDetail->sku);
                if (!$commodity)continue;
                array_push($commodities,['id'=>$commodity->id,'name'=>$commodity->name,
                    'barcodes'=>$commodity->barcodes,'sku'=>$commodity->sku,'amount'=>$docMovementDetail->toqty]);
            }*/
            $processContent=[
                'wms_code'=>$wms_code,
                'owner_name'=>$owner->name,
                'owner_id'=>$owner->id,
                'commodities'=>$commodities,
                'bill_type'=>'移库单',
            ];
            return json_encode($processContent);
        }
        return ['error'=>'未查到对应单据号'];
    }


    //重组商品数据
    private function resetData($doc,$skuColumn,$customeridColumn,$amountColumn,$lineNoColumn,$docHeader=null){
        //处理重组数据
        $docs=['owner_code'=>[],'sku'=>[]];
        $commodities=[];
        $commodity_ids=[];
        $i=0;
        $docSKUs=array_column($doc->toArray(),'sku');
        $docOwnerCodes=array_column($docHeader?$docHeader->toArray():$doc->toArray(),'customerid');
        $commoditiesTem=Commodity::with(['barcodes','owner'=>function($query)use($docOwnerCodes){
            return $query->whereIn('code',$docOwnerCodes);
        }])->whereIn('sku',$docSKUs)->get();
        $commoditiesData=[];
        foreach ($commoditiesTem as $commodityTem){
            $commoditiesData[$commodityTem->sku."_".$commodityTem->owner_code]=$commodityTem;
        }
        foreach ($doc as $docOne){
            $customerid=$docHeader?$docHeader[0][$customeridColumn]:$docOne[$customeridColumn];
            $commodity=isset($commoditiesData[$docOne[$skuColumn]."_".$customerid])
                ?$commoditiesData[$docOne[$skuColumn]."_".$customerid]:null;
            if (!$commodity){
                array_push($docs['owner_code'],$docHeader?$docHeader[0][$customeridColumn]:$docOne[$customeridColumn]);
                array_push($docs['sku'],$docOne[$skuColumn]);
                $i++;
                continue;
            }
            $commodity->amount=$docOne[$amountColumn];
            $commodity->lineNo=$docOne[$lineNoColumn];
            if (isset($commodity_ids[$commodity->id]))
                $commodities[$commodity_ids[$commodity->id]]['amount'] += $commodity->amount;
            else{
                array_push($commodities,$commodity->toArray());
                $commodity_ids[$commodity->id] = count($commodities)-1;
            }
            unset($doc[$i]);
            $i++;
        }
        unset($docSKUs,$docOwnerCodes,$commoditiesTem,$commoditiesData,$customerid);
        if (count($docs['sku'])>0 && count($docs['owner_code'])>0){
            $this->storeCommodity($docs);
            $docSKUs=array_column($doc->toArray(),'sku');
            $docOwnerCodes=array_column($docHeader?$docHeader->toArray():$doc->toArray(),'customerid');
            $commoditiesTem=Commodity::with(['barcodes','owner'=>function($query)use($docOwnerCodes){
                return $query->whereIn('code',$docOwnerCodes);
            }])->whereIn('sku',$docSKUs)->get();
            $commoditiesData=[];
            foreach ($commoditiesTem as $commodityTem){
                $commoditiesData[$commodityTem->sku."_".$commodityTem->owner_code]=$commodityTem;
            }
            foreach ($doc as $docOne){
                $customerid=$docHeader?$docHeader[0][$customeridColumn]:$docOne[$customeridColumn];
                $commodity=isset($commoditiesData[$docOne[$skuColumn]."_".$customerid])
                    ?$commoditiesData[$docOne[$skuColumn]."_".$customerid]:null;
                if (!$commodity)continue;
                $commodity->amount=$docOne[$amountColumn];
                $commodity->lineNo=$docOne[$lineNoColumn];
                if (isset($commodity_ids[$commodity->id]))
                    $commodities[$commodity_ids[$commodity->id]]['amount'] += $commodity->amount;
                else{
                    array_push($commodities,$commodity->toArray());
                    $commodity_ids[$commodity->id] = count($commodities)-1;
                }
            }
        }
        return $commodities;
    }

    private function storeCommodity($basSKUs){
        $oracleBasSkus=OracleBasSKU::whereIn("CustomerID",$basSKUs['owner_code'])->whereIn("SKU",$basSKUs['sku'])->get();
        if (count($oracleBasSkus)<1)return;
        $commoditiesData=[];
        $commoditiesTem=["sku"=>[],"owner_id"=>[]];
        $commodityBarCodeData=[];
        $commodityBarCodeTem=[];
        $owners_code=array_column($oracleBasSkus->toArray(),'customerid');
        $ownersTem=Owner::withTrashed()->whereIn('code',$owners_code)->get();
        $owners=array_column($ownersTem->toArray(),'id','code');
        for($i=0;$i<count($oracleBasSkus);$i++){
            if (!$owners[$oracleBasSkus[$i]->customerid])$owners[$oracleBasSkus[$i]->customerid]=$this->storeOwner($oracleBasSkus[$i]->customerid);
            array_push($commoditiesData,["owner_id"=>$owners[$oracleBasSkus[$i]->customerid],"name"=>$oracleBasSkus[$i]->descr_c,"sku"=>$oracleBasSkus[$i]->sku,"created_at"=>Carbon::now()]);
            array_push($commoditiesTem['sku'],$oracleBasSkus[$i]->sku);
            array_push($commoditiesTem['owner_id'],$owners[$oracleBasSkus[$i]->customerid]);
            $commodityBarCodeData[$oracleBasSkus[$i]->sku."_".$owners[$oracleBasSkus[$i]->customerid]]=["code"=>$oracleBasSkus[$i]->alternate_sku1,"commodity_id"=>'','created_at'=>Carbon::now()];
        }
        DB::table('commodities')->insert($commoditiesData);
        $this->log(__METHOD__, 'FLUX二次加工单接口录入商品__' . __FUNCTION__, json_encode($commoditiesData), Auth::user()['id']);
        $commodities=Commodity::whereIn('sku',$commoditiesTem['sku'])->whereIn('owner_id',$commoditiesTem['owner_id'])->get();
        foreach ($commodities as $commodity){
            $commodityBarCodeData[$commodity->sku."_".$commodity->owner_id]['commodity_id']=$commodity->id;
        }
        foreach ($commodityBarCodeData as $key=>$value){
            array_push($commodityBarCodeTem,$value);
        }
        DB::table('commodity_barcodes')->insert($commodityBarCodeTem);
        $this->log(__METHOD__, 'FLUX二次加工单接口录入商品条码__' . __FUNCTION__, json_encode($commodityBarCodeTem), Auth::user()['id']);
    }


    private function storeOwner($code){
        $owner=new Owner([
            "name"=>$code,
            "code"=>$code
        ]);
        $owner->save();
        $this->log(__METHOD__, 'FLUX二次加工单接口录入货主__' . __FUNCTION__, json_encode($owner), Auth::user()['id']);
        return $owner;
    }
}
