<?php

namespace App\Http\Controllers;

use App\Filters\OrderTrackFilters;
use App\Logistic;
use App\OrderTracking;
use App\Services\common\ExportService;
use App\Services\OrderTrackingService;
use App\Services\OwnerService;
use App\UploadFile;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Gate;
use Intervention\Image\Facades\Image;
use Ramsey\Uuid\Uuid;

class OrderTrackingController extends Controller
{

    public function index(Request $request,OrderTrackFilters $filters)
    {
        if (!Gate::allows('订单管理-跟踪')) return redirect(url('/'));

        /** @var OrderTrackingService $service */
        $service = app(OrderTrackingService::class);
        $service->fillInOrderTracking();

        $trackOrders = OrderTracking::query()->filter($filters)->defaultQuery()->defaultWith()->paginate($request['paginate'] ?? 50);

        $trackOrders->map(function($trackOrder){
            if($trackOrder->uploadFile){
                if(!str_starts_with($trackOrder->uploadFile->url,'http'))
                    $trackOrder->uploadFile->url = asset('/storage'.$trackOrder->uploadFile->url);
            }
        });

        $logistics = Logistic::all();
        $owners =  app(OwnerService::class)->getAuthorizedOwners();
        return view('order.tracking.index', compact('owners', 'trackOrders','logistics'));
    }

    public function logisticUpdateApi(Request $request)
    {
        if (!Gate::allows('订单管理-跟踪-物流公司编辑'))
            return redirect(url('/'));
        try {
            $message = app(OrderTrackingService::class)->updateOrderTracingAndSyc($request->input('id'),$request->input('param'),$request->input('value'));
            app('LogService')->log(__METHOD__, __FUNCTION__, '更新成功' . json_encode($request->getContent()) );
            return $message;
        } catch (\Exception $e) {
            app('LogService')->log(__METHOD__, __FUNCTION__, '更新失败' . json_encode($request->getContent()) .'||'.$e->getMessage().'||'.$e->getTraceAsString());
            return ['success' => false];
        }
    }

    public function warehouseUpdateApi(Request $request)
    {
        if (!Gate::allows('订单管理-跟踪-仓库编辑'))
            return redirect(url('/'));
        try {
            $message = app(OrderTrackingService::class)->updateOrderTracingAndSyc($request->input('id'),$request->input('param'),$request->input('value'));
            app('LogService')->log(__METHOD__, __FUNCTION__, '更新成功' . json_encode($request->getContent()));
            return $message;
        } catch (\Exception $e) {
            app('LogService')->log(__METHOD__, __FUNCTION__, '更新失败' . json_encode($request->getContent()) .'||'.$e->getMessage().'||'.$e->getTraceAsString());
            return ['success' => false];
        }
    }

    public function updateLogisticIdApi(Request $request)
    {
        if (!Gate::allows('订单管理-跟踪-仓库编辑'))
            return ['success'=>false,'fail_info'=>'没有对应权限'];
        try {
            $logistic = Logistic::query()->where('name',$request['value'])->first();
            $bool = OrderTracking::query()->where('id',$request['id'])->update(['logistic_id'=>$logistic['id']]);
            if($bool){
                app('LogService')->log(__METHOD__, __FUNCTION__, '更新成功' . json_encode($request->getContent()));
                return ['success'=>true];
            }else{
                app('LogService')->log(__METHOD__, __FUNCTION__, '更新失败' . json_encode($request->getContent()));
                return  ['success'=>false,'fail_info'=>'修改失败'];
            }
        } catch (\Exception $e) {
            app('LogService')->log(__METHOD__, __FUNCTION__, '更新失败' . json_encode($request->getContent()) .'||'.$e->getMessage().'||'.$e->getTraceAsString());
            return ['success' => false,'fail_info'=>$e->getMessage()];
        }
    }

    public function upload(Request $request)
    {
        if (!Gate::allows('订单管理-跟踪-物流公司编辑'))
            return ['success'=>false,'fail_info'=>'没有对应权限'];
        $file=$request->file('file');
        /** @var OrderTracking $orderTracking */
        $orderTracking = OrderTracking::query()->with('uploadFile')->find($request['id']);
        if(!$orderTracking){
            return ['success'=>false,'error'=>'未找到该追踪件'];
        }
        if($orderTracking->uploadFile){
            return ['success'=>false,'error'=>'该运单已存在照片！'];
        }
        if(!$file){
            return ['success'=>false,'error'=>'照片不能为空！'];
        }
        if(!$file->isValid()){
            return ['success'=>false,'error'=>'找不到照片'];
        }
        $tmpFile = $file->getRealPath();
        if(!is_uploaded_file($tmpFile)){
            return ['success'=>false,'error'=>'文件错误'];
        }
        $fileExtension=$file->getClientOriginalExtension();
        $fileName=date('ymd').'-'.Uuid::uuid1(); // 文件名生成
        $thumbnailName=storage_path('app/public/files/'.$fileName.'-thumbnail.'.$fileExtension);
        $commonName=storage_path('app/public/files/'.$fileName.'-common.'.$fileExtension);
        $bulkyName=storage_path('app/public/files/'.$fileName.'-bulky.'.$fileExtension);
        $result=move_uploaded_file ($tmpFile ,$bulkyName);
        if($result) {
            $img = Image::make($bulkyName);
            if ($img->height() > $img->width()) {
                $img->heighten(250)->save($commonName);
            } else {
                $img->widen(250)->save($commonName);
            }
            $img->heighten(28)->save($thumbnailName);
            $uploadFile=new UploadFile([
                "table_name"=>"order_trackings",
                "table_id"=>$orderTracking->order_client_code,
                "url"=>'/files/'.$fileName,
                "type"=>$fileExtension,
            ]);
            if ($uploadFile->save()){
                app('LogService')->log(__METHOD__, '追踪件 图片上传' . __FUNCTION__, json_encode($request));
            }
            $uploadFile->url=asset('/storage'.$uploadFile->url);
            return ['success'=>true,'data'=>$uploadFile];
        }
        return ['success'=>false,'error'=>'图片上传失败'];
    }

