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

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.currencycloud.client.CurrencyCloudClient;
import com.currencycloud.client.exception.ApiException;
import com.currencycloud.client.model.Account;
import com.liquidnet.common.exception.constant.ErrorCode;
import com.liquidnet.service.ResponseDto;
import com.liquidnet.service.bank.currencycloud.dto.BankCcAccountCreateDto;
import com.liquidnet.service.bank.currencycloud.dto.BankCcAccountCreateParam;
import com.liquidnet.service.bank.currencycloud.dto.BankCcAccountParam;
import com.liquidnet.service.bank.currencycloud.dto.BankCcContactParam;
import com.liquidnet.service.bank.currencycloud.entity.BankCcAccount;
import com.liquidnet.service.bank.currencycloud.entity.BankCcContact;
import com.liquidnet.service.bank.currencycloud.mapper.BankCcAccountMapper;
import com.liquidnet.service.bank.currencycloud.mapper.BankCcContactMapper;
import com.liquidnet.service.bank.currencycloud.service.IBankCcAccountService;
import com.liquidnet.service.bank.currencycloud.service.IBankCcContactService;
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;

import java.time.LocalDateTime;

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

    @Autowired
    CurrencyCloudClient currencyCloudClient;

    @Autowired
    BankCcAccountMapper bankCcAccountMapper;

    @Autowired
    IBankCcContactService bankCcContactService;

    @Autowired
    BankCcContactMapper bankCcContactMapper;

    @Override
    public ResponseDto<BankCcAccountCreateDto> createAccount(BankCcAccountCreateParam param) {
        BankCcContactParam contactParam = param.getBankCcContactParam();
        LambdaQueryWrapper<BankCcContact> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.eq(BankCcContact::getLoginId, contactParam.getLoginId());
        BankCcContact bankCcContact = bankCcContactMapper.selectOne(lambdaQueryWrapper);

        if (bankCcContact != null) {
            String accountId = bankCcContact.getAccountId();
            BankCcAccount bankCcAccount = bankCcAccountMapper.selectById(accountId);
            BankCcAccountCreateDto accountCreateDto = new BankCcAccountCreateDto();
            accountCreateDto.setBankCcAccount(bankCcAccount);
            accountCreateDto.setBankCcContact(bankCcContact);
            return ResponseDto.success(accountCreateDto);

        }

        // 创建 account
        ResponseDto<BankCcAccount> accountResponseDto = this.createAccount(param.getBankCcAccountParam());
        if (!accountResponseDto.isSuccess()) {
            return ResponseDto.failure(accountResponseDto.getCode(), accountResponseDto.getMessage());
        }

        // 创建 contact
        BankCcContactParam bankCcContactParam = param.getBankCcContactParam();
        bankCcContactParam.setAccountId(accountResponseDto.getData().getId());
        ResponseDto<BankCcContact> contactResponseDto = bankCcContactService.createContact(bankCcContactParam);
        if (!contactResponseDto.isSuccess()) {
            return ResponseDto.failure(contactResponseDto.getCode(), contactResponseDto.getMessage());
        }
        BankCcAccountCreateDto accountCreateDto = new BankCcAccountCreateDto();
        accountCreateDto.setBankCcAccount(accountResponseDto.getData());
        accountCreateDto.setBankCcContact(contactResponseDto.getData());
        return ResponseDto.success(accountCreateDto);
    }

    @Override
    @Transactional
    public ResponseDto<BankCcAccount> createAccount(BankCcAccountParam param) {
        String logFx = param.getUniqueRequestId() + ",cc create account.";
        try {
            // 必填参数
            String accountName = param.getAccountName();
            String legalEntityType = param.getLegalEntityType();
            String street = param.getStreet();
            String city = param.getCity();
            String postalCode = param.getPostalCode();
            String country = param.getCountry();
            // 选填参数
            String stateOrProvince = param.getStateOrProvince();
            // 创建cc sdk请求对象Account
            Account account = Account.create(accountName, legalEntityType, street, city, postalCode, country);
            account.setStateOrProvince(stateOrProvince);
            log.info(logFx + "request account=[{}]", JSON.toJSONString(account));
            Account accountResp = currencyCloudClient.createAccount(account);
            log.info(logFx + "response account=[{}]", accountResp.toString());
            BankCcAccount bankCcAccount = new BankCcAccount();
            BeanUtils.copyProperties(accountResp, bankCcAccount);
            // 持久化数据库
            bankCcAccount.setCreateTime(LocalDateTime.now());
            bankCcAccountMapper.insert(bankCcAccount);
            return ResponseDto.success(bankCcAccount);
        } catch (ApiException e) {
            log.error(logFx + "api eroor, errorCode=[{}],errors=[{}]", e.getErrorCode(), e.getErrors());
            return ResponseDto.failure(e.getErrorCode(), e.getMessage());
        } catch (Exception e) {
            log.error(logFx + "exception eroor:[{}]", JSON.toJSONString(e));
            return ResponseDto.failure(ErrorCode.HTTP_SYSTEM_ERROR);
        }

    }

}
