<?php

namespace App\Http\Middleware;

use Closure;
use DB;
use Illuminate\Support\Facades\Crypt;
class IsLogin
{
    /**
     * 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'=>'请输入api_token']);
        }
        // 解密api_token，如果不是系统生成的token会解密失败
        try{
            $api_token = Crypt::decrypt($request['api_token']);
        }catch (\Exception $e){
            return response()->json(["code"=>300,'msg'=>'登录过期','data'=>'非法api_token']);
        }
        $que = $request->route()->getAction();//获取请求的路由
        $action =explode('@',$que['uses'])[1];//方法
        $controller = trim($que['prefix'],'/');
        // 拿到token获取登录表信息
        $login_temporary = DB::table('login_temporary')
            ->leftjoin('shop as s', 'shop_id', '=', 'adm_shop_id')
            ->where('api_token','=',$api_token)
            ->select('last_login','api_token', 'adm_shop_id', 'shop_opening_type', 'shop_on_trial_end_time', 'shop_opening_end_time', 'adm_id', 's.shop_superior_id')
            ->first();
        if(empty($login_temporary)){
            return response()->json(["code"=>300,'msg'=>'登录过期','data'=>'不是系统api_token']);
        }
        $find_adm_shop_role = DB::table('admin_shop_role')
            ->where('adm_id', $login_temporary->adm_id)
            ->first();
        if ($find_adm_shop_role) {
            $find_admin = DB::table('admin')
                ->leftjoin('admin_shop_role', 'admin_shop_role.adm_id', '=', 'admin.adm_id')
                ->where('admin.adm_id', $login_temporary->adm_id)
                ->where('admin_shop_role.login_shop', 1)
                ->where('admin_shop_role.shop_id', $login_temporary->adm_shop_id)
                ->first(['admin_shop_role.adm_state']);
            if ($find_admin) {
                if ($find_admin->adm_state == 2) {
                    return response()->json(["code"=>300,'msg'=>'您已离职，无法继续操作','data'=>'']);
                }
            }
        }
        $shop_state = DB::table('shop')
            ->where('shop_id', $login_temporary->adm_shop_id)
            ->select('shop_state', 'shop_opening_end_time')
            ->first();
        if ($shop_state) {
            if ($shop_state->shop_state == 2) {
                return response()->json(["code"=>300,'msg'=>'您的门店已停用，无法继续操作','data'=>'您的门店已停用，无法继续操作']);
            }
        }
        // if(empty($login_temporary->adm_shop_id)){
        //     return response()->json(["code"=>300,'msg'=>'error','data'=>'不是系统api_token']);
        // }

        // 判断api_token是否与数据库token一致
        if($api_token !== $login_temporary->api_token){
            return response()->json(["code"=>300,'msg'=>'api_token错误','data'=>'api_token错误']);
        }
        
        if (!($action == 'leftList' || $action == 'shopInfo'|| $action == 'switchShopLogin' || $action == 'wxpay'|| $action == 'aliPay' || $action == 'getOrderState' || $action == 'getCoupon' || $action == 'getSpaPrice')) {
            if ($login_temporary->shop_opening_type == 1) {//开通类型1免费试用2正式开通
                $shop_on_trial_end_time = strtotime($login_temporary->shop_on_trial_end_time);
                if (time()>$shop_on_trial_end_time) {
                    return response()->json(['code'=>301, 'msg'=>'试用时间结束，请购买正式版本', 'data'=>'试用时间结束，请购买正式版本']);
                }
            } elseif ($login_temporary->shop_opening_type == 2) {
                $shop_opening_end_time = strtotime($login_temporary->shop_opening_end_time);
                if (time()>$shop_opening_end_time) {
                    if ($login_temporary->shop_superior_id) {
                        return response()->json(['code'=>303, 'msg'=>'系统已到期，请联系总店进行续费！', 'data'=>'系统已到期，请联系总店进行续费！']);
                    }
                    return response()->json(['code'=>302, 'msg'=>'已到期，请续费', 'data'=>'已到期，请续费']);
                }
            }
        }
        // 当前时间
        $hours = time();
        // 如果最后登录时间小于当前时间,说明登陆过期
        if($login_temporary->last_login < $hours){
            return response()->json(["code"=>300,'msg'=>'登陆过期','data'=>'']);
        }

        // // 如果一直在操作就当前时间加4小时
        DB::table('login_temporary')->where('api_token','=',$api_token)->update(['last_login'=>$hours + 4*60*60]);
        
        DB::listen(function ($query) {
            $bindings = $query->bindings;
            $sql = $query->sql;
            foreach ($bindings as $replace) {
                $value = is_numeric($replace) ? $replace : "'" . $replace . "'";
                $sql = preg_replace('/\?/', $value, $sql, 1);
            }
            if(strpos($sql,'delete') === 0){
                $url = storage_path().'/logs/sql.txt';
                $dir_name=dirname($url);
                //目录不存在就创建
                if (!file_exists($dir_name)) {
                    //iconv防止中文名乱码
                    mkdir(iconv("UTF-8", "GBK", $dir_name));
                    chmod($dir_name, 0777);
                }
                $fp = fopen($url, "a");//打开文件资源通道 不存在则自动创建
                date_default_timezone_set('PRC');
                flock($fp, LOCK_EX);
                if (is_array($sql)) {
                    $sql = json_encode($sql);
                }
                fwrite($fp, date("Y-m-d H:i:s").' '.var_export($sql, true)."\r\n\r\n");//写入文件
                flock($fp, LOCK_UN);
                fclose($fp);//关闭资源通道
            }
        });
        
        $request['api_token'] = $api_token;//赋值解密后的token值
        return $next($request);
    }
}
