<?php
/**
 * Created by PhpStorm.
 * User: hardyx
 * Date: 2019/8/29
 * Time: 10:52
 */


namespace App\Http\Middleware;


use App\Libs\Utils;
use Closure;
use Illuminate\Support\Facades\DB;

class ExternalSignCheck
{
    /**
     * 外部通用 判断签名是否正确.
     */
    public function handle($request, Closure $next)
    {
        $data = $request->all();
        \Log::info('对外API入参: '.json_encode($data, 256));
        $appid = getProp($data, 'appid', '');
        $company = DB::table('companies')->where('appid', $appid)->where('is_enable', 1)->first();
        if (!$company) {
            Utils::throwError('1001: 您的appid不合法!');
        }
        $timestamp  = getProp($data, 'timestamp', time());
        $sign = getProp($data, 'sign', '');
        $app_token = getProp($company, 'app_token');

        $params = [
            'appid'         => $appid,
            'timestamp'     => $timestamp,
        ];
        ksort($params);
        $str = strtolower(http_build_query($params));
        $checkSign = md5($str.'&key='.$app_token);
        \Log::info('ExternalSignCheck: str: '.$str.'; checkSign: '. $checkSign .'; paramSign: '.$sign);

        if ($checkSign != $sign) {
            Utils::throwError('1002: 您的签名不正确!');
        }

        $company_id = getProp($company, 'id');
        $distribution_channel_ids = DB::table('channel_users as cu')->leftJoin('distribution_channels as dc', 'dc.channel_user_id', 'cu.id')
            ->where('cu.company_id', $company_id)->where('cu.is_enabled', 1)->select('dc.id')->get()->pluck('id')->toArray();

        // 将数据绑定到全局
        $site                       = app('siteData');
        $site->appid                = $appid;
        $site->app_token            = getProp($company, 'app_token');
        $site->company_name         = getProp($company, 'name');
        $site->company_id           = $company_id;
        $site->channel_id           = $distribution_channel_ids;

        return $next($request);
    }
}
