package com.tzy.s.wx.common;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.tzy.s.wx.user.*;
import com.tzy.s.wx.util.HttpClient;
import com.tzy.s.wx.util.ListUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 用户管理
 */
@Slf4j
public class UserManageApi {
    private static int index = 0;
    private static int endidx = 0;
    private static List<UserInfo> userInfoList = new ArrayList<UserInfo>();

    //获取用户列表接口
    //1.next_openid 不传值 默认从开始拉取 ，一次最多拉取10000个
    //2. 超过10000个关注用户 next_openid 传 上一次拉取结果返回的 next_openid 的值
    private static String getUserList_uri = "https://api.weixin.qq.com/cgi-bin/user/get?access_token={0}&next_openid={1}";
    //获取用户信息 -- 单条
    private static String getUserInfo_uri = "https://api.weixin.qq.com/cgi-bin/user/info?access_token={0}&openid={1}&lang=zh_CN";
    //获取用户信息 列表  -- 多条
    //1.最多支持一次拉取100条
    private static String getUserInfoList_uri = "https://api.weixin.qq.com/cgi-bin/user/info/batchget?access_token={0}";

    /**
     * 获取用户列表、、获取openid列表
     * @param accessToken
     * @return
     */
    private static OpenidsResult getUserList(String accessToken, String openid){
//        System.out.println(" next openid 22>>> "+openid);
        OpenidsResult result = new OpenidsResult();
        String url = MessageFormat.format(getUserList_uri, accessToken, openid);
        String ret = HttpClient.httpsRequest(url, "GET", null);
        if(StringUtils.isNotEmpty(ret)) {
            JSONObject retJson = JSONObject.parseObject(ret);
            result = JSONObject.toJavaObject(retJson, OpenidsResult.class);
            if (null != result && null != result.getData() && null != result.getData().getOpenid()) {
                openids.getOpenid().addAll(result.getData().getOpenid());
                openids.setOpenid(ListUtil.removeDuplicate(openids.getOpenid()));
            }
            System.out.println(" all user by openid size >>> " + openids.getOpenid().size());
            if (null == result) {
                result.setErrcode(-1);
                result.setErrmsg("请求异常");
            } else if (StringUtils.isNotEmpty(result.getNext_openid()) && result.getCount() == 10000) {
                getUserList(accessToken, result.getNext_openid());
            } else if (null == result.getErrcode()) {
                result.setErrcode(0);
                result.setErrmsg("请求成功");
            }
        }
        return result;
    }

    private static Openids openids = new Openids();
    /**
     * 获取用户信息 -- 单条
     * @param accessToken
     * @param openid
     * @return
     */
    public static UserInfoResult getUserInfo(String accessToken , String openid){
        UserInfoResult result = new UserInfoResult();
        String url = MessageFormat.format(getUserInfo_uri, accessToken, openid);
        String ret = HttpClient.httpsRequest(url, "GET", null);
        if(StringUtils.isNotEmpty(ret)) {
            JSONObject retJson = JSONObject.parseObject(ret);
            UserInfo userInfo = JSONObject.toJavaObject(retJson, UserInfo.class);
//            UserInfo userInfo = JSonUtils.toBean(jsonObject.toJSONString(), UserInfo.class);
            if (null != userInfo && StringUtils.isNotEmpty(userInfo.getOpenid())) {
                userInfoList = new ArrayList<UserInfo>();
                userInfoList.add(userInfo);
                result.setErrcode(0);
                result.setErrmsg("请求成功");
                result.setUser_info_list(userInfoList);
                return result;
            }
        }
        return result;
    }

    public static OpenidsResult getAllUserList(String accessToken){
        String url = MessageFormat.format(getUserList_uri, accessToken, "");
        String ret = HttpClient.httpsRequest(url, "GET", null);
        OpenidsResult result = new OpenidsResult();
        if(StringUtils.isNotEmpty(ret)) {
            JSONObject retJson = JSONObject.parseObject(ret);
            result = JSONObject.toJavaObject(retJson, OpenidsResult.class);
//            result = JSonUtils.toBean(jsonObject.toJSONString(), OpenidsResult.class);
            System.out.println(" next openid 111>>> " + result.getNext_openid());
            System.out.println(" errcode >> " + (null == result.getErrcode()));
            if (null == result) {
                result.setErrcode(-1);
                result.setErrmsg("请求异常");
            } else if (StringUtils.isNotEmpty(result.getNext_openid()) && 10000 == result.getCount()) {
                openids = new Openids();
                openids.setOpenid(ListUtil.removeDuplicate(result.getData().getOpenid()));
                getUserList(accessToken, result.getNext_openid());
                result.getData().setOpenid(openids.getOpenid());
                result.setTotal(openids.getOpenid().size());//openids 总数量
            } else if (null == result.getErrcode() ) {
                result.setErrcode(0);
                result.setErrmsg("请求成功");
            }
        }
        return result;
    }

