<?php

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


use App\Commodity;
use App\OracleBasCode;
use App\OracleBasSKU;
use App\OracleDOCASNDetail;
use App\OracleDOCMovementDetail;
use App\OracleDOCMovementHeader;
use App\OracleDOCOrderDetail;
use App\Http\Controllers\Controller;
use App\Owner;
use App\ProcessesContent;
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{
            $basCodes = OracleBasCode::query()->select('code','codename_c')
                ->whereIn('codename_c',['部分收货','订单创建'])->where('codeid','ASN_STS')->get();
            $basCodeMap = [];
            foreach ($basCodes as $basCode){
                $basCodeMap[$basCode->code] = $basCode->codename_c;
            }
            $docASNs=OracleDOCASNDetail::query()->where("ASNNo",$wms_code)->get();   //入库单
        }catch (\Exception $e){
            return ['error'=>'数据库连接失败'];
        }
        if (count($docASNs)>0){
            $owner=Owner::query()->where("code",$docASNs[0]->customerid)->first();
            if (!$owner)$owner=$this->storeOwner($docASNs[0]->customerid);
            if (!$owner)return ['error'=>'找到了入库单，但未查询到货主代码！'];
            $docASNs[0]->load('oracleDocAsnHeader');
            $asnstatus = $basCodeMap[$docASNs[0]['oracleDocAsnHeader'] ? $docASNs[0]['oracleDocAsnHeader']['asnstatus'] : null] ?? null;
            $commodities=$this->resetData($docASNs,"sku","customerid","receivedqty","asnlineno");
            $commodities = $this->resetCommodityAmount($wms_code,$request->is_finished_product,$commodities);
            $processContent=[
                'wms_code'=>$wms_code,
                'owner_name'=>$owner->name,
                'owner_id'=>$owner->id,
                'commodities'=>$commodities,
                'bill_type'=>'入库单',
                'asnstatus' => $asnstatus,
            ];
            return json_encode($processContent);
        }
        $docOrders=OracleDOCOrderDetail::query()->where("OrderNo",$wms_code)->get();//出库单
        if (count($docOrders)>0){
            $owners=Owner::query()->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","qtyshipped",'orderlineno');
            $commodities = $this->resetCommodityAmount($wms_code,$request->is_finished_product,$commodities);
            $processContent=[
                'wms_code'=>$wms_code,
                'owner_name'=>$owner->name,
                'owner_id'=>$owner->id,
                'commodities'=>$commodities,
                'bill_type'=>'出库单',
            ];
            return json_encode($processContent);
        }
        $docMovementDetails=OracleDOCMovementDetail::query()->where("MDOCNO",$wms_code)->get();//移库单
        if (count($docMovementDetails)>0){
            $docMovementHeaders=OracleDOCMovementHeader::query()->select('customerid')->where('MDOCNO',$wms_code)->get();
            if (count($docMovementHeaders)<1)return ['error'=>'找到了移库单，但未查询移库单表头！'];
            $owner=Owner::query()->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);
            $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::query()->whereIn("CustomerID",$basSKUs['owner_code'])->whereIn("SKU",$basSKUs['sku'])->get();
        if (count($oracleBasSkus)<1)return;
        $commoditiesData=[];
        $commoditiesTem=["sku"=>[],"owner_id"=>[]];
        $commodityBarCodeData=[];
        $owners_code=array_column($oracleBasSkus->toArray(),'customerid');
        $ownersTem=Owner::query()->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]);
            if ($oracleBasSkus[$i]->alternate_sku1)$commodityBarCodeData[$oracleBasSkus[$i]->sku."_".$owners[$oracleBasSkus[$i]->customerid]]=["code"=>$oracleBasSkus[$i]->alternate_sku1,"commodity_id"=>'','created_at'=>Carbon::now()];
        }
        //保留：根据条码与货主批量二次查找商品
        if (count($commoditiesData) > 0){
            app('CommodityService')->insert($commoditiesData);
            app('LogService')->log(__METHOD__, 'FLUX二次加工单接口录入商品__' . __FUNCTION__, json_encode($commoditiesData), Auth::user()['id']);
            $commodities=Commodity::query()->whereIn('sku',$commoditiesTem['sku'])->whereIn('owner_id',$commoditiesTem['owner_id'])->get();
            foreach ($commodities as $commodity){
                if (isset($commodityBarCodeData[$commodity->sku."_".$commodity->owner_id]))
                    $commodityBarCodeData[$commodity->sku."_".$commodity->owner_id]['commodity_id']=$commodity->id;
            }
            if (count($commodityBarCodeData) > 0){
                app('CommodityBarcodeService')->insert(array_values($commodityBarCodeData));
                app('LogService')->log(__METHOD__, 'FLUX二次加工单接口录入商品条码__' . __FUNCTION__, json_encode($commodityBarCodeData), Auth::user()['id']);
            }
        }
    }


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

    private function resetCommodityAmount($code,$is_finished_product,$commodities){
        if ($is_finished_product) $type = "成品单";
        else $type="原料单";
        $ids = array_column($commodities,'id');
        $processesContent = ProcessesContent::query()->where('type',$type)->where('wms_code',$code)
            ->whereIn('commodity_id',$ids)->get();
        if (count($processesContent) < 1)return $commodities;
        $amountMap = [];
        foreach ($processesContent as $content){
            if ($amountMap[$content->commodity_id] ?? false)$amountMap[$content->commodity_id] += $content->amount;
            else $amountMap[$content->commodity_id] = $content->amount;
        }
        foreach ($commodities as &$commodity){
            if (($amountMap[$commodity['id']] ?? false) && $amountMap[$commodity['id']] < $commodity['amount']){
                $commodity['former_amount'] = $commodity['amount'];
                $commodity['amount'] = ($commodity['amount'])-$amountMap[$commodity['id']];
            }
        }
        return $commodities;
    }
}
