package com.liquidnet.service.bank.currencycloud.service.impl;

import com.alibaba.fastjson.JSON;
import com.currencycloud.client.CurrencyCloudClient;
import com.currencycloud.client.exception.ApiException;
import com.currencycloud.client.model.DetailedRate;
import com.liquidnet.commons.lang.util.DateUtil;
import com.liquidnet.service.bank.common.BankErrorCode;
import com.liquidnet.service.bank.common.BankResultDto;
import com.liquidnet.service.bank.currencycloud.dto.BankCcRateDto;
import com.liquidnet.service.bank.currencycloud.dto.BankCcRateParam;
import com.liquidnet.service.bank.currencycloud.service.IBankCcRateService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author liquidnet
 * @since 2020-10-13
 */
@Slf4j
@Service("bankCcRateService")
public class BankCcRateServiceImpl implements IBankCcRateService {

    @Autowired
    CurrencyCloudClient currencyCloudClient;

    @Override
    public BankResultDto<BankCcRateDto> detailedRate(BankCcRateParam param) {
        String logFx = "";
        try {
            BankCcRateDto bankCcRateDto = new BankCcRateDto();
            String contactId = param.getContactId();
            String buyCurrency = param.getBuyCurrency();
            String sellCurrency = param.getSellCurrency();
            String fixedSide = param.getFixedSide();
            BigDecimal amount = param.getAmount();

            Date conversionDate = DateUtil.parse(param.getConversionDate(), "yyyy-MM-dd");
            String conversionDatePreference = param.getConversionDatePreference();
            if (conversionDate != null) {
                conversionDatePreference = null;
            }
            String finalConversionDatePreference = conversionDatePreference;
            Runnable runnable = () -> {
                DetailedRate detailedRate = currencyCloudClient.detailedRates(buyCurrency, sellCurrency, fixedSide, amount, conversionDate, finalConversionDatePreference);
                BeanUtils.copyProperties(detailedRate, bankCcRateDto);
            };
            currencyCloudClient.onBehalfOfDo(contactId, runnable);
            return BankResultDto.success(bankCcRateDto);

        } catch (ApiException e) {
            log.error(logFx + "api eroor, errorCode=[{}],errors=[{}]", e.getErrorCode(), e.getErrors());
            return BankResultDto.failure(e.getErrorCode(), e.getMessage());
        } catch (Exception e) {
            log.error(logFx + "exception eroor:[{}]", JSON.toJSONString(e));
            return BankResultDto.failure(BankErrorCode.BANK_CC_001001);
        }

    }

}
