package com.jsowell.thirdparty.ruanjie.service.impl;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.jsowell.common.util.sign.MD5Util;
import com.jsowell.pile.dto.ruanjie.UseCouponDTO;
import com.jsowell.thirdparty.lutongyunting.service.impl.LTYTServiceImpl;
import com.jsowell.thirdparty.ruanjie.service.RJService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.Locale;
import java.util.TreeMap;

/**
 * TODO
 *
 * @author Lemon
 * @Date 2023/9/22 8:46
 */
@Service
public class RJServiceImpl implements RJService {

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

    private static final String BASE_URL = "https://redpay.ruanjiesh.com/ThirdAPI";

    private static final String SECRET_KEY = "ced9ar3ingZ";

    private static final String FCUST_NO = "390099";

    /**
     * 软杰--使用优惠券
     * @param dto
     * @return
     */
    @Override
    public String useCoupon(UseCouponDTO dto) {
        String url = BASE_URL + "/api/Coupon/UseCoupon";

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("fCustID", 0);
        jsonObject.put("fCustNo", FCUST_NO);
        jsonObject.put("fBusID", 0);
        jsonObject.put("fInTime", 0);
        jsonObject.put("fPlateCode", dto.getFPlateCode());
        jsonObject.put("fCouponType", dto.getFCouponType());
        jsonObject.put("fCouponValue", dto.getFCouponValue());
        jsonObject.put("fCouponCode", dto.getFCouponCode());
        jsonObject.put("fStatus", "1"); // 1-有效
        // 获取sign
        String sign = getSign(jsonObject, SECRET_KEY);

        jsonObject.put("sign", sign);
        // 发送post请求
        log.info("软杰--使用优惠券 params:{}, url:{}", JSON.toJSONString(jsonObject), url);
        String result = HttpUtil.post(url, JSON.toJSONString(jsonObject));
        log.info("软杰--使用优惠券 result:{}", result);
        JSONObject resultJson = JSONObject.parseObject(result);

        return resultJson.getString("return_msg");
    }

    private static String getSign(JSONObject jsonObject, String secretKey) {
        // String secretKey = "";
        TreeMap<String, Object> params = new TreeMap<>(jsonObject);

        StringBuilder sb = new StringBuilder();
        for (String key : params.keySet()) {
            sb.append(key).append("=").append(params.get(key)).append("&");
        }
        sb.deleteCharAt(sb.length() - 1);
        sb.append("&key=").append(secretKey);
        return MD5Util.MD5Encode(sb.toString()).toLowerCase(Locale.ROOT);
    }
}
