package com.hfkj.channel.gas.shell;

import com.alibaba.fastjson.JSONObject;
import com.hfkj.common.exception.ErrorCode;
import com.hfkj.common.exception.ErrorHelp;
import com.hfkj.common.exception.SysCode;
import com.hfkj.common.utils.DateUtil;
import com.hfkj.common.utils.HttpsUtils;
import com.hfkj.common.utils.MD5Util;
import com.hfkj.config.CommonSysConst;
import org.apache.commons.lang3.StringUtils;

import java.math.BigDecimal;
import java.util.*;

/**
 * 重庆壳牌请求
 * @className: CqShellPetroleumConfig
 * @author: HuRui
 * @date: 2024/7/22
 **/
public class CqShellPetroleumRequestService {

    /**
     * 请求地址
     */
    private final static String REQ_URL = CommonSysConst.getSysConfig().getCqShellReqUrl();
    /**
     * 壳牌合作伙伴id
     */
    private final static String PARTNER_ID = CommonSysConst.getSysConfig().getCqShellPartnerId();
    /**
     * 平台商id
     */
    private final static String PLAT_MERCHANT_ID = CommonSysConst.getSysConfig().getCqShellPlatMerchantId();
    /**
     * 平台商key
     */
    private final static String PLAT_MERCHANT_KEY = CommonSysConst.getSysConfig().getCqShellPlatMerchantKey();

    /**
     * 查询全量加油站
     * @param pageNum   当前页码
     * @param pageSize  每页数据量。最大值50
     * @return
     */
    public static JSONObject gasPageQueryAllStation(Integer pageNum, Integer pageSize) throws Exception {
        Map<String, Object> param = new HashMap<>();
        param.put("platMerchantId", PLAT_MERCHANT_ID);
        param.put("pageNo", pageNum);
        param.put("pageSize", pageSize);
        return request(System.currentTimeMillis()+"","gasPageQueryAllStation", param);
    }

    /**
     * 查询单个油站全量信息
     * @param stationCode   油站编码
     * @return
     */
    public static JSONObject gasStationQueryDetail(String stationCode) {
        try {
            Map<String, Object> param = new HashMap<>();
            param.put("platMerchantId", PLAT_MERCHANT_ID);
            param.put("stationCode", stationCode);
            return request(System.currentTimeMillis()+"","gasStationQueryDetail", param);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 【同步】油站付款
     * @param orderNo      订单号
     * @param stationCode  油站编码
     * @param finishTime   完成时间
     * @param oilPrice     加油金额
     * @param oilCode      油品编码
     * @param oilGun       油枪
     * @param settlementAmount   支付金额
     * @param channelFavourAmount       优惠金额
     * @return
     */
    public static JSONObject gasSyncPayment(String orderNo,
                                     String stationCode,
                                     Date finishTime,
                                     BigDecimal oilPrice,
                                     String oilCode,
                                     String oilGun,
                                     BigDecimal settlementAmount,
                                     BigDecimal channelFavourAmount) throws Exception {
            Map<String, Object> param = new HashMap<>();
            param.put("platMerchantId", PLAT_MERCHANT_ID);
            param.put("stationCode", stationCode);
            param.put("orderType", "OIL");
            param.put("finishTime", DateUtil.date2String(finishTime, "yyyy-MM-dd HH:mm:ss"));
            param.put("channelFavourAmount", channelFavourAmount);

            Map<String, Object> tradeOilOrder = new HashMap<>();
            tradeOilOrder.put("amount", oilPrice);
            tradeOilOrder.put("code", oilCode);
            tradeOilOrder.put("oilGun", oilGun);
            tradeOilOrder.put("channelSettlementAmount", settlementAmount);
            param.put("tradeOilOrder", JSONObject.toJSONString(tradeOilOrder));
            return request(orderNo, "gas_sync_payment_notify", param);
    }

    /**
     * 【同步】油站退款
     * @param finishTime   业务完成时间
     * @param tradeNo      交易流水号
     * @return
     */
    public static JSONObject gasSyncRefund(Date finishTime,String tradeNo) throws Exception {
        Map<String, Object> param = new HashMap<>();
        param.put("platMerchantId", PLAT_MERCHANT_ID);
        param.put("finishTime", DateUtil.date2String(finishTime, "yyyy-MM-dd HH:mm:ss"));
        param.put("tradeNo", tradeNo.replace("HF",""));
        // 请求接口
        return request(System.currentTimeMillis()+"" ,"gas_sync_refund_notify", param);
    }

    /**
     * 接口请求
     * @param map
     * @return
     * @throws Exception
     */
    private static JSONObject request(String logSerialNo, String service, Map<String,Object> map) throws Exception {
        Map<String, Object> param = new HashMap<>();
        param.put("merchantOrderNo", logSerialNo);
        param.put("partnerId", PARTNER_ID);
        param.put("service", service);
        param.put("version", "1.0.0");
        param.put("signType", "MD5");

        for (Map.Entry<String, Object> entry : map.entrySet()) {
            param.put(entry.getKey(), entry.getValue());
        }
        param.put("sign", MD5Util.encode(generateSignature(param, PLAT_MERCHANT_KEY).getBytes()).toLowerCase());
        // 请求接口
        JSONObject response = HttpsUtils.doPost(REQ_URL, param);
        if (response == null || !response.getString("status").equals("SUCCESS")) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, response == null?"请求失败":response.getString("message"));
        }
        return response;
    }

    /**
     * 生成签名
     * @param data  数据
     * @param key   秘钥app_secret
     * @return 加密结果
     */
    public static String generateSignature(final Map<String, Object> data, String key) {
        Set<String> keySet = data.keySet();
        String[] keyArray = keySet.toArray(new String[keySet.size()]);
        Arrays.sort(keyArray);
        StringBuilder sb = new StringBuilder();
        for (String k : keyArray) {
            if (data.get(k) != null) {
                if (StringUtils.isBlank(sb.toString())) {
                    sb.append(k).append("=").append(data.get(k));
                } else {
                    sb.append("&").append(k).append("=").append(data.get(k));
                }
            }
        }
        sb.append(key);
        return sb.toString();
    }

    /**
     * 生成参数
     * @param data  数据
     * @return 加密结果
     */
    public static String generateParam(final Map<String, Object> data) {
        Set<String> keySet = data.keySet();
        String[] keyArray = keySet.toArray(new String[keySet.size()]);
        StringBuilder sb = new StringBuilder();
        for (String k : keyArray) {
            if (data.get(k) != null) {
                if (StringUtils.isBlank(sb.toString())) {
                    sb.append(k).append("=").append(data.get(k));
                } else {
                    sb.append("&").append(k).append("=").append(data.get(k));
                }
            }
        }
        return sb.toString();
    }
}
