<?php

namespace App\Http\Controllers;

use App\Models\DwbsUser;
use App\Models\User;
use App\Models\Verify;
use App\Models\VipLog;
use GuzzleHttp\Client;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Cache;
use Overtrue\EasySms\EasySms;
use Overtrue\EasySms\PhoneNumber;
use Illuminate\Support\Facades\Validator;
use App\Exceptions\ExampleException;

class LoginController extends Controller
{
    // 微信登陆
    public function wxLogin(Request $request){
        $Code=$request->input('wxcode');
        $store_id=$request->input('store_id')??null;
        log::info('code:'.$Code);
        $info=$this->getUserOpenid($Code);
        if(isset($info['openid']) && isset($info['unionid'])){
            $user=User::where('unionId',$info['unionid'])->where('openid',$info['openid'])->first();
            if(empty($user)){
                $user=User::where('unionId',$info['unionid'])
                    ->select('id','nickname','area_code','phone','openId','unionId','is_vip','status','sex','avatar')
                    ->first();
                if($user){
                    $openid_user=User::where('openid',$info['openid'])->first();
                    if($openid_user){
                        if(!empty($user->phone) && !empty($openid_user->phone) && ($user->phone <> $openid_user->phone)){
                            Log::info($user->nickname.'---'.$user->id.'---H5与小程序冲突');
                            return $this->error('450001','','H5与小程序冲突');
                        }
                        if(empty($user->phone) && !empty($openid_user->phone)){
                            $openid_user->unionid=$user->unionId;
                            $openid_user->save();
                            $user->delete();
                            $user = $openid_user;
                        }
                        if(empty($openid_user->phone)){
                            $user->openId=$info['openid'];
                            $user->save();
                            $openid_user->delete();
                        }
                    }else{
                        if(empty($user->openId)){
                            $user->openId=$info['openid'];
                            $user->save();
                        }
                    }
                }else{
                    $user=User::where('openid',$info['openid'])
                        ->select('id','nickname','area_code','phone','openId','unionId','is_vip','status','sex','avatar')
                        ->first();
                    if($user){
                        $user->unionId=$info['unionid'];
                        $user->save();
                    }else{
                        $userInfo=$this->getWxUserInfo($info['openid'],$info['access_token']);
                        if(isset($userInfo['openid']) && !empty($userInfo['openid'])){
                            $user=User::create([
                                'openId'=>$userInfo['openid'],
                                'unionId'=>$userInfo['unionid'],
                                'nickname'=>$userInfo['nickname'],
                                'name'=>$userInfo['nickname'],
                                'avatar'=>$userInfo['headimgurl'],
                            ]);
                        }else{
                            return $this->error('450001','','您未关注微信公众号1');
                        }
                    }
                }
            }
            if(!empty($user)){//用户存在
                if($user->status==1){
                    return $this->error('450001','该用户已被禁用');
                }
                //修改客户信息！！！！！！！！！！！！！！！！
                $userInfo=$this->getWxUserInfo($info['openid'],$info['access_token']);
                Log::info(json_encode($userInfo));
                if(isset($userInfo['openid'])){
                    if(empty($user->unionId) && !empty($userInfo['unionid'])){
                        $user->unionId=$userInfo['unionid'];
                    }
                    Log::info($userInfo['headimgurl'].'/////'.$userInfo['nickname']);
                    $user->avatar=$userInfo['headimgurl'];
                    $user->nickname=$userInfo['nickname'];
                    $user->save();
                }
            }else{//用户不存在
                $userInfo=$this->getWxUserInfo($info['openid'],$info['access_token']);
                if(isset($userInfo['openid']) && !empty($userInfo['openid'])){
                    $user=User::create([
                        'openId'=>$userInfo['openid'],
                        'unionId'=>$userInfo['unionid'],
                        'nickname'=>$userInfo['nickname'],
                        'name'=>$userInfo['nickname'],
                        'avatar'=>$userInfo['headimgurl'],
                    ]);
                }else{
                    return $this->error('450001','','您未关注微信公众号1');
                }
            }
            $data['token'] = Auth::guard('api')->fromUser($user);
            $dwbsUser = DwbsUser::where('mobile',$user->phone)
                ->where(function($query){
                    $query->where('cert_status',3)
                        ->orWhere('cert_status',6);
                })
                ->where('service_status',0)
                ->first();
            if($dwbsUser){
                $data['is_agent'] = 1;
            }else{
                $data['is_agent'] = 0;
            }
            return $this->success($data);
        }else{
            return $this->error('450001','','您未关注微信公众号2');
        }
    }
    // 获取openid
    public function getUserOpenid($Code){
        $client=new Client();
        $AppId=config('wechat.payment.default.app_id');
        $Secret=config('wechat.payment.default.secret');
        $url='https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$AppId.'&secret='.$Secret.'&code='.$Code.'&grant_type=authorization_code';
        $data=$client->request('get',$url);
        $da=$data->getBody()->getContents();
        $das=json_decode($da,true);
        return (array)$das;
    }
    // 获取微信用户信息
    public function getWxUserInfo($openid,$access_token){
        $client=new Client();
        $url="https://api.weixin.qq.com/sns/userinfo";
        $array=[
            'query' => [
                'access_token' =>$access_token,
                'openid'=>$openid
            ]
        ];
        $data=$client->request('GET',$url,$array);
        $userInfo = json_decode($data->getBody()->getContents(),true);
        return $userInfo;
    }

