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.Beneficiary;
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.BankCcBeneficiaryParam;
import com.liquidnet.service.bank.currencycloud.service.IBankCcBeneficiaryService;
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.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * currency cloud beneficiaries table 服务实现类
 * </p>
 *
 * @author liquidnet
 * @since 2020-10-12
 */
@Slf4j
@Service(value = "bankCcBeneficiaryService")
public class BankCcBeneficiaryServiceImpl implements IBankCcBeneficiaryService {

    @Autowired
    private CurrencyCloudClient currencyCloudClient;

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public BankResultDto<BankCcBeneficiaryParam> createBeneficiary(BankCcBeneficiaryParam param) {
        String logFx = param.getUniqueRequestId() + ",cc create beneficiary.";
        try {
            String contactId = param.getCreatorContactId();
            BankCcBeneficiaryParam resp = new BankCcBeneficiaryParam();
            Runnable runnable = () -> {
                Beneficiary beneficiaryReq = Beneficiary.create();
                BeanUtils.copyProperties(param, beneficiaryReq);
                log.info(logFx + "request=[{}]", JsonUtils.toJson(beneficiaryReq));
                Beneficiary beneficiaryResp = currencyCloudClient.createBeneficiary(beneficiaryReq);
                log.info(logFx + "response=[{}]", JsonUtils.toJson(beneficiaryResp));
                BeanUtils.copyProperties(beneficiaryResp, resp);
            };
            currencyCloudClient.onBehalfOfDo(contactId, runnable);
            return BankResultDto.success(resp);

        } 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);
        }

    }

}
