package com.hfkj.channel.hsg;

import com.alibaba.fastjson.JSONObject;
import com.hfkj.channel.hsg.config.HsgConfig;
import com.hfkj.channel.hsg.type.RebateProductTypeEnum;
import com.hfkj.channel.weixin.utils.WxUtils;
import com.hfkj.channel.weixin.utils.sdk.WXPayConstants;
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.ResponseMsgUtil;
import io.netty.channel.ConnectTimeoutException;
import org.apache.commons.collections4.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.math.BigDecimal;
import java.net.SocketTimeoutException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @className: HsgService
 * @author: HuRui
 * @date: 2023/4/27
 **/
public class HsgIntegralService {

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

    /**
     * 积分返利
     * @param productType
     * @param phone
     * @param orderNo
     * @param orderId
     * @param price
     * @param storeName
     * @param createTime
     * @return
     * @throws Exception
     */
    public static Boolean rebate(RebateProductTypeEnum productType,
                                String phone,
                                String orderNo,
                                Long orderId,
                                BigDecimal price,
                                String storeName,
                                Date createTime) {
        log.info("========== start 积分返利 ===========");
        String requestJSON = "";

        try {
            Map<String , Object> mapPost = new HashMap<>();
            mapPost.put("merchId" , HsgConfig.merchId);
            mapPost.put("productType" , productType.getNumber()); // 101 普通支付  102 商家活动差价返利
            mapPost.put("orderNo" , orderNo);
            mapPost.put("phone" , phone);
            mapPost.put("orderId" , orderId);
            mapPost.put("price" , price);
            mapPost.put("title" , storeName);
            mapPost.put("createTime" , createTime);
            mapPost.put("sign" , WxUtils.generateSignApi(mapPost, HsgConfig.apiKey, WXPayConstants.SignType.MD5));

            requestJSON = JSONObject.toJSONString(mapPost);
            log.info("请求参数：" + requestJSON);
            JSONObject response = HttpsUtils.doPost(HsgConfig.hsgDomainName+"v1/orderRebate/rebate", mapPost, new HashMap<>());
            log.info("响应参数：" + response);
            if (response == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "请求超时");
            }
            if (!response.getString("return_code").equals("000000")) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, response.getString("return_msg"));
            }
            return true;

        } catch (SocketTimeoutException | ConnectTimeoutException e) {
            log.info("请求超时：" + e);
            return false;
        } catch (Exception e) {
            log.info("出现异常：" + e);
            return false;
        } finally {
            log.info("========== end 积分返利 ===========");
        }
    }

    /**
     * 退款返利
     * @param orderId
     * @param orderNo
     * @return
     */
    public static Boolean recycleIntegral(String orderId,String orderNo) {
        log.info("========== start 退款返利 ===========");
        String requestJSON = "";
        try {
            Map<String , Object> mapPost = new HashMap<>();
            mapPost.put("merchId" , HsgConfig.merchId);
            mapPost.put("orderId" , orderId);
            mapPost.put("orderNo" , orderNo);
            mapPost.put("sign" , WxUtils.generateSignApi(mapPost, HsgConfig.apiKey, WXPayConstants.SignType.MD5));

            requestJSON = JSONObject.toJSONString(mapPost);
            log.info("请求参数：" + requestJSON);
            JSONObject response = HttpsUtils.doPost(HsgConfig.hsgDomainName+"v1/orderRebate/recycleIntegral", mapPost, new HashMap<>());
            log.info("响应参数：" + response.toJSONString());

            if (response == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "请求超时");
            }
            if (!response.getString("return_code").equals("000000")) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, response.getString("return_msg"));
            }
            return true;

        } catch (SocketTimeoutException | ConnectTimeoutException e) {
            log.info("请求超时：" + e);

            return false;
        } catch (Exception e) {
            log.info("出现异常：" + e);
            return false;
        } finally {
            log.info("========== end 退款返利 ===========");
        }
    }

    /**
     * 通知退还积分状态
     * @param orderId
     * @param orderNo
     * @return
     */
    public static Boolean refundReturn(String orderId,String orderNo, Boolean status) {
        log.info("========== start 通知退还积分状态 ===========");
        String requestJSON = "";
        try {
            Map<String , Object> mapPost = new HashMap<>();
            mapPost.put("merchId" , HsgConfig.merchId);
            mapPost.put("orderId" , orderId);
            mapPost.put("orderNo" , orderNo);
            mapPost.put("refundStatus" , status.equals(true)?"succeed":"fail");
            mapPost.put("sign" , WxUtils.generateSignApi(mapPost, HsgConfig.apiKey, WXPayConstants.SignType.MD5));

            requestJSON = JSONObject.toJSONString(mapPost);
            log.info("请求参数：" + requestJSON);
            JSONObject response = HttpsUtils.doPost(HsgConfig.hsgDomainName+"v1/orderRebate/refundReturn", mapPost, new HashMap<>());
            log.info("响应参数：" + response.toJSONString());

            if (response == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "请求超时");
            }
            if (!response.getString("return_code").equals("000000")) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, response.getString("return_msg"));
            }
            return true;

        } catch (SocketTimeoutException | ConnectTimeoutException e) {
            log.info("请求超时：" + e);
            return false;
        } catch (Exception e) {
            log.info("出现异常：" + e);
            return false;
        } finally {
            log.info("========== end 通知退还积分状态 ===========");
        }
    }


}
