<?php

namespace App\Http\Controllers\Wechat;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Ixudra\Curl\Facades\Curl;

class Fans extends Controller
{
    //

    public static function getTotal()
    {
        $openids = array();
        $next_openid = null;
        $i = 0;
        do {
            $http = 'https://api.weixin.qq.com/cgi-bin/user/get?access_token=' . Base::getAccessToken() . '&next_openid=' . $next_openid;
            $result = json_decode(Curl::to($http)->get(), true);
            $openids = array_merge($openids, $result['data']['openid']);
            $next_openid = $result['next_openid'];
            $i += 10000;
        } while ($i < $result['total']);

        return $openids;
    }

    public static function batchGetInfo(array $openids)
    {
        $array = [];
        foreach ($openids as $openid) {
            $array[] = [
                'openid' => $openid
            ];
        }
        $data = array();
        for ($i = 0; $i < count($array); $i += 100) {
            $post = json_encode(['user_list' => array_slice($array, $i, 100)]);
            $http = 'https://api.weixin.qq.com/cgi-bin/user/info/batchget?access_token=' . Base::getAccessToken();
            $result = json_decode(Curl::to($http)->withData($post)->post(), true);
            $data = array_merge($data, $result['user_info_list']);
        }
        return $data;
    }


    public static function getUserInfo(string $openid)
    {
        $http = 'https://api.weixin.qq.com/cgi-bin/user/info?access_token=' . Base::getAccessToken() . '&openid=' . $openid . '&lang=zh_CN';
        $result = json_decode(Curl::to($http)->get(), true);
        if (isset($result['errcode'])) {
            return false;
        }
        return $result;
    }
}
