package com.fs.pay.pay.util;

import com.fs.common.utils.StringUtils;
import com.fs.common.utils.sign.Md5Utils;
import com.fs.common.utils.spring.SpringUtils;
import com.fs.pay.pay.config.PayConfig;
import com.fs.store.domain.FsPayConfig;
import com.fs.system.domain.SysConfig;
import com.fs.system.mapper.SysConfigMapper;
import com.google.gson.Gson;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;

@SuppressWarnings("all")
public class PayUtil {


    public static String endPayHttp(String url , Map<String,String> map){
        //获取sign
        String sign = sign(map);
        map.put("sign",sign);
        Gson gson = new Gson();
        String json = gson.toJson(map);
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("Content-Type", "application/json");
        StringEntity requestEntity = new StringEntity(json, "UTF-8");
        httpPost.setEntity(requestEntity);
        return  sendHttp(httpPost);
    }

    public static String sendHttp( HttpPost httpPost){
        String responseText=null;
        // 创建HttpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // 发送请求，获取响应
        try {
            CloseableHttpResponse response = httpClient.execute(httpPost);
            // 获取响应实体
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                responseText = EntityUtils.toString(entity, "UTF-8");
            }
            // 关闭响应
            response.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭HttpClient
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return responseText;
    }



    public static String sign(Map<String, String> formData) {
        SysConfigMapper sysConfigMapper= SpringUtils.getBean(SysConfigMapper.class);
        SysConfig sysConfig = sysConfigMapper.selectConfigByConfigKey("store.pay");
        FsPayConfig fsPayConfig = new Gson().fromJson(sysConfig.getConfigValue(), FsPayConfig.class);
        String secretyKey= fsPayConfig.getYbKey();
        if (formData == null) {
            throw new IllegalArgumentException("数据不能为空");
        } else if (formData.isEmpty()) {
            return null;
        } else if (secretyKey == null) {
            throw new IllegalArgumentException("安全校验码数据不能为空");
        } else {
            Map<String, String> sortedMap = new TreeMap(formData);
            if (sortedMap.containsKey("sign")) {
                sortedMap.remove("sign");
            }

            StringBuffer stringToSign = new StringBuffer();
            if (sortedMap.size() > 0) {
                Iterator var4 = sortedMap.entrySet().iterator();

                while(var4.hasNext()) {
                    Map.Entry<String, String> entry = (Map.Entry)var4.next();
                    if (StringUtils.isNotBlank((CharSequence)entry.getValue()) && entry.getValue() != null) {
                        stringToSign.append((String)entry.getKey()).append("=").append((String)entry.getValue()).append("&");
                    }
                }
                stringToSign.deleteCharAt(stringToSign.length() - 1);
            }
            stringToSign.append("&key="+secretyKey);
            String hash = Md5Utils.hash(stringToSign.toString());

            String signature = Md5Utils.hash(stringToSign.toString());

            return signature.toUpperCase();
        }
    }

        public static <T> T GsonFromJson(String json, Class<T> classOfT) {
            Gson gson = new Gson();

            return gson.fromJson(json, classOfT);
        }



    public static boolean isSgin(String s){
        Gson gson = new Gson();
        // 使用Type引用来获取Map类型
        Type type = new com.google.gson.reflect.TypeToken<Map<String, String>>(){}.getType();
        // 将JSON字符串转换为Map对象
        Map<String, String> map = gson.fromJson(s, type);
        String status = map.get("status");
        if (status.equals("101")){
            return true;
        }
        String sign = PayUtil.sign(map);
        String sg = map.get("sign");
        if (sg.equals(sign)){
            return false;
        }
        return true;
    }
}