    public function export(Request $request,OrderTrackFilters  $filters)
    {
        if (!Gate::allows('订单管理-跟踪')) return redirect(url('/'));

        $orderTrackings = OrderTracking::query()->filter($filters)->defaultQuery()->defaultWith()->get();

        $row = ['公司','订单号','WEB+订单号','提货日期','销售','客户','SKU','物料描述','数量','订单备注','重量','体积',
            '托盘合计','运输方式','运输单号','到达城市','序列号','应送达时间','是否赶上卡班','到货情况','签收日期','签收单情况','备注'];
        $mergeRow = [];
        $list=[];
        $start_row = 0;
        $order_client_code_temp = '';
        $row_count = 0;
        foreach ($orderTrackings as $index=> $orderTracking) {
            $logistic =  $orderTracking->logistic->name ?? '';
            if($order_client_code_temp==''){
                $order_client_code_temp=$orderTracking->order_client_code;
                $row_count=1;
            }else if($order_client_code_temp==$orderTracking->order_client_code){
                $row_count++;
                if($index == $orderTrackings->count()-1){
                    if($row_count>1){
                        $end_row=$index+2;
                        $start_row = $index+3-$row_count;
                        $mergeRow[(string)($start_row)]=(string)($end_row);
                    }
                }
            }else if($order_client_code_temp!=$orderTracking->order_client_code){
                if($row_count>1){
                    $end_row=$index+1;
                    $start_row = $index+2-$row_count;
                    $mergeRow[(string)($start_row)]=(string)($end_row);
                }
                $start_row=$index+2;
                $row_count=1;
                $order_client_code_temp = $orderTracking->order_client_code;
            }
            $serialNumberStr = '';
            if($orderTracking['commodities']['serialNumbers']){
                foreach ($orderTracking['commodities']['serialNumbers'] as $serialNumber){
                    $serialNumberStr.=$serialNumber['serial_number'].",\r\n";;
                }
            }

            $order_client_code = $orderTracking->web_order_number?'':$orderTracking->order_client_code;
            $web_order_number = $orderTracking->web_order_number??'';
            $pick_up_at=str_split($orderTracking->pick_up_at,10)[0];
            $planning_sent_at=str_split($orderTracking->planning_sent_at,10)[0];
            $signed_at=str_split($orderTracking->signed_at,10)[0];
            $logistic_number =$orderTracking->commodities->package->logistic_number;
            if($logistic=='新杰物流'||$logistic=='新杰物流到付'){
                $logistic_number = $orderTracking->order_client_code;
            }
            if(str_starts_with('null',$logistic_number)){
                $logistic_number = '';
            }
            $list[]=[
                $orderTracking->owner->name ?? '',
                $order_client_code,
                $web_order_number,
                $pick_up_at=='0000-00-00'?'':$pick_up_at,
                $orderTracking->sale,
                $orderTracking->client,
                $orderTracking->commodities->commodity->sku ?? '',
                $orderTracking->commodities->commodity->name ?? '',
                $orderTracking->commodities->amount ?? '',
                $orderTracking->order_remark,
                $orderTracking->gross_weight,
                $orderTracking->bulk,
                $orderTracking->pallet_total,
                $logistic,
                $logistic_number,
                $orderTracking->commodities->package->order->city ?? '',
                rtrim($serialNumberStr,",\r\n"),              //原始运单号
                $planning_sent_at=='0000-00-00'?'':$planning_sent_at,
                $orderTracking->is_on_duty_shift,
                $orderTracking->is_arrival,
                $signed_at=='0000-00-00'?'':$signed_at,
                $orderTracking->receive_bill_status,
                $orderTracking->remark,
            ];
        }
        return app(ExportService::class)->json($row,$list,'订单跟踪件');
    }

    public function destroyImg(Request $request)
    {
        if(!Gate::allows('订单管理-跟踪-物流公司编辑'))
            return ['success'=>false,'error'=>'没有对应权限'];
        $orderTracking = OrderTracking::query()->where('id',$request['id'])->first();
        if(!$orderTracking){
            return ['success'=>false,'error'=>'没有找到对应id'];
        }
        try {
            return ['success'=>UploadFile::query()->where('table_name', 'order_trackings')->where('table_id', $orderTracking->order_client_code)->delete()];
        } catch (Exception $e) {
            app('LogService')->log(__METHOD__,__FUNCTION__,'追踪件删除照片'.json_encode($e->getMessage()).json_encode($e->getTraceAsString()));
            return ['success'=>false,'error'=>$e->getMessage()];
        }
    }
}

