package com.game.business.util.other;

import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.game.common.exception.ServiceException;
import com.game.system.service.ISysConfigService;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

public class PayOrderUtils {

    private static final Logger logger = LoggerFactory.getLogger(PayOrderUtils.class);

    private static final String key = "EKCAUP9FWRVGCCR2FVN3WZWVAXAQXINN45IGYD8QKVRYUYWHLRYZRKSOHY0ABEUHEW0SUVMIA1H7UCCKZ2UAC7YIPH5FZCMDPT1FTDUYFKHSU2DB3CJ24FDW97K2YPBP";
/*    private static final String reqUrl = "http://samsunghook.xyz/api/pay/create_order";
    private static final String queryUrl = "http://samsunghook.xyz/api/pay/query_order";*/
    private static final String reqUrl = "http://samsunghook.xyz/api/pay/create_order";
    private static final String queryUrl = "http://samsunghook.xyz/api/pay/query_order";
    private static final String mchId = "20000380";
    private static final String wxCode = "8086";
    private static final String zfbCode = "8085";
    private static final String notifyUrl = "/business/cashrecord/otherCallback";

    public static Map<String, Object> getPayUrl(String orderNo, String payType, Integer amount,String extra){
        ISysConfigService sysConfigService = SpringUtil.getBean(ISysConfigService.class);
        if(null == sysConfigService){
            throw new ServiceException("系统异常");
        }
        String url = sysConfigService.selectConfigByKey("sys_api_url");
        if(StringUtils.isBlank(url)){
            throw new ServiceException("配置缺失");
        }
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("code", 0);
        resultMap.put("mgs", "获取支付地址失败！");
        resultMap.put("data", "");

        SortedMap<String, String> signMap = new TreeMap<>();

        signMap.put("mchId", mchId);
        signMap.put("productId", payType);
        signMap.put("mchOrderNo", orderNo);
        signMap.put("amount", amount.toString());
        signMap.put("currency", "cny");
        signMap.put("notifyUrl", url + notifyUrl);
        signMap.put("subject", "gamesubject");
        signMap.put("body", "gamebody");
        signMap.put("reqTime", System.currentTimeMillis() + "");
        signMap.put("version", "1.0");
        signMap.put("extra", extra);

        Map<String, String> params = SignUtils.paraFilter(signMap);
        StringBuilder buf = new StringBuilder((params.size() +1) * 10);
        SignUtils.buildPayParams(buf, params, false);
        String preStr = buf.toString();

        //获得签名
        String sign = MD5.sign(preStr, "&key=" + key, "utf-8");
        signMap.put("sign", sign);

        HttpPost httpPost = new HttpPost(reqUrl);
        CloseableHttpResponse response;
        CloseableHttpClient client = null;

        try {

            String req = JSON.toJSONString(signMap);
            logger.info("{}请求数据:{}, 请求地址:{}", new Object[]{"getPayUrl", req, reqUrl});

            MultipartEntityBuilder mu = MultipartEntityBuilder.create();
            for (String mapKey : signMap.keySet()){
                StringBody stringBody = new StringBody(MapUtils.getString(signMap, mapKey), ContentType.TEXT_PLAIN);
                mu.addPart(mapKey, stringBody);
            }
            HttpEntity reqEntity = mu.build();
            httpPost.setEntity(reqEntity);

            client = HttpClients.createDefault();
            response = client.execute(httpPost);

            if(response != null && response.getEntity() != null){

                String result = PayHttpUtil.InputStreamTOString(response.getEntity(), "utf-8");
                logger.info("{}返回数据:{}", new Object[]{"getPayUrl", result});

                JSONObject jsonObject = JSON.parseObject(result);
                String code = jsonObject.getString("retCode");
                if(code == null || !code.equals("0")){
                    resultMap.put("code", -1);
                    resultMap.put("msg", "调起通道失败[通道提示：请联系客服！]");
                    return resultMap;
                }

                String payUrl = jsonObject.getString("payUrl");
                if (StringUtils.isNotBlank(payUrl)) {
                    payUrl = payUrl.replaceAll("\\\\" , "");
                }
                resultMap.put("code", 1);
                resultMap.put("data", payUrl);
                return resultMap;
            }else{
                resultMap.put("msg", "调起通道失败[通道提示：请联系客服！]");
            }

        }catch (Exception e){
            logger.info("调起四方接口异常：{}",e);
        }
        return resultMap;
    }

