package com.hfkj.yushang;

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.HttpsUtils;
import com.hfkj.common.utils.MD5Util;
import com.hfkj.config.CommonSysConst;
import com.hfkj.config.GenerateSign;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;
import java.util.Map;

public class YuShangService {

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

    /**
     * @MethodName insertV2
     * @Description: 直充订单提交接口
     * @param map
     * @return: com.alibaba.fastjson.JSONObject
     * @Author: Sum1Dream
     * @Date: 2024/9/5 下午2:17
     */
    public static JSONObject insertV2(Map<String , Object> map) throws Exception {

        JSONObject object = request("/Order/InsertV2" , map);

        if ( object.getInteger("Code") == 999) {
            return object;
        } else {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "请求失败！");
        }

    }

    /**
     * @MethodName queryV2
     * @Description: 订单查询接口
     * @param map 
     * @return: com.alibaba.fastjson.JSONObject
     * @Author: Sum1Dream
     * @Date: 2024/9/5 下午2:29
     */
    public static JSONObject queryV2(Map<String , Object> map) throws Exception {

        JSONObject object = request("Order/QueryV2" , map);

        if ( object.getInteger("Code") == 999) {
            return object;
        } else {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "请求失败！");
        }

    }

    /**
     * 请求
     * @param postUrl  接口请求地址
     * @param param       参数
     * @return
     * @throws Exception
     */
    public static JSONObject request(String postUrl, Map<String,Object> param) throws Exception {

        log.info("============ 娱尚请求-START =============");
        param.put("AppKey", CommonSysConst.getSysConfig().getYuShangAppKey());
        param.put("timestamp", new Date().getTime());
        param.put("CustomerIP", "127.0.0.1");
        param.put("sign", MD5Util.encode(GenerateSign.paramSortYuShang(param,CommonSysConst.getSysConfig().getYuShangAppSecret()).getBytes()).toLowerCase());

        log.info("请求接口：" + postUrl);
        log.info("请求参数：" + JSONObject.toJSONString(param));

        JSONObject response = HttpsUtils.doPost(CommonSysConst.getSysConfig().getYuShangPostUrl()+ postUrl, JSONObject.toJSONString(param));

        log.info("响应参数：" + response.toJSONString());
        log.info("============ 娱尚请求-END ==============");
        return response;

    }


}
