<?php

namespace App\Http\Controllers\API\H5;

use App\Http\Controllers\Controller;
use App\Services\Login\LoginService;
use App\Services\PersonService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class LoginController extends Controller
{
    public function H5Login()
    {
        $LoginStatus=false;
        $openid =request('openid');
        $appid =request('appid');
        if(isset($appid)){
           $app= DB::table('y_app')->where(['app_id'=>$appid,'status'=>1,'is_del'=>0])->get();
              if(count($app)==0){
                return \Yz::echoError1('未找到有效应用');
              }
        }else{
            return \Yz::echoError1('缺失参数appid');
        }
        if(isset($openid)){
            $person=new PersonService();
            $c= $person->checkRegister(['openid'=>$openid]);
            $Login= new LoginService();
            $userid=0;
            if($c[0]){  //判断是否注册过
                $userid=$c[1];
            }else{
                //未注册自动注册
                $userid=DB::table('persons')->insertGetId([
                    'openid' => $openid,
                    'status'=>1,
                    'app_id'=>$appid
                ]);
            }
            $token_info= $Login->MianMiLogin($userid,$appid);
            $LoginStatus=  DB::table('persons')->where(['openid'=>$openid,'status'=>1])->update(['token'=>md5($token_info['data']['refresh_token'])]);
            if($LoginStatus) {
                return \Yz::Return(true, '登录成功', $token_info['data']);
            }else{
                return \Yz::echoError1('登录失败');
            }
        }else{
            return \Yz::echoError1('缺失参数');
        }


    }
}