    /**
     * 获取用户信息 -- 列表
     * @param accessToken
     * @param openids
     * @return
     */
    private static int userSize = 0;
    public static UserInfoResult getUserInfo(String accessToken , List<String> openids){
        UserInfoResult result = new UserInfoResult();
        UserInfoList userInfos =  new UserInfoList();
        //组装参数
        if(null == openids || openids.size() == 0){
            result.setErrcode(-1);
            result.setErrmsg("用户openid为空");
            return result;
        }
        if(endidx == 0 && userSize > 100){
            endidx = 100;
        }else
        if(userSize < 100){
            endidx = userSize;
        }
        List<Map<String,String >> userlist = new ArrayList<>();
        for(int i = index ;i < endidx ;i++ ){
            Map<String ,String> params = new HashMap<>();
            params.put("openid",openids.get(i));
            params.put("lang","zh_CN");
            userlist.add(params);
        }
        JSONArray jsonArray = JSONArray.parseArray(JSONArray.toJSONString(userlist));
        if(null == jsonArray){
            result.setErrcode(-1);
            result.setErrmsg("系统异常,请联系管理员");
            return result ;
        }
        JSONObject user_list = new JSONObject();
        user_list.put("user_list", jsonArray);
        String url = MessageFormat.format(getUserInfoList_uri, accessToken, "");
        String ret = HttpClient.httpsRequest(url, "POST", user_list.toJSONString());
//        log.info("ret>>>"+ret);
//        JSONObject jsonObject = HttpClientUtils.doPost(MessageFormat.format(getUserInfoList_uri,accessToken),JSONObject.toJSON(user_list));
        if(StringUtils.isNotEmpty(ret)) {
            JSONObject retJson = JSONObject.parseObject(ret);
            result = JSONObject.toJavaObject(retJson, UserInfoResult.class);
//            result = JSonUtils.toBean(jsonObject.toJSONString(), UserInfoResult.class);
        }
        if(null != result){
            JSONObject retJson = JSONObject.parseObject(ret);
            userInfos = JSONObject.toJavaObject(retJson,UserInfoList.class);
        }else{ //如果为 空 返回数据
            return result;
        }
        if(userSize > endidx){
            index = index + 100;
            endidx = endidx + 100;
            if(endidx > userSize ){
                endidx = userSize ;
            }
            if(null == userInfoList  ){
                if(null != userInfos.getUser_info_list()){
                    userInfoList = new ArrayList<>();
                }else{
                    userInfoList = userInfos.getUser_info_list();
                }
            } else {
                if(null != userInfos.getUser_info_list()){
                    userInfoList.addAll(userInfos.getUser_info_list());
//                    userInfoList = ListUtil.removeDuplicate(userInfoList);
//                    userInfoList = new ListUtil().removeDuplicateBean(userInfoList);
                    userInfoList = userInfoList.stream().filter(ListUtil.distinctByKey(UserInfo::getOpenid)).collect(Collectors.toList());
                }
            }
//            System.out.println("  get user info at  >>> "+endidx);
            getUserInfo(accessToken , openids);
        }
        if(null != userInfos.getUser_info_list()){
            userInfoList.addAll(userInfos.getUser_info_list());
//            userInfoList = new ListUtil().removeDuplicateBean(userInfoList);
            userInfoList = userInfoList.stream().filter(ListUtil.distinctByKey(UserInfo::getOpenid)).collect(Collectors.toList());
//            userInfoList = ListUtil.removeDuplicate(userInfoList);
        }
        if(null != userInfoList){
            result.setErrcode(0);
            result.setErrmsg("请求成功");
            result.setUser_info_list(userInfoList);
            return result;
        }
        return result;
    }

    /**
     * 获取该公众号下的所有用户的基本信息 - all
     * @param accessToken
     * @return
     */
    public static UserInfoResult getAllUserInfos(String accessToken){
        index = 0;
        endidx = 0;
        userInfoList = new ArrayList<UserInfo>();
        UserInfoResult userInfo = new UserInfoResult();
        OpenidsResult userList = getAllUserList(accessToken);
        if(null != userList && userList.isSuccess()){
            Openids data = userList.getData();
            if(null != data && null != data.getOpenid() && data.getOpenid().size() > 0){
                userSize = data.getOpenid().size();
                System.out.println(" all user size >>>"+userSize);
                userInfo  = getUserInfo(accessToken, data.getOpenid());

            }
        }else if(null != userList && !userList.isSuccess()){
            userInfo.setErrcode(userList.getErrcode());
            userInfo.setErrmsg(userList.getErrmsg());
        }
        return userInfo;
    }

    /**
     * 根据openid 验证是否关注
     * @param accessToken
     * @param openid
     * @return
     */
    public static int checkSubscribe(String accessToken,String openid ){
        String url = MessageFormat.format(getUserInfoList_uri, accessToken, openid);
        String ret = HttpClient.httpsRequest(url, "GET", null);
//        JSONObject jsonObject = HttpClientUtils.doGet(MessageFormat.format(getUserInfo_uri,accessToken,openid));
        if(StringUtils.isNotEmpty(ret)) {
            JSONObject retJson = JSONObject.parseObject(ret);
            UserInfo userInfo = JSONObject.toJavaObject(retJson, UserInfo.class);
//            UserInfo userInfo = JSonUtils.toBean(jsonObject.toJSONString(), UserInfo.class);
            if (null != userInfo && userInfo.getErrcode() == 0) {
                return userInfo.getSubscribe();
            }else{
                return userInfo.getErrcode();
            }
        }
        return 0;
    }


}
