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.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<>(3);
        map.put("StartDate", DateTimeFormatter.ofPattern(CommonConstant.TIME_FORMAT).format(jobPointLog.getStartTime().minusHours(1)));
        map.put("EndDate", DateTimeFormatter.ofPattern(CommonConstant.TIME_FORMAT).format(jobPointLog.getEndTime()));
        map.put("State", jobPointLog.getType());
        map.put("PageRow", jobPointLog.getPageSize());
        Integer page = 1;
        Integer pagetotal = 0;
        do {
            map.put("CurrentPage", page);
            Response response = null;
            String responseStr = null;
            try {
                RequestBody body = RequestBody.create(mediaType, JSON.toJSONString(map));
                Request request = new Request.Builder()
                        .url(propertiesUtil.getPropertyAsString("TRANSFER_DETAILS_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 (transferDetailsPOJO  != null && transferDetailsPOJO.getData()  != null && transferDetailsPOJO.getData().size() > 0) {
                        switch (jobPointLog.getType()) {
                            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);
                                        mapper1.upsertSelective(dcBaseTransferBale);
                                        SessionUtil.getSession().commit();
                                    } 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);
                                        mapper2.upsertSelective(dcBaseTransferDelivery);
                                        SessionUtil.getSession().commit();
                                    } 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);
                                        mapper3.upsertSelective(dcBaseTransferVerify);
                                        SessionUtil.getSession().commit();
                                    } 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);
                                        mapper4.upsertSelective(dcBaseTransferTransit);
                                        SessionUtil.getSession().commit();
                                    } 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);
                                        mapper5.upsertSelective(dcBaseTransferComplete);
                                        SessionUtil.getSession().commit();
                                    } 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);
                                        mapper12.upsertSelective(dcBaseTransferInbound);
                                        SessionUtil.getSession().commit();
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                        throw new RuntimeException("MYbatis操作DB失败", e);
                                    } finally {
                                        SessionUtil.closeSession();
                                    }
                                }
                                break;
                        }
                    }
                    jobPointLog.setStartTime(jobPointLog.getEndTime());
                    jobPointLog.setEndTime(jobPointLog.getStartTime().plusDays(jobPointLog.getIntervalTime().longValue()).isAfter(LocalDateTime.now()) ? LocalDateTime.now() : jobPointLog.getStartTime().plusDays(jobPointLog.getIntervalTime().longValue()));
                }
            } else {
                throw new RuntimeException("调用调拨流水接口失败");
            }
            page++;
        } while (page <= pagetotal);
        jobPointLog.setStartTime(jobPointLog.getEndTime());
        jobPointLog.setEndTime(jobPointLog.getStartTime().plusDays(jobPointLog.getIntervalTime().longValue()).isAfter(LocalDateTime.now()) ? LocalDateTime.now() : jobPointLog.getStartTime().plusDays(jobPointLog.getIntervalTime().longValue()));
    }
}
