package com.malk.kabeiyi.util;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.malk.server.common.McR;
import com.malk.server.common.VenR;
import com.malk.utils.UtilHttp;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.HashMap;
import java.util.Map;



@Slf4j
public class U8Util {



    public static String FROM_ACCOUNT = "kbeapi";
    public static String TO_ACCOUNT = "kbeapi";
    public static String APP_KEY = "opa52c74dd3e0563458";
    public static String APP_SECRET = "5b96fad7470a489bbae369ec79406fb1";
    public static String APP_TOKEN = "";

    public static String getToken()throws Exception{
        HashMap<String, Object> paramMap = new HashMap();
        paramMap.put("from_account", FROM_ACCOUNT);
        paramMap.put("app_key", APP_KEY);
        paramMap.put("app_secret", APP_SECRET);
        String result= HttpUtil.get("https://api.yonyouup.com/system/token", paramMap);
        System.out.println(result);
        Map map = (Map) JSONObject.parse(result);
        Map resultMap = (Map) map.get("token");
        APP_TOKEN = String.valueOf(resultMap.get("id"));
        return APP_TOKEN;

    }

    public static String getTradeid()throws Exception{
        HashMap<String, Object> param = new HashMap();
        Map resultMap = sendGetNoToAc(param,"https://api.yonyouup.com/system/tradeid","trade");
        return String.valueOf(resultMap.get("id"));
    }

    public static Map sendGet(Map paramMap, String url,String key)throws Exception{
        paramMap.put("to_account", TO_ACCOUNT);
        return sendGetNoToAc(paramMap,url,key);
    }

    public static Map sendGetNoToAc(Map paramMap, String url,String key)throws Exception{
        log.info("发送数据：{}",paramMap);
        Map data=new HashMap();
        data.putAll(paramMap);
        paramMap.put("from_account", FROM_ACCOUNT);
        paramMap.put("app_key", APP_KEY);
        paramMap.put("token", APP_TOKEN);
        String result= HttpUtil.get(url, paramMap);
        Map map = (Map) JSONObject.parse(result);
        log.info("接口返回值：{}",map);
        String errcode=String.valueOf(map.get("errcode"));
        if("0".equals(errcode)){
            if("batch".equals(key)){
                return map;
            }else{
                Map resultMap= (Map) JSONObject.parse(String.valueOf(map.get(key)));
                return resultMap;
            }
        }else if(errcode.equals("10004")||errcode.equals("30011")||errcode.equals("30012")){
            log.info("错误信息：【{}】",map.get("errmsg"));
            log.info("重新获取token");
            getToken();
            log.info("重新调用接口...");
            return sendGet(data,url,key);
        }else{
            log.info("错误信息：【{}】",map.get("errmsg"));
            return null;
        }
    }

    public static McR sendPost(Map paramMap, String url, String key)throws Exception{
        log.info("发送数据：{}",paramMap);
        Map data=new HashMap();
        data.put("from_account", FROM_ACCOUNT);
        data.put("to_account", TO_ACCOUNT);
        data.put("app_key", APP_KEY);
        data.put("token", APP_TOKEN);
        if(paramMap.containsKey("tradeid")){
            data.put("tradeid", paramMap.get("tradeid"));
            data.put("sync",1);// 0=异步新增（默认）;1=同步新增;
            paramMap.remove("tradeid");
        }
        Map bodyMap=new HashMap();
        bodyMap.put(key,paramMap);
        String body=JSONObject.toJSONString(bodyMap);
        String result= post(url,data,body);
        Map map = (Map) JSONObject.parse(result);
        log.info("接口返回值：{}",map);
        String errcode=String.valueOf(map.get("errcode"));
        if("0".equals(errcode)){
            return McR.success(String.valueOf(map.get("id")));
        }else if(errcode.equals("10004")||errcode.equals("30011")||errcode.equals("30012")){
            log.info("错误信息：【{}】",map.get("errmsg"));
            log.info("重新获取token");
            getToken();
            log.info("重新调用接口...");
            return sendPost(data,url,key);
        }else{
            log.info("错误信息：【{}】",map.get("errmsg"));
            return McR.error(String.valueOf(map.get("errcode")),String.valueOf(map.get("errmsg")));

        }

    }


    /***
     * 获取随机数
     * @param args1 长度
     * @param args2 1 字母  2 数字
     * @return
     */

    public static String RANDOM(int args1, String args2) {
        if (StringUtils.isEmpty(args2)) {
            throw new RuntimeException("RANDOM");
        } else {
            args2 = StringUtils.trim(args2);
            if (StringUtils.equals(args2, "0")) {
                return RandomStringUtils.randomAlphanumeric(args1);
            } else {
                return StringUtils.equals(args2, "1") ? RandomStringUtils.randomAlphabetic(args1) : RandomStringUtils.randomNumeric(args1);
            }
        }
    }



    public static String post(String url,Map<String,Object> paramMap, String body)throws Exception {
        String newUrl = url;
        StringBuffer param = new StringBuffer();
        for (String key : paramMap.keySet()) {
            param.append(key + "=" + paramMap.get(key).toString() + "&");
        }
        String paramStr = param.toString();
        paramStr = paramStr.substring(0, paramStr.length() - 1);
        if (newUrl.indexOf("?") >= 0) {
            newUrl += "&" + paramStr;
        } else {
            newUrl += "?" + paramStr;
        }
        return HttpUtil.post(newUrl, body);

    }





}