package com.bailuntec.job;

import com.alibaba.fastjson.JSON;
import com.bailuntec.domain.InfractionFeeInfo;
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.domain.example.*;
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 InfractionFeeSyncJob {

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


    public void handleInfractionFee(JobAccountLog jobAccountLog, DcBaseCompanyAccount dcBaseCompanyAccount) {
        LinkedHashMap<String, String> map = new LinkedHashMap<>(3);
        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()));
        String urlPath = OkHttpUtil.attachHttpGetParams(propertiesUtil.getPropertyAsString("INFRACTIONS_GET_URL"), map);
        updateInfractionFeeInfo(jobAccountLog, urlPath);
    }

    private void updateInfractionFeeInfo(JobAccountLog jobAccountLog, String urlPath) {
        Response response = null;
        String palResultStr = null;
        try {
            Request request = new Request.Builder()
                    .get()
                    .url(urlPath)
                    .addHeader("Content-Type", "application/json")
                    .build();
            response = okHttpClient.newCall(request).execute();
            palResultStr = response.body().string();
        } catch (IOException e) {
            throw new RuntimeException(urlPath + "请求wish接口失败" + response, e);
        } finally {
            if (response != null) {
                response.close();
            }
        }
        if(StringUtils.isNotBlank(palResultStr)) {
            WishExceptionInfo wishExceptionInfo = JSON.parseObject(palResultStr, WishExceptionInfo.class);
            if(wishExceptionInfo.getCode() == 0) {
                InfractionFeeInfo infractionFeeInfo = JSON.parseObject(palResultStr, InfractionFeeInfo.class);
                List<Map<String, DcBaseFinanceWishInfraction>> mapList = infractionFeeInfo.getData().get("InfractionsResponse").get("infractions");
                for(Map<String, DcBaseFinanceWishInfraction> dcBaseFinanceWishInfractionMap : mapList) {
                    DcBaseFinanceWishInfraction dcBaseFinanceWishInfraction = dcBaseFinanceWishInfractionMap.get("Infraction");
                    try {
                        dcBaseFinanceWishInfraction.setId(null);
                        BigDecimal exchangeRate = CallBailunSystem.getExchangeRate(CurrencyType.USD.value(), CurrencyType.CNY.value(), dcBaseFinanceWishInfraction.getCreateTime());
                        dcBaseFinanceWishInfraction.setOtherToCnyExchangeRate(exchangeRate);
                        dcBaseFinanceWishInfraction.setAccountId(jobAccountLog.getAccountId());
                        dcBaseFinanceWishInfraction.setCompanyId(jobAccountLog.getCompanyId());
                        dcBaseFinanceWishInfraction.setRecordTime(jobAccountLog.getStartTime().toLocalDate());
                        DcBaseFinanceWishInfractionMapper mapper = SessionUtil.getSession().getMapper(DcBaseFinanceWishInfractionMapper.class);
                        int updateInt = mapper.updateByExampleSelective(dcBaseFinanceWishInfraction, DcBaseFinanceWishInfractionExample.newAndCreateCriteria().andInfractionsIdEqualTo(dcBaseFinanceWishInfraction.getInfractionsId()).andRecordTimeEqualTo(dcBaseFinanceWishInfraction.getRecordTime()).example());
                        if(updateInt == 0) {
                            mapper.insertSelective(dcBaseFinanceWishInfraction);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        throw new RuntimeException("Mybatis操作DB插入任务记录失败", e);
                    } finally {
                        SessionUtil.closeSession();
                    }
                }
                if(infractionFeeInfo.getPaging() != null) {
                    for(Map<String, String> stringMap : infractionFeeInfo.getPaging()) {
                        if(stringMap.get("next") != null) {
                            updateInfractionFeeInfo(jobAccountLog, stringMap.get("next"));
                        }
                    }
                }
                jobAccountLog.setMessage("执行成功");
            }else {
                jobAccountLog.setMessage(palResultStr);
            }
        }
    }

    private DcBaseCompanyAccount getToken(JobAccountLog jobAccountLog) {
        DcBaseCompanyAccountMapper mapper = SessionUtil.getSession().getMapper(DcBaseCompanyAccountMapper.class);
        return  mapper.selectOneByExample(DcBaseCompanyAccountExample.newAndCreateCriteria().andCompanyIdEqualTo(jobAccountLog.getCompanyId()).andAccountIdEqualTo(jobAccountLog.getAccountId()).example());
    }
}
