package com.bailuntec.job;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bailuntec.domain.constant.CommonConstant;
import com.bailuntec.domain.entity.*;
import com.bailuntec.domain.example.*;
import com.bailuntec.domain.pojo.TransferDetailsPOJO;
import com.bailuntec.domain.pojo.TransferStreamPOJO;
import com.bailuntec.mapper.*;
import com.bailuntec.utils.OkHttpUtil;
import com.bailuntec.utils.PropertiesUtil;
import com.bailuntec.utils.SessionUtil;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.apache.commons.beanutils.BeanUtils;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.LinkedHashMap;

@Slf4j
public class TransferDetailsServiceImpl {
    private static PropertiesUtil propertiesUtil = PropertiesUtil.getInstance("const");

    public static void syncTransferDetails(JobPointLog jobPointLog) {
        OkHttpClient client = OkHttpUtil.getInstance();
        MediaType mediaType = MediaType.parse("application/json");
        LinkedHashMap<String, Object> map = new LinkedHashMap<>(5);
        map.put("StartDate", DateTimeFormatter.ofPattern(CommonConstant.TIME_FORMAT).format(jobPointLog.getStartTime().minusHours(9)));
        map.put("EndDate", DateTimeFormatter.ofPattern(CommonConstant.TIME_FORMAT).format(jobPointLog.getEndTime()));
        String url = propertiesUtil.getPropertyAsString("TRANSFER_PLAN_URL");
        if (jobPointLog.getType() != 0) {
            map.put("State", jobPointLog.getType());
            url = propertiesUtil.getPropertyAsString("TRANSFER_DETAILS_URL");
        }
        map.put("PageRow", jobPointLog.getPageSize());
        do {
            map.put("CurrentPage", jobPointLog.getPageIndex() > 0?jobPointLog.getPageIndex() : 1);
            Response response = null;
            String responseStr = null;
            try {
                RequestBody body = RequestBody.create(mediaType, JSON.toJSONString(map));
                Request request = new Request.Builder()
                        .url(url)
                        .post(body)
                        .addHeader("Content-Type", "application/json")
                        .build();
                response = client.newCall(request).execute();
                responseStr = response.body().string();
            } catch (IOException e) {
                throw new RuntimeException("调用调拨单sku流水接口失败", e);
            } finally {
                if (response != null) {
                    response.close();
                }
            }
            if (response != null && response.isSuccessful()) {
                JSONObject jsonObject = JSON.parseObject(responseStr);
                if (jsonObject.get("isSuccess") != null && jsonObject.getBooleanValue("isSuccess")) {
                    TransferDetailsPOJO transferDetailsPOJO = jsonObject.getObject("data", TransferDetailsPOJO.class);
                    if (jobPointLog.getPageIndex().equals(0)) {
                        jobPointLog.setPageIndex(transferDetailsPOJO.getPageCount() + 1);
                    }
                    if (transferDetailsPOJO  != null && transferDetailsPOJO.getData()  != null && transferDetailsPOJO.getData().size() > 0) {
                        switch (jobPointLog.getType()) {
                            case 0:
                                for (TransferStreamPOJO transferStreamPOJO : transferDetailsPOJO.getData()) {
                                    DcBaseTransferPlan dcBaseTransferPlan = new DcBaseTransferPlan();
                                    try {
                                        BeanUtils.copyProperties(dcBaseTransferPlan, transferStreamPOJO);
                                    } catch (Exception e) {
                                        throw new RuntimeException("解析调拨单sku流水BeanUtils.copyProperties失败", e);
                                    }
                                    try {
                                        DcBaseTransferPlanMapper mapper0 = SessionUtil.getSession().getMapper(DcBaseTransferPlanMapper.class);
                                        int i = mapper0.updateByExampleSelective(dcBaseTransferPlan, DcBaseTransferPlanExample.newAndCreateCriteria().andBailunSkuEqualTo(dcBaseTransferPlan.getBailunSku())
                                                .andTransferPlanOrderIdEqualTo(dcBaseTransferPlan.getTransferPlanOrderId()).example());
                                        if (i == 0) {
                                            mapper0.insertSelective(dcBaseTransferPlan);
                                        }
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                        throw new RuntimeException("MYbatis操作DB失败", e);
                                    } finally {
                                        SessionUtil.closeSession();
                                    }
                                }
                                break;
                            case 1:
                                for (TransferStreamPOJO transferStreamPOJO : transferDetailsPOJO.getData()) {
                                    DcBaseTransferBale dcBaseTransferBale = new DcBaseTransferBale();
                                    try {
                                        BeanUtils.copyProperties(dcBaseTransferBale, transferStreamPOJO);
                                    } catch (Exception e) {
                                        throw new RuntimeException("解析调拨单sku流水BeanUtils.copyProperties失败", e);
                                    }
                                    try {
                                        DcBaseTransferBaleMapper mapper1 = SessionUtil.getSession().getMapper(DcBaseTransferBaleMapper.class);
                                        int i = mapper1.updateByExampleSelective(dcBaseTransferBale, DcBaseTransferBaleExample.newAndCreateCriteria().andBailunSkuEqualTo(dcBaseTransferBale.getBailunSku())
                                                .andTransferOrderIdEqualTo(dcBaseTransferBale.getTransferOrderId()).example());
                                        if (i == 0) {
                                            mapper1.insertSelective(dcBaseTransferBale);
                                        }
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                        throw new RuntimeException("MYbatis操作DB失败", e);
                                    } finally {
                                        SessionUtil.closeSession();
                                    }
                                }
                                break;
                            case 2:
                                for (TransferStreamPOJO transferStreamPOJO : transferDetailsPOJO.getData()) {
                                    DcBaseTransferDelivery dcBaseTransferDelivery = new DcBaseTransferDelivery();
                                    try {
                                        BeanUtils.copyProperties(dcBaseTransferDelivery, transferStreamPOJO);
                                    } catch (Exception e) {
                                        throw new RuntimeException("解析调拨单sku流水BeanUtils.copyProperties失败", e);
                                    }
                                    try {
                                        DcBaseTransferDeliveryMapper mapper2 = SessionUtil.getSession().getMapper(DcBaseTransferDeliveryMapper.class);
                                        int i = mapper2.updateByExampleSelective(dcBaseTransferDelivery, DcBaseTransferDeliveryExample.newAndCreateCriteria().andBailunSkuEqualTo(dcBaseTransferDelivery.getBailunSku())
                                                .andTransferOrderIdEqualTo(dcBaseTransferDelivery.getTransferOrderId()).example());
                                        if (i == 0) {
                                            mapper2.insertSelective(dcBaseTransferDelivery);
                                        }
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                        throw new RuntimeException("MYbatis操作DB失败", e);
                                    } finally {
                                        SessionUtil.closeSession();
                                    }
                                }

                                break;
                            case 3:
                                for (TransferStreamPOJO transferStreamPOJO : transferDetailsPOJO.getData()) {
                                    DcBaseTransferVerify dcBaseTransferVerify = new DcBaseTransferVerify();
                                    try {
                                        BeanUtils.copyProperties(dcBaseTransferVerify, transferStreamPOJO);
                                    } catch (Exception e) {
                                        throw new RuntimeException("解析调拨单sku流水BeanUtils.copyProperties失败", e);
                                    }
                                    try {
                                        DcBaseTransferVerifyMapper mapper3 = SessionUtil.getSession().getMapper(DcBaseTransferVerifyMapper.class);
                                        int i = mapper3.updateByExampleSelective(dcBaseTransferVerify, DcBaseTransferVerifyExample.newAndCreateCriteria().andBailunSkuEqualTo(dcBaseTransferVerify.getBailunSku())
                                                .andTransferOrderIdEqualTo(dcBaseTransferVerify.getTransferOrderId()).example());
                                        if (i == 0) {
                                            mapper3.insertSelective(dcBaseTransferVerify);
                                        }
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                        throw new RuntimeException("MYbatis操作DB失败", e);
                                    } finally {
                                        SessionUtil.closeSession();
                                    }
                                }
                                break;
                            case 4:
                                for (TransferStreamPOJO transferStreamPOJO : transferDetailsPOJO.getData()) {
                                    DcBaseTransferTransit dcBaseTransferTransit = new DcBaseTransferTransit();
                                    try {
                                        BeanUtils.copyProperties(dcBaseTransferTransit, transferStreamPOJO);
                                    } catch (Exception e) {
                                        throw new RuntimeException("解析调拨单sku流水BeanUtils.copyProperties失败", e);
                                    }
                                    try {
                                        DcBaseTransferTransitMapper mapper4 = SessionUtil.getSession().getMapper(DcBaseTransferTransitMapper.class);
                                        int i = mapper4.updateByExampleSelective(dcBaseTransferTransit, DcBaseTransferTransitExample.newAndCreateCriteria().andBailunSkuEqualTo(dcBaseTransferTransit.getBailunSku())
                                                .andTransferOrderIdEqualTo(dcBaseTransferTransit.getTransferOrderId()).example());
                                        if (i == 0) {
                                            mapper4.insertSelective(dcBaseTransferTransit);
                                        }
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                        throw new RuntimeException("MYbatis操作DB失败", e);
                                    } finally {
                                        SessionUtil.closeSession();
                                    }
                                }
                                break;
                            case 5:
                                for (TransferStreamPOJO transferStreamPOJO : transferDetailsPOJO.getData()) {
                                    DcBaseTransferComplete dcBaseTransferComplete = new DcBaseTransferComplete();
                                    try {
                                        BeanUtils.copyProperties(dcBaseTransferComplete, transferStreamPOJO);
                                    } catch (Exception e) {
                                        throw new RuntimeException("解析调拨单sku流水BeanUtils.copyProperties失败", e);
                                    }
                                    try {
                                        DcBaseTransferCompleteMapper mapper5 = SessionUtil.getSession().getMapper(DcBaseTransferCompleteMapper.class);
                                        int i = mapper5.updateByExampleSelective(dcBaseTransferComplete, DcBaseTransferCompleteExample.newAndCreateCriteria().andBailunSkuEqualTo(dcBaseTransferComplete.getBailunSku())
                                                .andTransferOrderIdEqualTo(dcBaseTransferComplete.getTransferOrderId()).example());
                                        if (i == 0) {
                                            mapper5.insertSelective(dcBaseTransferComplete);
                                        }
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                        throw new RuntimeException("MYbatis操作DB失败", e);
                                    } finally {
                                        SessionUtil.closeSession();
                                    }
                                }
                                break;
                            case 12:
                                for (TransferStreamPOJO transferStreamPOJO : transferDetailsPOJO.getData()) {
                                    DcBaseTransferInbound dcBaseTransferInbound = new DcBaseTransferInbound();
                                    try {
                                        BeanUtils.copyProperties(dcBaseTransferInbound, transferStreamPOJO);
                                    } catch (Exception e) {
                                        throw new RuntimeException("解析调拨单sku流水BeanUtils.copyProperties失败", e);
                                    }
                                    try {
                                        DcBaseTransferInboundMapper mapper12 = SessionUtil.getSession().getMapper(DcBaseTransferInboundMapper.class);
                                        int round = Math.round(dcBaseTransferInbound.getCreateTime().getNano() / 1000000000.0F);
                                        int i = mapper12.updateByExampleSelective(dcBaseTransferInbound, DcBaseTransferInboundExample.newAndCreateCriteria()
                                                        .andBailunSkuEqualTo(dcBaseTransferInbound.getBailunSku())
                                                        .andTransferOrderIdEqualTo(dcBaseTransferInbound.getTransferOrderId())
                                                .andCreateTimeEqualTo(dcBaseTransferInbound.getCreateTime().withNano(0).plusSeconds(round))
                                                .example());
                                        if (i == 0) {
                                            mapper12.insertSelective(dcBaseTransferInbound);
                                        }
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                        throw new RuntimeException("MYbatis操作DB失败", e);
                                    } finally {
                                        SessionUtil.closeSession();
                                    }
                                }
                                break;
                        }
                    }
                } else {
                    throw new RuntimeException("调用调拨流水接口返回200但是失败");
                }
            } else {
                throw new RuntimeException("调用调拨流水接口失败");
            }
            if (jobPointLog.getPageIndex() % 5 == 0) {
                try {
                    JobPointLogMapper mapper = SessionUtil.getSession().getMapper(JobPointLogMapper.class);
                    mapper.upsertSelective(jobPointLog);
                } catch (Exception e) {
                    e.printStackTrace();
                    throw new RuntimeException("Mybatis操作DB插入任务记录失败", e);
                } finally {
                    SessionUtil.closeSession();
                }
            }
            jobPointLog.setPageIndex(jobPointLog.getPageIndex() - 1);
        } while (jobPointLog.getPageIndex() > 0);
        jobPointLog.setPageIndex(0);
        jobPointLog.setStartTime(jobPointLog.getEndTime());
        jobPointLog.setEndTime(jobPointLog.getStartTime().plusDays(jobPointLog.getIntervalTime().longValue()).isAfter(LocalDateTime.now()) ? LocalDateTime.now() : jobPointLog.getStartTime().plusDays(jobPointLog.getIntervalTime().longValue()));
    }
}
