package com.hai.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hai.common.pay.util.sdk.WXPayConstants;
import com.hai.common.utils.HttpsUtils;
import com.hai.common.utils.MD5Util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;

/**
 * 团油请求
 */
public class TuanYouConfig {

    private static final Logger log = LoggerFactory.getLogger(TuanYouConfig.class);


    /**
     * 分页获取(全量)油站信息
     * @param pageIndex 页数
     * @param pageSize  单页数据量，最大 3000
     * @return 请求结果
     * @throws Exception
     */
    public static JSONObject queryGasInfoListByPage(Integer pageIndex,Integer pageSize) throws Exception {
        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("app_key", CommonSysConst.getSysConfig().getTuanYouAppKey());
        paramMap.put("timestamp", new Date().getTime());
        paramMap.put("pageIndex", pageIndex);
        paramMap.put("pageSize", pageSize);
        paramMap.put("sign", MD5Util.encode(generateTuanYouSignature(paramMap,CommonSysConst.getSysConfig().getTuanYouAppSecret()).getBytes()).toLowerCase());
        return HttpsUtils.doPost(CommonSysConst.getSysConfig().getTuanYouUrl()+"/services/vp/openapi/queryGasInfoListByPage", JSON.toJSONString(paramMap));
    }

    /**
     * 根据油站 id 拉取最新的油站数据
     * @param gasId 油站 ID
     * @return 请求结果
     * @throws Exception
     */
    public static JSONObject queryGasInfoByGasId(String gasId) throws Exception {
        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("app_key", CommonSysConst.getSysConfig().getTuanYouAppKey());
        paramMap.put("timestamp", new Date().getTime());
        paramMap.put("gasId", gasId);
        paramMap.put("sign", MD5Util.encode(generateTuanYouSignature(paramMap,CommonSysConst.getSysConfig().getTuanYouAppSecret()).getBytes()).toLowerCase());
        return HttpsUtils.doPost(CommonSysConst.getSysConfig().getTuanYouUrl()+"/services/vp/openapi/queryGasInfoByGasId", JSON.toJSONString(paramMap));
    }

    /**
     * 查询油站，某油号实时价格
     * @param gasId 加油站id
     * @param oilNo 油号id
     * @return 请求结果
     * @throws Exception
     */
    public static JSONObject queryCompanyPriceDetail(String gasId,String oilNo) throws Exception {
        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("app_key", CommonSysConst.getSysConfig().getTuanYouAppKey());
        paramMap.put("timestamp", new Date().getTime());
        paramMap.put("gasId", gasId);
        paramMap.put("oilNo", oilNo);
        paramMap.put("sign", MD5Util.encode(generateTuanYouSignature(paramMap,CommonSysConst.getSysConfig().getTuanYouAppSecret()).getBytes()).toLowerCase());
        return HttpsUtils.doPost(CommonSysConst.getSysConfig().getTuanYouUrl()+"/services/vp/openapi/queryCompanyPriceDetail", JSON.toJSONString(paramMap));
    }