    public static Map<String, Object> getOrderStatus(HttpServletRequest request) {

        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("code", 0);
        resultMap.put("mgs", "订单回调失败！");
        resultMap.put("data", "");
        resultMap.put("tradeNo", "");

        Map<String, Object> params = null;

        String resString;
        try {
            request.setCharacterEncoding("utf-8");
            resString = PayHttpUtil.parseRequst(request);
            logger.info("通知内容：" + resString);

            if (StringUtils.isEmpty(resString)) {
                resString = PayHttpUtil.getParamsFromFormDataByNames(request);
                logger.info("表单通知内容：" + resString);
            }

            params = JSONObject.parseObject(resString, Map.class);

        } catch (UnsupportedEncodingException var16) {
            logger.error("处理订单支付回调】回调解析异常");
            var16.printStackTrace();
            return resultMap;
        }

        String returncode = params.get("status").toString();
        String orderid = params.get("mchOrderNo").toString();
        String tradeNo = params.get("payOrderId").toString();
        resultMap.put("data", orderid);
        resultMap.put("tradeNo", tradeNo);

        if (returncode == null || (!returncode.equals("2") && !returncode.equals("3"))) {
            logger.error("状态错误 ,payOrderId={}, status={}", new Object[]{orderid, returncode});
            return resultMap;
        } else {
            Map<String, String> params1 = SignUtils.paraFilterObjectSign(params);
            if (!SignUtils.checkParam(params1, key)) {
                logger.error("验证签名失败. payOrderId={}, ", new Object[]{orderid});
                return resultMap;
            } else {
                resultMap.put("code", 1);
                resultMap.put("data", orderid);
                resultMap.put("mgs", "订单回调成功！");
                resultMap.put("tradeNo", tradeNo);
                return resultMap;
            }
        }
    }

    public static Map<String, Object> checkOrder(String orderNo, String tradeNo) {

        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("code", 0);
        resultMap.put("mgs", "校验订单失败！");

        SortedMap<String, String> signMap = new TreeMap<>();

        signMap.put("mchId", mchId);
        signMap.put("payOrderId", tradeNo);
        signMap.put("mchOrderNo", orderNo);
        signMap.put("reqTime", System.currentTimeMillis() + "");
        signMap.put("version", "1.0");

        Map<String, String> params = SignUtils.paraFilter(signMap);
        StringBuilder buf = new StringBuilder((params.size() +1) * 10);
        SignUtils.buildPayParams(buf, params, false);
        String preStr = buf.toString();

        //获得签名
        String sign = MD5.sign(preStr, "&key=" + key, "utf-8");
        signMap.put("sign", sign);

        HttpPost httpPost = new HttpPost(queryUrl);
        CloseableHttpResponse response;
        CloseableHttpClient client = null;

        try {

            String req = JSON.toJSONString(signMap);
            logger.info("{}请求数据:{}, 请求地址:{}", new Object[]{"checkOrder", req, reqUrl});

            MultipartEntityBuilder mu = MultipartEntityBuilder.create();
            for (String mapKey : signMap.keySet()){
                StringBody stringBody = new StringBody(MapUtils.getString(signMap, mapKey), ContentType.TEXT_PLAIN);
                mu.addPart(mapKey, stringBody);
            }
            HttpEntity reqEntity = mu.build();
            httpPost.setEntity(reqEntity);

            client = HttpClients.createDefault();
            response = client.execute(httpPost);

            if(response != null && response.getEntity() != null){

                String result = PayHttpUtil.InputStreamTOString(response.getEntity(), "utf-8");
                logger.info("{}返回数据:{}", new Object[]{"checkOrder", result});

                JSONObject jsonObject = JSON.parseObject(result);
                String code = jsonObject.getString("retCode");
                if(code == null || !code.equals("0")){
                    resultMap.put("msg", "调起查询失败[通道提示：请联系客服！]");
                }

                String status = jsonObject.getString("status");
                if("2".equals(status) || "3".equals(status)){
                    resultMap.put("code", 1);
                    resultMap.put("mgs", "校验订单号成功！");
                }
                return resultMap;
            }else{
                resultMap.put("msg", "调起查询失败[通道提示：请联系客服！]");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return resultMap;
    }
}
