package com.bailuntec.support;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.bailuntec.domain.constant.CommonConstant;
import com.bailuntec.domain.entity.DcExchangeRate;
import com.bailuntec.domain.example.DcExchangeRateExample;
import com.bailuntec.domain.pojo.AccountNoToken;
import com.bailuntec.mapper.DcExchangeRateMapper;
import com.bailuntec.utils.OkHttpUtil;
import com.bailuntec.utils.SessionUtil;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;

@Slf4j
public class CallBailunSystem {

    /**
     * 获取每月月初的汇率
     *
     * @param fromCurrency
     * @param toCurrency
     * @return
     * @throws Exception
     */
    public static BigDecimal getMonthExchangeRate(String fromCurrency, String toCurrency, LocalDateTime queryTime) {

        if (queryTime.isBefore(LocalDateTime.of(2018, 1, 1, 0, 0, 0))) {
            queryTime = LocalDateTime.of(2018, 1, 1, 0, 0, 0);
        }
        queryTime = queryTime.withDayOfMonth(1);
        BigDecimal exchangeRate = null;
        try {
            exchangeRate = getMySqlExchangeRate(fromCurrency, toCurrency, queryTime.toLocalDate());
        } catch (Exception e) {
            log.error("获取月初汇率失败", e);
            throw new RuntimeException("获取" + queryTime + "的汇率失败", e);
        }
        return exchangeRate;
    }

    /**
     * 获取指定日期的汇率
     *
     * @param fromCurrency
     * @param toCurrency
     * @return
     * @throws Exception
     */
    public static BigDecimal getExchangeRate(String fromCurrency, String toCurrency, LocalDateTime queryTime) {
        if (queryTime.isBefore(LocalDateTime.of(2018, 1, 1, 0, 0, 0))) {
            queryTime = LocalDateTime.of(2018, 1, 1, 0, 0, 0);
        }
        BigDecimal exchangeRate = null;
        try {
            exchangeRate = getMySqlExchangeRate(fromCurrency, toCurrency, queryTime.toLocalDate());
        } catch (Exception e) {
            log.error("获取" + queryTime + "的汇率失败", e);
            throw new RuntimeException("获取" + queryTime + "的汇率失败", e);
        }
        return exchangeRate;
    }

    private static BigDecimal getMySqlExchangeRate(String fromCurrency, String toCurrency, LocalDate queryTime) {
        DcExchangeRateMapper mapper = SessionUtil.getSession().getMapper(DcExchangeRateMapper.class);
        DcExchangeRate dcExchangeRate = mapper.selectOneByExample(DcExchangeRateExample.newAndCreateCriteria().andInitCurrenyEqualTo(fromCurrency).andFinalCurrenyEqualTo(toCurrency).andRecordTimeEqualTo(queryTime).example());
        if (dcExchangeRate != null) {
            return dcExchangeRate.getExchangeRate();
        }
        OkHttpClient client = OkHttpUtil.getInstance();
        HashMap<String, String> map = new HashMap<>(3);
        map.put("fromCur", fromCurrency);
        map.put("toCur", toCurrency);
        map.put("date", DateTimeFormatter.ofPattern(CommonConstant.DATE_FORMAT).format(queryTime));
        BigDecimal exchangeRate = null;
        Response responseEntity = null;
        try {
            Request request = new Request.Builder()
                    .url(OkHttpUtil.attachHttpGetParams(CommonConstant.EXCHANGE_RATE_URL, map))
                    .get()
                    .build();
            responseEntity = client.newCall(request).execute();
            exchangeRate = null;
            if (responseEntity.isSuccessful()) {
                JSONObject jsonObject = JSON.parseObject(responseEntity.body().string());
                exchangeRate = (BigDecimal) jsonObject.get("rate");
                dcExchangeRate = new DcExchangeRate();
                dcExchangeRate.setInitCurreny(fromCurrency);
                dcExchangeRate.setFinalCurreny(toCurrency);
                dcExchangeRate.setExchangeRate(exchangeRate);
                dcExchangeRate.setRecordTime(queryTime);
                try {
                    mapper.insertSelective(dcExchangeRate);
                    SessionUtil.getSession().commit();
                } catch (Exception e) {
                    throw new RuntimeException("Mybatis操作DB失败", e);
                } finally {
                    SessionUtil.closeSession();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("调用汇率接口失败", e);
        } finally {
            if (responseEntity != null) {
                responseEntity.close();
            }
        }
        return exchangeRate;
    }

    public static AccountNoToken getBailunAccount(Integer bailunAccountId) {
        OkHttpClient client = OkHttpUtil.getInstance();

        Response response = null;
        String resultStr = null;
        try {
            Request request = new Request.Builder()
                    .url(CommonConstant.ACCOUNT_NO_TOKEN_URL + bailunAccountId)
                    .get()
                    .build();
            response = client.newCall(request).execute();
            resultStr = response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("调用百伦账号系统接口失败" + bailunAccountId, e);
        } finally {
            if (response != null) {
                response.close();
            }
        }
        if (response != null && response.isSuccessful()) {
            JSONObject jsonObject = JSON.parseObject(resultStr);
            if (jsonObject != null && jsonObject.get("Data") != null) {
                List<AccountNoToken> accountNoTokenList = jsonObject.getObject("Data", new TypeReference<List<AccountNoToken>>() {
                });
                return accountNoTokenList.size() > 0 ? accountNoTokenList.get(0) : null;
            }
        } else {
            throw new RuntimeException("调用百伦账号系统接口失败" + bailunAccountId);
        }
        return null;
    }

}
