package com.kym.service.parking;

import com.alibaba.fastjson2.JSONObject;
import com.kym.common.R;
import com.kym.common.exception.BusinessException;
import com.kym.common.utils.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Map;

/**
 * @author skyline
 * 互联互通平台接口服务
 */
@Service
@Slf4j
public class ZongTingParkingApiServiceImpl implements ParkingApi {

    // todo 纵停平台秘钥，每个停车场不同，后面做成数据库配置
    private static final String ZONG_TING_PARKING_SIGN_KEY = "";
    private static final String ZONG_TING_URL = "http://shenzhen.gate.4pyun.com:8661";


    /**
     * 【纵停】生成签名
     *
     * @param paramMap
     * @return
     */
    private static String genSign(final Map<String, String> paramMap) {
        // 创建一个长度和map.size()大小一致的字符串数组
        String[] keyArray = new String[paramMap.keySet().size()];
        // 将 map的key的set 集合转化为数组
        paramMap.keySet().toArray(keyArray);
        // 将数组元素按字典序进行排序
        Arrays.sort(keyArray);
        StringBuilder sb = new StringBuilder();
        // 遍历key数组,将键与值按照key=value&进行拼接
        for (String key : keyArray) {
            if (StringUtils.isNotBlank(key) && StringUtils.isNotBlank(paramMap.get(key))) {
                sb.append(key).append("=").append(paramMap.get(key)).append("&");
            }
        }
        // 拼接秘钥时先将秘钥做一次 md5 加密然后拼接
        sb.append("key=").append(DigestUtils.md5Hex(ZONG_TING_PARKING_SIGN_KEY));
        log.info("param : {}", sb);
        // 将拼接的字符串先进行 md5 加密，再转为大写
        String sign = DigestUtils.md5Hex(sb.toString()).toUpperCase();
        log.info("param: {} sign: {}", sb, sign);
        return sign;
    }

    /**
     * 【纵停】发放优惠券
     *
     * @param params
     * @return
     */
    @Override
    public R<?> parkingFeeReduction(ZongTingParamsBody params) {
        var signParams = Map.of("plateNo", params.getPlateNo(), "merchId", params.getMerchId(), "duration", params.getCouponValue());
        params.setSign(genSign(signParams));
        var res = HttpUtil.post(ZONG_TING_URL, JSONObject.toJSONString(params), R.class);
        log.info("停车场ID:{},车辆：{}减免停车费用结果：{}", params.getParkId(), params.getParkId(), res);
        return switch (res.getCode()) {
            case 10001 -> R.success();
            case 10002 -> throw new BusinessException("车辆未入场");
            case 10003 -> throw new BusinessException("重复减免");
            case 10005 -> throw new BusinessException("系统错误");
            case 10006 -> throw new BusinessException("merchId错误");
            case 10007 -> throw new BusinessException("签名错误");
            case 10008 -> throw new BusinessException("减免类型与配置不一致");
            case 10009 -> throw new BusinessException("全免金额长度需小于10");
            default -> throw new BusinessException("未知错误");
        };
    }

}
