<?php

namespace App\Http\Middleware;

use App\Modules\User\Services\QappPackageService;
use Closure;
use Tymon\JWTAuth\Middleware\BaseMiddleware;

class QuickAppGetPackage extends BaseMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        // 获取头部信息
        $package     = $request->header('x-package', '');
        if(empty($package)){
            $package = $request->input('package',"");
        }
        $origin_package = $package;
        //FIXME 海天包传成浩瀚了，特殊处理下，这个名字就给海天用
//         if($package =='com.beidao.kuaiying.haohan'){
//             $package = 'com.beidao.kuaiying.haitian';
//         }
        
//        //FIXME 浩瀚包传的是haohannew，但是打开要跟官方包名保持一致，所以这样特殊处理
//        if($package =='com.beidao.kuaiying.haohannew'){
//            $package = 'com.beidao.kuaiying.haohan';
//        }

        $package = get_real_package($package);
        $channel_id = QappPackageService::getChannelId($package);
        $sendOrderId  = $request->header('send-order-id',0);
        if($request->input('send_order_id',0)){
            $sendOrderId = $request->input('send_order_id',0);
        }
        $sendOrderId = check_qapp_send_order_id($channel_id,$sendOrderId) ? $sendOrderId : 0;
        $request->headers->set('send-order-id',$sendOrderId);
        $request->headers->set('x-package',$package);
        $request->merge(['send_order_id' => $sendOrderId,'distribution_channel_id' => $channel_id,'package' => $package]);
        if($channel_id > 0){
            return $next($request);
        }else{
            \Log::info('not_exists_package:'.$package. 'channel_id:'. $channel_id);
            return response()->error('QAPP_SYS_ERROR');
        }

    }
}
