<?php

namespace App\Http\Controllers;

use App\OracleBasCustomer;
use App\OracleDOCOrderHeader;
use App\OracleDOCWaveDetails;
use App\OrderIssueType;
use App\Services\LogisticService;
use App\Services\LogService;
use App\Services\OrderService;
use App\Services\RejectedBillItemService;
use App\Services\RejectedBillService;
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 OrderController extends Controller
{
    public function delivering(Request $request){
        if(!Gate::allows('订单管理-查询')){ return view('order/index');  }
        /** @var OrderService $orderService */
        $orderService = app('OrderService');
        $request = $request->input();
        $owners = app('OwnerService')->getIntersectPermitting(['id','code']);
        $service=app(LogisticService::class);
        $logistics=$service->getSelection(['id','name']);
        $codes = array_column($owners->toArray(),'code');
        if ($request['customerid'] ?? false){
            $arr = explode(',',$request['customerid']);
            $request['customerid'] = [];
            foreach ($arr as $value){
                if (in_array($value,$codes))$request['customerid'][] = $value;
            }
            if (count($request['customerid']) < 1)$request['customerid'] = [''];
        }else $request['customerid'] = $codes;

        $result = $orderService->paginate($request);
        $picktotraceids = $result['picktotraceids'];
        $orders = $result['orders'];
        $orderIssueNos =  $orderService->返回有问题件的订单号($orders);
        $commodities = $result['commodities'];
        $customers=app('OracleBasCustomerService')->getCustomers($codes);
        $page = $request["page"] ?? 1;
        $codes=DB::connection('oracle')->table('BAS_CODES')->select('code','codename_c')->where('codeid','SO_STS')->orderBy('code','asc')->get();
        $orderIssueType = OrderIssueType::all();
        return view('order/index/delivering',compact('orders','customers','request','codes','commodities','page','picktotraceids','orderIssueType','orderIssueNos','logistics'));
    }

    //导出
    public function export(Request $request){
        $is_merge = $request->is_merge ?? false;
        /** @var OrderService $orderService */
        $orderService = app('OrderService');
        $req = ['type'=>'order'];
        if ($is_merge && $is_merge == 'true')$req["createFormat"] = "merge";
        if ($request->data){
            $req["sql"] = $orderService->getSql(['data'=>$request->data]);
        }else{
            $req["sql"] = $orderService->getSql($request->input());
        }
        $post = Http::post(config('go.export.url'),$req);
        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 createRejectedBill(Request $request){
        if(!Gate::allows('订单管理-订单-生成退货单')){ return ['success'=>false,'data'=>'您无权操作！'];  }
        /** @var OrderService $orderService */
        $orderService = app('OrderService');
        $result = $orderService->get(['data' => $request->data]);

        /** @var RejectedBillService $rejectedBillService */
        $rejectedBillService = app('RejectedBillService');

        /** @var RejectedBillItemService $rejectedBillItemService */
        $rejectedBillItemService = app('RejectedBillItemService');

        $commodities = $result['commodities'];
        $rejectedBillItems = [];
        //分箱号
        $picktotraceids = json_decode($result['picktotraceids'],true);
        $rejectedBill_collect = collect();// 保存生成的rejectedBill
        foreach ($result['orders'] as $order){
            $blacklist = ["00","10","20","30","90"/*,"99"*/];
            if (array_search($order->sostatus,$blacklist) !== false)return ['success'=>false,'data'=>'“'.$order->orderno."”状态异常，无法操作"];
        }
        foreach ($result['orders'] as $order){
            //不存在时将当前快递单号视为分箱号
            if (!($picktotraceids[$order->orderno] ?? false))$picktotraceids[$order->orderno] = [$order->soreference5];
            //获取货主与快递方
            $owner = app('OwnerService')->firstOrCreate(['name' => $order->customer_descr_c],
                ['name' => $order->customer_descr_c, 'code' => $order->customer_descr_c]);
            $logistic = app('LogisticService')->firstOrCreate(['name' => $order->carriername],
                ['name' => $order->carriername, 'code' => $order->carriername]);
            foreach ($picktotraceids[$order->orderno] as $orderno){
                $rejectedBill = $rejectedBillService->create([
                    'id_owner' => $owner->id,
                    'sender' => $order->c_contact,
                    'logistic_number_return' => $orderno,
                    'id_logistic_return' => $logistic->id,
                    'order_number' => $order->soreference1,
                    'mobile_sender' => empty($order->c_tel2)?$order->c_tel1:$order->c_tel2,
                    'logistic_number' => '原单退回',//$order->soreference1
                    'remark' => $order->notes,
                    'is_loaded' =>0,
                    "id_operator" => Auth::id(),
                ]);
                $rejectedBill_collect->push($rejectedBill);// 保存生成的rejectedBill
                LogService::log(__METHOD__,"生成退货单",json_encode($order),Auth::user()['id']);
                $cms = $commodities[$order->orderno] ?? [];
                if (count($picktotraceids[$order->orderno]) > 0 && $cms){
                    $sql = <<<sql
 SELECT sum(QTY) qty,sku FROM ACT_ALLOCATION_DETAILS where ORDERNO = ? and PICKTOTRACEID = ? GROUP BY sku
sql;
                    $acts = DB::connection("oracle")->select(DB::raw($sql),[$order->orderno,$orderno]);
                    $skus = array_column($acts,"sku");
                    foreach ($cms as $orderCommodities){
                        $index = array_search($orderCommodities["sku"],$skus);
                        if ($index === false)continue;
                        array_push($rejectedBillItems,[
                            'id_rejected_bill' => $rejectedBill->id,
                            'barcode_goods' => $orderCommodities['alternate_sku1'],
                            'name_goods' => $orderCommodities['descr_c'],
                            'amount' => $acts[$index]->qty,//$orderCommodities['qtyordered'],
                            'id_quality_label' => 1,
                            'created_at' => date('Y-m-d H:i:s'),
                        ]);
                    }
                }
            }
        }
        $rejectedBillItemService->insert($rejectedBillItems);
        LogService::log(__METHOD__,"批量生成退货单详情",json_encode($rejectedBillItems),Auth::user()['id']);
        $rejectedBill_collect->each(function($rejectedBill)use($rejectedBillService){
            $rejectedBillService->joinOrderIssue($rejectedBill);
            $rejectedBillService->syncOrderIssue($rejectedBill);
        });
        return ['success'=>true];
    }

    public function isRejectedBillExist(Request $request){
        if(!Gate::allows('订单管理-订单-生成退货单')){ return redirect(url('/'));  }
        /** @var RejectedBillService $rejectedBillService */
        $rejectedBillService = app('RejectedBillService');
        $rejectedBills = $rejectedBillService->get(['order_number' => $request->data]);
        if (count($rejectedBills) == 0)return ['success'=>true];
        return ['success'=>false, 'data'=>json_encode(array_column($rejectedBills->toArray(),'order_number'))];
    }

    //批量备注追加
    public function batchComments(Request $request){
        if(!Gate::allows('订单管理-批量备注')){ return redirect(url('/'));  }
        $checkData=$request->input('checkData');
        $content=$request->input('content');
        $ordersNotNull=OracleDOCOrderHeader::query()->select('OrderNo','Notes')->whereIn('orderno',$checkData)
            ->whereNotNull('notes')->get();
        OracleDOCOrderHeader::query()->select('OrderNo','Notes')->whereIn('orderno',$checkData)
            ->whereNull('notes')->update(['notes'=>$content]);
        $ordersNotNullArr=array_column($ordersNotNull->toArray(),'orderno');
        $ordersNullArr=array_diff($checkData,$ordersNotNullArr);
        $data=[];
        foreach ($ordersNotNull as $order){
            OracleDOCOrderHeader::query()->where('orderno',$order->orderno)->update(["notes"=>($order->notes).",".$content]);
            app('LogService')->log(__METHOD__,'批量备注追加修改'.__FUNCTION__,json_encode($request->toArray()),Auth::user()['id']);
            $order->notes=($order->notes).",".$content;
            array_push($data,$order);
        }
        foreach ($ordersNullArr as $order){
            array_push($data,["orderno"=>$order,'notes'=>$content]);
        }
        return $data;
    }
    //批量冻结
    public function freezeAll(Request $request){
        if(!Gate::allows('订单管理-编辑')){ return redirect(url('/'));  }
        $checkData=$request->input('checkData')??'';
        //冻结条件只局限于 分配完成sostatus=40  创建订单sostatus=00  拣货完成sostatus=60  播种完成sostatus=61
        $sostatus=['40','00','60','61'];
        $orders=OracleDOCOrderHeader::select('OrderNo','SoStatus')->whereIn('orderno',$checkData)->whereIn('SoStatus',$sostatus)->get();
        if(count($checkData)!=count($orders))return ['success'=>false,'fail_info'=>"勾选订单有不可冻结订单"];
        foreach ($orders as $order){
            $waveno=OracleDOCOrderHeader::where('orderno',$order->orderno)->value('waveno');
            if ($waveno && $waveno!='*'){
                OracleDOCWaveDetails::where('waveno',$waveno)->where('orderno',$order->orderno)->delete();
                app('LogService')->log(__METHOD__,'批量冻结删除波次号'.__FUNCTION__,json_encode($request->toArray()),Auth::user()['id']);
            }
            $is_freeze=OracleDOCOrderHeader::where('orderno',$order->orderno)->update(['releasestatus'=>'H','waveno'=>'*']);
            app('LogService')->log(__METHOD__,'批量冻结修改'.__FUNCTION__,json_encode($request->toArray()),Auth::user()['id']);
            if (!$is_freeze)return ['success'=>false,'fail_info'=>"数据 {$order['orderno']} 更新失败"];
        }
        return ['success'=>true];
    }
    //批量取消分配
    public function deAllocationAll(Request $request){
        if(!Gate::allows('订单管理-编辑')){ return redirect(url('/'));  }
        $checkData=$request->input('checkData')??'';
        //取消分配条件只局限于 分配完成sostatus=40 和 部分分配sostatus=30
        $sostatus=['30','40'];
        $orders=OracleDOCOrderHeader::select('OrderNo','SoStatus')->whereIn('orderno',$checkData)->whereIn('SoStatus',$sostatus)->get();
        if(count($checkData)!=count($orders))return ['success'=>false,'fail_info'=>"勾选订单有不可取消分配订单"];
        foreach ($orders as $order){
            $is_deAllocation=$this->isDeAllocation($order->orderno);
            $waveno=OracleDOCOrderHeader::where('orderno',$order->orderno)->value('waveno');
            if ($waveno && $waveno!='*'){
                OracleDOCWaveDetails::where('waveno',$waveno)->where('orderno',$order->orderno)->delete();
                app('LogService')->log(__METHOD__,'批量取消分配删除波次号'.__FUNCTION__,json_encode($request->toArray()),Auth::user()['id']);
            }
            $deAllocation=OracleDOCOrderHeader::where('orderno',$order->orderno)->update(['sostatus'=>'00','waveno'=>'*']);
            app('LogService')->log(__METHOD__,'批量取消分配'.__FUNCTION__,json_encode($request->toArray()),Auth::user()['id']);
            if (!$is_deAllocation||!$deAllocation)return ['success'=>false,'fail_info'=>"数据 {$order['orderno']} 更新失败"];
        }
        return ['success'=>true];
    }
    //冻结
    public function freeze(Request $request){
        if(!Gate::allows('订单管理-编辑')){ return redirect(url('/'));  }
        $orderno=$request->input('orderno');
        $waveno=$request->input('waveno');
        if ($waveno && $waveno!='*'){
            OracleDOCWaveDetails::where('waveno',$waveno)->where('orderno',$orderno)->delete();
            app('LogService')->log(__METHOD__,'冻结删除波次号'.__FUNCTION__,json_encode($request->toArray()),Auth::user()['id']);
        }
        OracleDOCOrderHeader::where('orderno',$orderno)->update(['releasestatus'=>'H','waveno'=>'*']);
        app('LogService')->log(__METHOD__,'冻结'.__FUNCTION__,json_encode($request->toArray()),Auth::user()['id']);
        return ['success'=>true];
    }
    public function thaw(Request $request){
        if(!Gate::allows('订单管理-编辑')){ return redirect(url('/'));  }
        $orderno = $request->orderno;
        if (!is_array($orderno)) {
            $orderno = [$orderno];
        }
        OracleDOCOrderHeader::query()->whereIn('orderno',$orderno)->update(['releasestatus'=>'N']);
        app('LogService')->log(__METHOD__,'解冻'.__FUNCTION__,json_encode($request->toArray()),Auth::user()['id']);
        return ['success'=>true];
    }

    //重置快递获取标记
    public function resetLogisticsGetMark(Request $request){
        if(!Gate::allows('订单管理-编辑')){ return redirect(url('/'));  }
        $orderno=$request->orderno;
        OracleDOCOrderHeader::query()->whereIn('orderno',$orderno)->where('edisendflag2','W')->update(['edisendflag2'=>'N']);
        app('LogService')->log(__METHOD__,'解冻'.__FUNCTION__,json_encode($orderno),Auth::user()['id']);
        return ['success'=>true];
    }

    //取消分配
    public function deAllocation(Request $request){
        if(!Gate::allows('订单管理-编辑')){ return redirect(url('/'));  }
        $orderno=$request->input('orderno');
        $waveno=$request->input('waveno');
        if ($waveno && $waveno!='*'){
            OracleDOCWaveDetails::where('waveno',$waveno)->where('orderno',$orderno)->delete();
            app('LogService')->log(__METHOD__,'取消分配删除波次号'.__FUNCTION__,json_encode($request->toArray()),Auth::user()['id']);
        }
        OracleDOCOrderHeader::where('orderno',$orderno)->update(['sostatus'=>'00','waveno'=>'*']);
        app('LogService')->log(__METHOD__,'取消分配'.__FUNCTION__,json_encode($request->toArray()),Auth::user()['id']);
        $is_deAllocation=$this->isDeAllocation($orderno);
        if($is_deAllocation) return ['success'=>true];

    }
    //调用sp取消选中订单的分配
    public function isDeAllocation($orderno){
        $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'); //连接oracle数据库
        $IN_Warehouse='';
        $IN_Process_Action_C='' ;
        $IN_Process_By_C='By OrderNO';
        $IN_WaveNO_C='';
        $IN_OrderNO_C=$orderno;
        $IN_OrderLineNO_C='';
        $IN_AllocationDetailsID='';
        $IN_Language='';
        $IN_UserID='';
        $OUT_Return_Code='';
        $sql_sp="begin SPSO_DEALLOCATION_PROCESS(:IN_Warehouse,:IN_Process_Action_C,:IN_Process_By_C,
        :IN_WaveNO_C,:IN_OrderNO_C,:IN_OrderLineNO_C,:IN_AllocationDetailsID,:IN_Language,:IN_UserID,:OUT_Return_Code); end;";
        $stmt = oci_parse($conn, $sql_sp);
        oci_bind_by_name($stmt,':IN_Warehouse',$IN_Process_Action_C);
        oci_bind_by_name($stmt,':IN_Process_Action_C',$IN_Warehouse);
        oci_bind_by_name($stmt,':IN_Process_By_C',$IN_Process_By_C);
        oci_bind_by_name($stmt,':IN_WaveNO_C',$IN_WaveNO_C);
        oci_bind_by_name($stmt,':IN_OrderNO_C',$IN_OrderNO_C);
        oci_bind_by_name($stmt,':IN_OrderLineNO_C',$IN_OrderLineNO_C);
        oci_bind_by_name($stmt,':IN_AllocationDetailsID',$IN_AllocationDetailsID);
        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',$OUT_Return_Code,300);
        oci_execute($stmt);
        if (substr($OUT_Return_Code,0,3) != '000'){
            app('LogService')->log(__METHOD__,'调用sp根据订单取消分配失败'.__FUNCTION__,"ORDERNO:".$orderno."ERROR：".$OUT_Return_Code);
            return false;
        }
        oci_close($conn);
        return true;
    }

    public function resetInterfaceReturnMark(Request $request)
    {
        if(!Gate::allows('订单管理-编辑')){ return redirect(url('/'));  }
        $orderno=$request->orderno;
        $oldIds =OracleDOCOrderHeader::query()
            ->whereIn('orderno', $orderno)
            ->where('edisendflag', 'N')->pluck('orderno')->toArray();

        OracleDOCOrderHeader::query()
            ->whereIn('orderno',$orderno)
            ->where('sostatus','99')
            ->whereIn('edisendflag',['R','W'])
                ->where('addwho','!=','EDI')
            ->update(['edisendflag'=>'N']);

        $failedOrdernos =OracleDOCOrderHeader::query()
            ->whereIn('orderno', $orderno)
            ->where('edisendflag', '!=', 'N')->pluck('orderno');

        $successedOrdernos =OracleDOCOrderHeader::query()
            ->whereIn('orderno', array_diff($orderno,$oldIds))
            ->where('edisendflag', 'N')->pluck('orderno');

        app('LogService')->log(__METHOD__,'重置接口回传标记'.__FUNCTION__,json_encode($orderno),Auth::user()['id']);
        if (count($failedOrdernos)==0) {
            return ['success'=>true];
        } else {
            return ['success'=>false,'fail_info'=>"数据 {$failedOrdernos} 更新失败,数据{$successedOrdernos}更新成功"];
        }
    }

}
