package com.bailuntec.job;


import com.alibaba.fastjson.JSON;
import com.bailuntec.domain.FBWFeeInfo;
import com.bailuntec.domain.WishAuth;
import com.bailuntec.domain.WishExceptionInfo;
import com.bailuntec.domain.constant.CommonConstant;
import com.bailuntec.domain.entity.*;
import com.bailuntec.domain.enumerate.CurrencyType;
import com.bailuntec.mapper.*;
import com.bailuntec.support.CallBailunSystem;
import com.bailuntec.utils.OkHttpUtil;
import com.bailuntec.utils.PropertiesUtil;
import com.bailuntec.utils.SessionUtil;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.math.BigDecimal;
import java.time.format.DateTimeFormatter;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@Slf4j
public class FBWFeeSyncJob {

    private OkHttpClient okHttpClient = OkHttpUtil.getInstance();
    private PropertiesUtil propertiesUtil = PropertiesUtil.getInstance("const");


    public void handleFBWFee(JobAccountLog jobAccountLog, DcBaseCompanyAccount dcBaseCompanyAccount) {
        LinkedHashMap<String, String> map = new LinkedHashMap<>(4);
        WishAuth wishAuth = JSON.parseObject(dcBaseCompanyAccount.getAuthJson(), WishAuth.class);
         map.put("since", DateTimeFormatter.ofPattern(CommonConstant.DATE_FORMAT).format(jobAccountLog.getStartTime()));
        map.put("access_token", wishAuth.getAccessToken());
        map.put("limit", String.valueOf(jobAccountLog.getPageSize()));
        Integer start = 0;
        do{
            map.put("start", start.toString());
            Response response = null;
            String FBWFeeResultStr = null;
            try {
                Request request = new Request.Builder()
                        .get()
                        .url(OkHttpUtil.attachHttpGetParams(propertiesUtil.getPropertyAsString("FBW_FEE_GET_URL"), map))
                        .addHeader("Content-Type", "application/json")
                        .build();
                response = okHttpClient.newCall(request).execute();
                FBWFeeResultStr = response.body().string();
            } catch (IOException e) {
                throw new RuntimeException("请求FBWFee接口失败" + response, e);
            } finally {
                if (response != null) {
                    response.close();
                }
            }
            if(StringUtils.isNotBlank(FBWFeeResultStr)) {
                WishExceptionInfo wishExceptionInfo = JSON.parseObject(FBWFeeResultStr, WishExceptionInfo.class);
                if(wishExceptionInfo.getCode() == 0) {
                    FBWFeeInfo fbwFeeInfo = JSON.parseObject(FBWFeeResultStr, FBWFeeInfo.class);
                    List<Map<String, DcBaseFinanceWishFbw>> mapList = fbwFeeInfo.getData();
                    if(mapList != null && mapList.size() > 0) {
                        for(Map<String, DcBaseFinanceWishFbw> maps : mapList) {
                            DcBaseFinanceWishFbw dcBaseFinanceWishFbw = null;
                            try {
                                dcBaseFinanceWishFbw = maps.get("FBWFee");
                                BigDecimal exchangeRate = CallBailunSystem.getExchangeRate(CurrencyType.USD.value(), CurrencyType.CNY.value(), dcBaseFinanceWishFbw.getCreatedTime());
                                dcBaseFinanceWishFbw.setOtherToCnyExchangeRate(exchangeRate);
                                dcBaseFinanceWishFbw.setAccountId(jobAccountLog.getAccountId());
                                dcBaseFinanceWishFbw.setCompanyId(jobAccountLog.getCompanyId());
                                dcBaseFinanceWishFbw.setRecordTime(jobAccountLog.getStartTime().toLocalDate());
                                DcBaseFinanceWishFbwMapper mapper = SessionUtil.getSession().getMapper(DcBaseFinanceWishFbwMapper.class);
                                mapper.insertSelective(dcBaseFinanceWishFbw);
                            } catch (Exception e) {
                                e.printStackTrace();
                                throw new RuntimeException("Mybatis操作DB插入任务记录失败", e);
                            } finally {
                                SessionUtil.closeSession();
                            }
                        }
                        start = start + jobAccountLog.getPageSize();
                    }else{
                        jobAccountLog.setMessage("执行成功");
                        break;
                    }
                }else {
                    jobAccountLog.setMessage(FBWFeeResultStr);
                    break;
                }
            }
        }while(true);
    }
}
