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.Conversion;
import com.liquidnet.commons.lang.util.JsonUtils;
import com.liquidnet.service.bank.common.BankErrorCode;
import com.liquidnet.service.bank.common.BankResultDto;
import com.liquidnet.service.bank.currencycloud.dto.BankCcConversionCreateParam;
import com.liquidnet.service.bank.currencycloud.dto.BankCcConversionDto;
import com.liquidnet.service.bank.currencycloud.service.IBankCcConversionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author lightnet
 * @since 2020-09-08
 */
@Service("bankCcConversionService")
@Slf4j
public class BankCcConversionServiceImpl implements IBankCcConversionService {

    @Autowired
    CurrencyCloudClient currencyCloudClient;

    @Override
    @Transactional
    public BankResultDto<BankCcConversionDto> createConversions(BankCcConversionCreateParam param) {
        String logFx = param.getUniqueRequestId() + ",cc create conversion.";
        try {
            Conversion conversion = Conversion.create();
            BeanUtils.copyProperties(param, conversion);
            BankCcConversionDto dto = new BankCcConversionDto();
            Runnable runnable = () -> {
                log.info(logFx + "request conversion[{}]", JsonUtils.toJson(conversion));
                Conversion resp = currencyCloudClient.createConversion(conversion);
                BeanUtils.copyProperties(resp, dto);
                log.info(logFx + "response conversion=[{}]", JsonUtils.toJson(conversion));
            };

            currencyCloudClient.onBehalfOfDo(param.getContactId(), runnable);
            return BankResultDto.success(dto);
        } 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);
        }
    }

}