    public function getUserInfo(Request $request){
        $store_id=$request->input('store_id');
        $user=User::where('id',Auth::user()->id)
            ->select('id','nickname','area_code','phone','openId','unionId','is_vip','status','sex','avatar')
            ->first();
        $vip_log=VipLog::where('user_id',$user->id)->where('store_id',$store_id)->first();
        if($vip_log){
            $user->is_vip=1;
        }else{
            $user->is_vip=0;
        }
        if($user){
            return $this->success($user);
        }else{
            return $this->error();
        }
    }
    //发送验证码
    public function sendSms(Request $request){
        $area_code=$request->input('code');
        $regex=Verify::where('code',$area_code)->value('preg');
        $rules=[
            'phone'=>['required','regex:'.$regex],
        ];
        $message=[
            'phone.required'=>'手机号不能为空.',
            'phone.regex'=>'手机号格式有误.'
        ];
        $validator = Validator::make($request->input(),$rules,$message);
        if($validator->fails()){
            return $this->error('400013',$validator->errors()->first());
        }
        $phone=$request->input('phone');
        $number = new PhoneNumber($phone, $area_code);
        $config=config('easysms');
        $easySms = new EasySms($config);
        $code = mt_rand(100000,999999);
        $minute=5;
        $content="您正在换绑手机号，{$code}为您的更换验证码，请于{$minute}分钟内填写。如非本人操作，请忽略本短信。";
        Cache::put('sms-'.$area_code.'-'.$phone,$code,$minute*60);
        try{
            $easySms->send($number, ['content' =>$content ]);
        } catch (\Overtrue\EasySms\Exceptions\NoGatewayAvailableException $exception) {
            $message = $exception->getException('qcloud')->getMessage();
            return $this->error(40013, $message == null ? '短信发送异常' : $message);
        }
        return $this->success([]);
    }
    //绑定手机号
    public function editSms(Request $request)
    {
        $area_code=$request->input('code');
        $regex=Verify::where('code',$area_code)->value('preg');
        $rules=[
            'phone'=>['required','regex:'.$regex],
            'phone_code'=>'required|size:6',
        ];
        $message=[
            'phone.required'=>'手机号不能为空.',
            'phone.regex'=>'手机号格式有误.',
            'phone_code.required'=>'验证码不能为空.',
            'phone_code.size'=>'验证码为6位字符串.',
        ];
        $validator = Validator::make($request->input(),$rules,$message);
        if($validator->fails()){
            return $this->error('400013',$validator->errors()->first());
        }
        $phone=$request->input('phone');
        $phone_code=$request->input('phone_code');
        $user=User::where('id',Auth::user()->id)->first();//客户当前登录手机号
        if($phone == $user->phone){
            return $this->error('450001','新输入手机号不能与已绑定手机号相同');
        }
        $ph_user=User::where('phone',$phone)->first();//手机号绑定客户信息
        $code= Cache::get('sms-'.$area_code.'-'.$phone);
//        Log::info([$user,$ph_user]);
        if($code==$phone_code){
            $dwbsUser = DwbsUser::where('mobile',$phone)->whereIn('cert_status',[3,6])->where('service_status',0)->first();
            $is_agent=!empty($dwbsUser)?1:0;
            $login=0;
            try{
                DB::transaction(function()use($ph_user,$user,$phone,$code,$area_code,&$login){
                    if(!empty($ph_user)){//手机号已被绑定
                        if(!empty($user->phone)) {//客户已绑定手机号，修改手机号绑定
                            $ph_user->openId=$user->openId;
                            $ph_user->unionId=$user->unionId;
                            $ph_user->save();
                            $user->openId=null;
                            $user->unionId=null;
                            $user->save();
                        }else{
                            if(empty($ph_user->openId) || empty($ph_user->unionId)){
                                throw new ExampleException('该手机号已注册未绑定,是否去合并账号');
                            }else{
                                $ph_user->openId=$user->openId;
                                $ph_user->unionId=$user->unionId;
                                $ph_user->save();
                                $user->delete();
                            }
                        }
                        $login=1;
                    }else{
                        Cache::put('sms-'.$area_code.'-'.$phone,$code,-1);
                        User::where('id',Auth::user()->id)->update(['phone'=>$phone,'area_code'=>$area_code]);
                    }
                });
                $data['is_agent']=$is_agent;
                $data['is_login']=$login;
                return $this->success($data);
            }catch(ExampleException $ee){
                return $this->error('450005',$ee->getMessage());
            }catch(\Exception $e){
                return $this->error('450001',$e->getMessage());
            }
        }else{
            return $this->error('450001','验证码有误');
        }
    }
    //合并用户
    public function mergeUser(Request $request){
        $phone=$request->input('phone');
        $user_id=Auth::user()->id;
        $user=User::where('phone',$phone)->first();
        if(empty($user)){
            return $this->error('450001','该手机号未绑定用户信息');
        }
        if(!empty($user->openId) && !empty($user->unionId)){
            return $this->error('450001','该手机号已被绑定，不能合并');
        }
        try{
            DB::transaction(function()use($user_id,$user){
                $wx_user=User::where('id',$user_id)->first();
                $user->openId=$wx_user->openId;
                $user->unionId=$wx_user->unionId;
                $user->avatar=$wx_user->avatar;
                $user->nickname=$wx_user->nickname;
                $user->name=$wx_user->name;
                $user->save();
                $wx_user->delete();
            },5);
            $token = Auth::guard('api')->fromUser($user);
            return $this->success($token);
        }catch(\Exception $e){
            return $this->error();
        }
    }

    public function getToken(){
        $phone = '715768';
        $user=User::where('id',$phone)
            ->select('id','nickname','area_code','phone','openId','unionId','is_vip','status','sex','avatar')
            ->first();
        $token = Auth::guard('api')->fromUser($user);
        return $this->success($token);
    }
}
