<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\DwbsUser;
use App\Models\LoginLog;
use App\Models\OrderRefund;
use Carbon\Carbon;
use GuzzleHttp\Client;
use Illuminate\Http\Request;
use App\Models\Admin;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;
use Zhuzhichao\IpLocationZh\Ip;


class LoginController extends Controller
{

//管理员登录
    public function login(Request $request)
    {
        header("Access-Control-Allow-Origin: *");
        header("Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE");
        header('Access-Control-Allow-Headers:x-requested-with,content-type');

        $input=$request->all();
        $rules=[
            'name'=>'required|between:5,12',
            'password'=>'required|between:6,12'
        ];
        $messages=[
            'name.required'=>'账号不能为空.',
            'name.between'=>'账号长度应为5-12个字符.',
            'password.required'=>'密码不能为空.',
            'password.between'=>'密码长度应为6-12个字符.',
        ];
        $validator = Validator::make($input, $rules, $messages);
        if($validator->fails()){
            return $this->error('400013',$validator->errors()->first());
        }
        $admin=Admin::where('name',$input['name'])->first();
        $real_ip=$request->header('X-Real-IP');
        $ip_arr=$request->header('x-forwarded-for');
        $ip_arr=explode(',',$ip_arr);
        if ($ip_arr[0]=='127.0.0.1'){
            $address=Ip::find(trim($ip_arr[1]));
        }else{
            $address=Ip::find($ip_arr[0]);
        }

        $ip_arrs=$request->header('x-forwarded-for');
        $ip_arrs=explode(',',$ip_arrs);
        $ddress_arr=[];
        foreach ($ip_arrs as $k=>$v){
            $ddress_arr[]=Ip::find(trim($v));
        }
        try {
            $log=new LoginLog();
            $log->name=$input['name'];
            $log->address=json_encode($address,JSON_UNESCAPED_UNICODE);
            $log->address_arr=json_encode($ddress_arr,JSON_UNESCAPED_UNICODE);
            $log->info=json_encode($request->header(),JSON_UNESCAPED_UNICODE);
            $log->real_ip=$real_ip;
            $log->ip_info=json_encode($ip_arr,JSON_UNESCAPED_UNICODE);
            $log->time=Carbon::now()->toDateTimeString();
            $log->ip=$ip_arr[0];
            $log->status='ERROR';
            $log->save();
            $client=new Client();

            $url='https://oapi.dingtalk.com/robot/send?access_token=fe9c0949d2dbab3ca20274632ddfd62a55ad42ada6e099f46daf718a5bb7d4ff';
            $arr=[
                'msgtype'=>'text',
                'text'=>[
                    'content'=>$input['name'].'账号进行了登录操作，状态登录失败，'.'IP地址为：'.json_encode($ip_arr,JSON_UNESCAPED_UNICODE).'；IP所属地为：'.json_encode($ddress_arr,JSON_UNESCAPED_UNICODE)
                ],
            ];
//            dd(json_encode($arr,JSON_UNESCAPED_UNICODE));
            $client->post($url,[
                'json'=>$arr
            ]);
        }catch (\Exception $exception){
//            Log::log($exception->getMessage());
            Log::info($exception->getMessage());
        }
        $pass=Hash::make($input['password']);
        if($input['name']!='test123'){
            'd';
        }

        if($admin){
            if($admin->status=='2'){
                return $this->error('400004','账户已禁用');
            }
            if(!Hash::check($input['password'],$admin->password)){
                return $this->error('400004','密码有误');
            }
        }else{
            return $this->error('400004','账户名不存在');
        }
        try {
            $log->status='SUCCESS';
            $log->save();
            $url='https://oapi.dingtalk.com/robot/send?access_token=fe9c0949d2dbab3ca20274632ddfd62a55ad42ada6e099f46daf718a5bb7d4ff';
            $arr=[
                'msgtype'=>'text',
                'text'=>[
                    'content'=>$input['name'].'账号进行了登录操作，状态登录成功，'.'IP地址为：'.json_encode($ip_arr,JSON_UNESCAPED_UNICODE).'；IP所属地为：'.json_encode($ddress_arr,JSON_UNESCAPED_UNICODE)
                ],
            ];
//            dd(json_encode($arr,JSON_UNESCAPED_UNICODE));
            $client->post($url,[
                'json'=>$arr
            ]);
        }catch (\Exception $exception){
            Log::error('登录成功：'.$input['name'].',ip为：'.$request->header('x-forwarded-for'));
        }
        $token = Auth::guard('api')->fromUser($admin);
        $data['admin']=$admin;
        $data['token']=$token;
        return $this->success($data);
    }


    public function user(){
        $id=Auth::guard('admin')->user()->id;
        $admin=Admin::with('role:id,name,permissions')->where('id',$id)->first();
        if($admin && in_array($admin->role_id,[22,24])){//超级管理员
            $data=OrderRefund::query();
        }else{
            $agent_ids=DwbsUser::whereHas('warea',function($query)use($admin){
                $query->where('admin_id',$admin->id);
            })->pluck('id');
            $data=OrderRefund::whereHas('store',function($query)use($agent_ids){
                $query->whereIn('user_id',$agent_ids);
            });
        }
        $admin->refund_no_auth = $data->where('status', 0)->count();
        return $this->success($admin);
    }

    //退出登录
    public function logout(){
        Auth::guard('admin')->logout();
        return $this->success([]);
    }
}