    /**
     * 推送订单
     * @param map
     * @return 请求结果
     * @throws Exception
     */
    public static JSONObject refuelingOrderPush(Map<String,Object> map) throws Exception {
        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("app_key", CommonSysConst.getSysConfig().getTuanYouAppKey());
        paramMap.put("timestamp", new Date().getTime());
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            paramMap.put(entry.getKey(), entry.getValue().toString());
        }
        paramMap.put("sign", MD5Util.encode(generateTuanYouSignature(paramMap,CommonSysConst.getSysConfig().getTuanYouAppSecret()).getBytes()).toLowerCase());
        return HttpsUtils.doPost(CommonSysConst.getSysConfig().getTuanYouUrl()+"/services/vp/openapi/refuelingOrderPush", JSON.toJSONString(paramMap));
    }

    /**
     * 订单退款
     * @param driverPhone 司机手机号
     * @param thirdSerialNo 三方订单号
     * @param refundReason  退款原因
     * @return 请求结果
     * @throws Exception
     */
    public static JSONObject refuelingOrderRefund(String driverPhone,String thirdSerialNo,String refundReason) throws Exception {
        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("app_key", CommonSysConst.getSysConfig().getTuanYouAppKey());
        paramMap.put("timestamp", new Date().getTime());
        paramMap.put("driverPhone", driverPhone);
        paramMap.put("thirdSerialNo", thirdSerialNo);
        paramMap.put("refundReason", refundReason);
        paramMap.put("sign", MD5Util.encode(generateTuanYouSignature(paramMap,CommonSysConst.getSysConfig().getTuanYouAppSecret()).getBytes()).toLowerCase());
        return HttpsUtils.doPost(CommonSysConst.getSysConfig().getTuanYouUrl()+"/services/vp/openapi/refuelingOrderRefund", JSON.toJSONString(paramMap));
    }

    /**
     * queryCompanyAccountBalance
     * @return 企业余额查询（多能源类型）
     * @throws Exception
     */
    public static JSONObject queryCompanyAccountInfo2JD() throws Exception {
        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("app_key", CommonSysConst.getSysConfig().getTuanYouAppKey());
        paramMap.put("timestamp", new Date().getTime());
        paramMap.put("companyCode", CommonSysConst.getSysConfig().getTuanYouAppKey());
        paramMap.put("sign", MD5Util.encode(generateTuanYouSignature(paramMap,CommonSysConst.getSysConfig().getTuanYouAppSecret()).getBytes()).toLowerCase());
        return HttpsUtils.doPost(CommonSysConst.getSysConfig().getTuanYouUrl()+"/services/vp/openapi/queryCompanyAccountInfo2JD", JSON.toJSONString(paramMap));
    }

    /**
     * 订单结果查询
     * @param thirdSerialNo 三方订单号
     * @return 请求结果
     * @throws Exception
     */
    public static JSONObject queryThirdOrderDetail(String thirdSerialNo) throws Exception {
        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("app_key", CommonSysConst.getSysConfig().getTuanYouAppKey());
        paramMap.put("timestamp", new Date().getTime());
        paramMap.put("companyCode", CommonSysConst.getSysConfig().getTuanYouAppKey());
        paramMap.put("thirdSerialNo", thirdSerialNo);
        paramMap.put("sign", MD5Util.encode(generateTuanYouSignature(paramMap,CommonSysConst.getSysConfig().getTuanYouAppSecret()).getBytes()).toLowerCase());
        return HttpsUtils.doPost(CommonSysConst.getSysConfig().getTuanYouUrl()+"/services/vp/openapi/queryThirdOrderDetail", JSON.toJSONString(paramMap));
    }

    /**
     * 订单列表查询
     * @param companyCode 公司 code  AppKey
     * @param startTime 查询开始时间 2018-11-30 12:28:55
     * @param endTime   查询结束时间 2018-11-30 16:28
     * @param page      页码（缺省默认 1）
     * @param rows      每页记录行数（缺省默认 20）最大值 200
     * @param orderPayFlag 订单状态 未支付:1, 已支付:3, 退款中:5, 已退款:6,退款失败:7;
     * @return
     * @throws Exception
     */
    public static JSONObject queryOrderInfoList(String companyCode,String startTime,String endTime,Integer page,Integer rows,Integer orderPayFlag) throws Exception {
        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("app_key", CommonSysConst.getSysConfig().getTuanYouAppKey());
        paramMap.put("timestamp", new Date().getTime());
        paramMap.put("companyCode", companyCode);
        paramMap.put("startTime", startTime);
        paramMap.put("endTime", endTime);
        if (page != null) {
            paramMap.put("page", page);
        }
        if (rows != null) {
            paramMap.put("rows", rows);
        }
        if (orderPayFlag != null) {
            paramMap.put("orderPayFlag", orderPayFlag);
        }
        paramMap.put("sign", MD5Util.encode(generateTuanYouSignature(paramMap,CommonSysConst.getSysConfig().getTuanYouAppSecret()).getBytes()).toLowerCase());
        return HttpsUtils.doPost(CommonSysConst.getSysConfig().getTuanYouUrl()+"/services/vp/openapi/queryOrderInfoList", JSON.toJSONString(paramMap));
    }

    /**
     * 上汽油站下单结果查询
     * @param thirdSerialNo 三方订单号
     * @return
     * @throws Exception
     */
    public static JSONObject loopShangQiOrder(String thirdSerialNo) throws Exception {
        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("app_key", CommonSysConst.getSysConfig().getTuanYouAppKey());
        paramMap.put("timestamp", new Date().getTime());
        paramMap.put("thirdSerialNo", thirdSerialNo);
        paramMap.put("sign", MD5Util.encode(generateTuanYouSignature(paramMap,CommonSysConst.getSysConfig().getTuanYouAppSecret()).getBytes()).toLowerCase());
        return HttpsUtils.doPost(CommonSysConst.getSysConfig().getTuanYouUrl()+"/services/vp/openapi/loopShangQiOrder", JSON.toJSONString(paramMap));
    }

    /**
     * 生成签名
     * @param data  数据
     * @param key   秘钥app_secret
     * @return 加密结果
     */
    public static String generateTuanYouSignature(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();
        sb.append(key);
        for (String k : keyArray) {
            if (k.equals(WXPayConstants.FIELD_SIGN)) {
                continue;
            }
            if (data.get(k) != null) // 参数值为空，则不参与签名
                sb.append(k).append(data.get(k));
        }
        sb.append(key);
        return sb.toString();
    }



}
