<?php
namespace App\Http\Middleware;

use Closure;
use DB;
use Illuminate\Support\Facades\Crypt;

class WechatAppletLogin
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if (!$request->exists('api_token')) {
            return response()->json(['code'=>300, 'msg'=>'api_token错误', 'data'=>'']);
        }
        
        $request['api_token_old'] = $request['api_token'];
        // 解密api_token，如果不是系统生成的token会解密失败
        try {
            $api_token = Crypt::decrypt($request['api_token']);
        } catch (\Exception $e) {
            return response()->json(['code'=>300, 'msg'=>'非法api_token', 'data'=>'']);
        }

        $que = $request->route()->getAction();//获取请求的路由
        $action =explode('@',$que['uses'])[1];//方法
        $controller = trim($que['prefix'],'/');
        // 拿到token获取登录表信息
        $login_wechat_applet = DB::table('login_wechat_applet as l')
            ->leftjoin('shop', 'shop_id', '=', 'adm_shop_id')
            ->leftjoin('admin_shop_role as a', 'a.adm_id', '=', 'l.adm_id')
//            ->leftjoin('admin as a', 'a.adm_id', '=', 'l.adm_id')
            ->where('a.login_shop_wechat', 1)
            ->where('api_token', $api_token)
            ->select('last_login', 'api_token', 'l.adm_phone', 'shop_source_identify', 'adm_shop_leave as adm_leave', 'adm_state', 'a.adm_id', 'shop_opening_type', 'shop_on_trial_end_time', 'shop_opening_end_time')
            ->first();
        if (empty($login_wechat_applet)) {
            return response()->json(['code'=>300, 'msg'=>'不是系统api_token', 'data'=>'']);
        }
        if (!($action == 'getPri' || $action == 'getPersonalShops' || $action == 'switchShopLogin')) {
            if ($login_wechat_applet->shop_opening_type == 1) {//开通类型1免费试用2正式开通
                $shop_on_trial_end_time = strtotime($login_wechat_applet->shop_on_trial_end_time);
                if (time()>$shop_on_trial_end_time) {
                    return response()->json(['code'=>301, 'msg'=>'试用时间结束，请购买正式版本', 'data'=>'试用时间结束，请购买正式版本']);
                }
            } elseif ($login_wechat_applet->shop_opening_type == 2) {
                $shop_opening_end_time = strtotime($login_wechat_applet->shop_opening_end_time);
                if (time()>$shop_opening_end_time) {
                    return response()->json(['code'=>301, 'msg'=>'已到期，请续费', 'data'=>'已到期，请续费']);
                }
            }
        }
        

        if ($login_wechat_applet->adm_state == 2) {//状态1在职2离职
            return response()->json(['code'=>300, 'msg'=>'此用户已离职', 'data'=>'']);
        }
        $date = date('Y-m-d H:i:s');
        $find_online = DB::table('online_management')
            ->where('onma_state', 1)
            ->where('onma_start_time', '<=', $date)
            ->where('onma_end_time', '>=', $date)
            ->first();
        if ($find_online) {
            $adm_id = explode(',', $find_online->onma_adm_id);
            if (!in_array($login_wechat_applet->adm_id, $adm_id)) {
                return response()->json(['code'=>300, 'msg'=>$find_online->onma_name, 'data'=>'']);
            }
        }
        if ($login_wechat_applet->shop_source_identify == '5' && $login_wechat_applet->adm_leave != 3) {
            $id = DB::table('settle_in')
                ->where('phone',$login_wechat_applet->adm_phone)
                ->value('id');
            $ret = DB::table('settle_sync_information')
                ->where('settle_in_id', $id)
                ->where('info_status', 2)//审核结果:1默认2通过3驳回
                ->orderBy('id','desc')
                ->select('remark','info_status')
                ->first();
            if (empty($ret)) {
                $se_ret = DB::table('settle_in')
                    ->where('id', $id)
                    ->select('id','status')
                    ->first();
                if(!empty($se_ret) && !in_array($se_ret->status, [4,2,6])){
                    if($login_wechat_applet->shop_source_identify != 5) {
                        return response()->json(['code' => 300, 'msg' => '审核未通过', 'data' => '']);
                    }
                }
            }
        }


        // 判断api_token是否与数据库token一致
        if($api_token !== $login_wechat_applet->api_token){
            return response()->json(['code'=>300, 'msg'=>'api_token错误', 'data'=>'']);
        }

        // 当前时间
        $hours = time();
        // 如果最后登录时间小于当前时间,说明登陆过期
        // if ($login_wechat_applet->last_login < $hours) {
        //     return response()->json(['code'=>300, 'msg'=>'登陆过期', 'data'=>'']);
        // }

        // 如果一直在操作就当前时间加2小时
        DB::table('login_wechat_applet')->where('api_token','=',$api_token)->update(['last_login'=>$hours + 4*60*60]);
        
        $request['api_token'] = $api_token;//赋值解密后的token值
        return $next($request);
    }
}
