<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;

class WeiXinController extends Controller
{
    public static function GetAccessToken(){
        $url="https://api.weixin.qq.com/cgi-bin/token";
        $data=[
            "grant_type"=>"client_credential",
            "appid"=>config('app.globals.WxAppid'),
            "secret"=>config('app.globals.WxAppSecret')
        ];
        $token=false;
        $res= self::Get($url,$data);
        if(!isset($res['access_token'])){
            return ['status'=>false,'msg'=>"获取失败",'access_token'=>''];
        }
        $token=$res['access_token'];
        // var_dump($token->access_token);
        $currentDateTime = date('Y-m-d H:i:s'); // 获取当前时间
        $nextHourDateTime = date('Y-m-d H:i:s', strtotime('+1 hour', strtotime($currentDateTime))); // 获取当前时间后1小时的时间
        $data=['value'=>json_encode([
            'value'=>$token,
            'insert_time'=>$currentDateTime,
            'end_time'=>$nextHourDateTime,
        ],JSON_UNESCAPED_UNICODE)] ;
       $u= DB::table('configs')->where('label','AccessToken')->update($data);
       if($u){
           return ['status'=>true,'msg'=>'成功','access_token'=>$token];
       }else{
           return ['status'=>false,'msg'=>'获取access_token失败','access_token'=>''];
       }

    }
    public function SendHouJianNotice()
    {
         $name=request('name');
         $nextClinic=request('nextClinic');
         $waitCount=request('waitCount');
         $itemName=request('itemName');
         $id_number=request('id_number');
         if(!isset($id_number)) return \Yz::echoError1("用户证件号不能为空");
        $info=DB::table('person')->where(['id_number'=> $id_number,'is_del'=>0])->get();
        $res=['status'=>false,'msg'=>"未找到用户信息"];
        if(count($info)>0){
            foreach ($info as $item){ //给所有绑定该身份证的人都发
                $openid=$item->openid;
                $template_id='dMVCm2hNiTZCYRttVSibROud9EiQ1Nj9xW0TnunvHU4';
                $data=[
                    'thing10'=>['value'=>$name],
                    'thing4'=>['value'=>$nextClinic],
                    'character_string7'=>['value'=>$waitCount],
                    'thing9'=>['value'=>mb_substr($itemName, 0, 20, 'UTF-8')]
                ];
                $res=self::SendWxMsg($openid,$template_id,$data);
            }
        }

        return \Yz::Return($res['status'],$res['msg'],['data'=>$res]);
    }
    public static function SendWxMsg($openid,$template_id,$data=[]){
        $access_token_json=DB::table('configs')->where('label','AccessToken')->value('value');
        $access_token_arr=json_decode($access_token_json,true);
        $access_token=false;
        if(!$access_token_arr or $access_token_arr['end_time']<date('Y-m-d H:i:s')){
            $res=self::GetAccessToken();
            if($res['status']){
                $access_token=$res['access_token'];
            }else{
                return ['status'=>false,'msg'=>$res['msg']];
            }
        }else{
            $access_token=$access_token_arr['value'];
        }
        if(!!$access_token){
            $url="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$access_token;
            $send_data=[
                'appid'=>config('app.globals.WxAppid'),
                'touser'=>$openid,
                'template_id'=>$template_id,
                'data'=>$data
            ];
            $res2=self::Post($url,$send_data);
            if($res2['errcode']==0){
                return ['status'=>true,'msg'=>'发送完成'];
            }else{
                return ['status'=>false,'msg'=>$res2['errmsg'],'data'=>$res2];
            }

        }else{
            return ['status'=>false,'msg'=>$res['msg']];
        }

    }
    public static function Get($url,$data=[])
    {
        $response = Http::get($url,$data);
        if ($response->successful()) {
            $res = $response->json();
            return $res;
        }else{

        }

    }
    public static function Post($url,$data=[])
    {
        $response = Http::post($url,$data);
        if ($response->successful()) {
            $res = $response->json();

            return $res;
        }else{

        }

    }
}
