package com.jwipc.sys.client.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.jwipc.sys.client.ExchangeRateClient;
import com.jwipc.sys.entity.ExchangeRate;
import com.jwipc.sys.service.IExchangeRateService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;

/**
 * @author shenyang.ou
 * @date 2024/4/7 14:24
 * @desc
 */
@Service
@RequiredArgsConstructor
public class ExchangeRateClientImpl implements ExchangeRateClient {
    private final IExchangeRateService exchangeRateService;

    /**
     * 根据币种获取当月汇率
     * @param currencyCode 从币种
     * @param convertExchange 到币种 (一般都是CNY)
     * @return 当月汇率
     */

    public BigDecimal getExchangeRate(String currencyCode,String convertExchange){
        if (!"CNY".equals(currencyCode)){
            ExchangeRate sapExchangeRate = exchangeRateService.getOne(Wrappers.lambdaQuery(ExchangeRate.class).eq(ExchangeRate::getOriginalCurrency,currencyCode).eq(ExchangeRate::getConvertExchange,convertExchange).eq(ExchangeRate::getMonthDate, DateUtil.format(new Date(),"yyyyMM")+"01").last(" limit 1"));
            return ObjectUtil.isNull(sapExchangeRate)?null:sapExchangeRate.getExchange();
        }else {
            return BigDecimal.ONE;
        }
    }

    public BigDecimal getExchangeRateDefault(String currencyCode){
        if (!"CNY".equals(currencyCode)){
            ExchangeRate sapExchangeRate = exchangeRateService.getOne(Wrappers.lambdaQuery(ExchangeRate.class).eq(ExchangeRate::getOriginalCurrency,currencyCode).eq(ExchangeRate::getConvertExchange,"CNY").eq(ExchangeRate::getMonthDate, DateUtil.format(new Date(),"yyyyMM")+"01").last(" limit 1"));
            return ObjectUtil.isNull(sapExchangeRate)?null:sapExchangeRate.getExchange();
        }else {
            return BigDecimal.ONE;
        }
    }
}
