package com.jwipc.sys.logic.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jwipc.page.PageUtil;
import com.jwipc.page.PageView;
import com.jwipc.query.BasePageQuery;
import com.jwipc.sys.convert.ExchangeRateConvert;
import com.jwipc.sys.dto.ExchangeRateDTO;
import com.jwipc.sys.entity.ExchangeRate;
import com.jwipc.sys.logic.ExchangeRateLogic;
import com.jwipc.sys.service.IExchangeRateService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

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


/**
 * <p> </p>
 *
 * @author BOGON
 * @version 1.0
 * @since JDK 1.8
 */
@Service
@RequiredArgsConstructor
public class ExchangeRateLogicImpl implements ExchangeRateLogic {
    private final IExchangeRateService exchangeRateService;
    private final ExchangeRateConvert exchangeRateConvert;

    @Override
    public PageView list(BasePageQuery pageQuery) {
        final Page<ExchangeRate> page = PageUtil.toPage(pageQuery);
        final List<ExchangeRate> list = exchangeRateService.list(page,
                new LambdaQueryWrapper<ExchangeRate>().orderBy(true, false, ExchangeRate::getMonthDate));
        List<ExchangeRateDTO> exchangeRateDTOS = exchangeRateConvert.entities2DTOs(list);
        return PageUtil.getPV(exchangeRateDTOS, page.getTotal());
    }

    @Override
    public String getExchangeRate(String currencyCode) {
        if (!"CNY".equals(currencyCode)){
            ExchangeRate sapExchangeRate = exchangeRateService.getOne(Wrappers.lambdaQuery(ExchangeRate.class).eq(ExchangeRate::getOriginalCurrency,currencyCode).eq(ExchangeRate::getMonthDate, DateUtil.format(new Date(),"yyyyMM")+"01").last(" limit 1"));
            return ObjectUtil.isNull(sapExchangeRate)?"没有获取到":sapExchangeRate.getExchange().toPlainString();
        }else {
            return "1";
        }
    }
}