package com.bailuntec.job;

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.dto.PurchaseDetailDTO;
import com.bailuntec.domain.entity.*;
import com.bailuntec.domain.example.DcBasePurchaseExample;
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 org.apache.commons.lang3.StringUtils;

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

@Slf4j
public class PurchaseDetailsServiceImpl {
    private static PropertiesUtil propertiesUtil = PropertiesUtil.getInstance("const");
    private static OkHttpClient client = OkHttpUtil.getInstance();
    public static void syncPurchaseDetails(JobPointLog jobPointLog) {
        MediaType mediaType = MediaType.parse("application/json");
        LinkedHashMap<String, Object> map = new LinkedHashMap<>(3);
        map.put("start", DateTimeFormatter.ofPattern(CommonConstant.TIME_FORMAT).format(jobPointLog.getStartTime().minusMinutes(3L)));
        map.put("end", DateTimeFormatter.ofPattern(CommonConstant.TIME_FORMAT).format(jobPointLog.getEndTime()));
        map.put("type", jobPointLog.getType());
        map.put("pagesize", jobPointLog.getPageSize());
        do {
            map.put("page", jobPointLog.getPageIndex() > 0? jobPointLog.getPageIndex() : 1);
            RequestBody body = RequestBody.create(mediaType, JSON.toJSONString(map));
            String purchaseStr = null;
            Response response = null;
            try {
                Request request = new Request.Builder()
                        .url(propertiesUtil.getPropertyAsString("PURCHASE_DETAILS_URL"))
                        .post(body)
                        .addHeader("Content-Type", "application/json")
                        .build();
                response = client.newCall(request).execute();
                purchaseStr = response.body().string();
            } catch (IOException e) {
                throw new RuntimeException("调用采购单sku流水接口失败", e);
            } finally {
                if (response != null) {
                    response.close();
                }
            }
            if (StringUtils.isNotBlank(purchaseStr)) {
                JSONObject jsonObject = JSON.parseObject(purchaseStr);
                if (jsonObject != null) {
                    if (jobPointLog.getPageIndex() == 0) {
                        jobPointLog.setPageIndex(jsonObject.getInteger("pagetotal") + 1);
                    }
                    List<PurchaseDetailDTO> purchaseDetailDTOList = jsonObject.getObject("data", new TypeReference<List<PurchaseDetailDTO>>() {
                    });
                    if (purchaseDetailDTOList != null && purchaseDetailDTOList.size() > 0) {
                        switch (jobPointLog.getType()) {
                            case 1:
                                for (PurchaseDetailDTO purchaseDetailDTO : purchaseDetailDTOList) {
                                    DcBasePurchase dcBasePurchase = new DcBasePurchase();
                                    try {
                                        BeanUtils.copyProperties(dcBasePurchase, purchaseDetailDTO);
                                        dcBasePurchase.setCreateTime(purchaseDetailDTO.getUpdatedTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());
                                        dcBasePurchase.setUpdateTime(purchaseDetailDTO.getUpdatedTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());
                                        if (purchaseDetailDTO.getLastpaytime() != null) {
                                            dcBasePurchase.setPayTime(purchaseDetailDTO.getLastpaytime().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());
                                        }
                                        if (purchaseDetailDTO.getSuretime() != null) {
                                            dcBasePurchase.setConfirmTime(purchaseDetailDTO.getSuretime().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());
                                        }
                                        if (purchaseDetailDTO.getArrivaldate() != null) {
                                            dcBasePurchase.setEstimatedArrivalTime(purchaseDetailDTO.getArrivaldate().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());
                                        }
                                        dcBasePurchase.setGmtModified(LocalDateTime.now());
                                    } catch (Exception e) {
                                        throw new RuntimeException("解析采购单sku流水BeanUtils.copyProperties失败", e);
                                    }
                                    try {
                                        DcBasePurchaseMapper mapper1 = SessionUtil.getSession().getMapper(DcBasePurchaseMapper.class);
                                        DcBasePurchase dcBasePurchaseSelected = mapper1.selectOneByExample(DcBasePurchaseExample.newAndCreateCriteria().andBailunSkuEqualTo(dcBasePurchase.getBailunSku()).andPurchaseIdEqualTo(dcBasePurchase.getPurchaseId()).example());
                                        if (dcBasePurchaseSelected != null && dcBasePurchaseSelected.getParentId() <= dcBasePurchase.getParentId()) {
                                            dcBasePurchase.setId(dcBasePurchaseSelected.getId());
                                            mapper1.updateByPrimaryKeySelective(dcBasePurchase);
                                        } else if (dcBasePurchaseSelected == null){
                                            mapper1.insertSelective(dcBasePurchase);
                                        }
                                        SessionUtil.getSession().commit();
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                        throw new RuntimeException("MYbatis操作DB失败", e);
                                    } finally {
                                        SessionUtil.closeSession();
                                    }
                                }
                                break;
                            case 2:
                                for (PurchaseDetailDTO purchaseDetailDTO : purchaseDetailDTOList) {
                                    DcBasePurchaseDelivery dcBasePurchaseDelivery = new DcBasePurchaseDelivery();
                                    try {
                                        BeanUtils.copyProperties(dcBasePurchaseDelivery, purchaseDetailDTO);
                                        dcBasePurchaseDelivery.setDeliveryId(purchaseDetailDTO.getCommonId());
                                        dcBasePurchaseDelivery.setCreateTime(purchaseDetailDTO.getUpdatedTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());
                                        dcBasePurchaseDelivery.setUpdateTime(purchaseDetailDTO.getUpdatedTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());
                                        dcBasePurchaseDelivery.setGmtModified(LocalDateTime.now());
                                    } catch (Exception e) {
                                        throw new RuntimeException("解析采购单sku流水BeanUtils.copyProperties失败", e);
                                    }
                                    try {
                                        DcBasePurchaseDeliveryMapper mapper2 = SessionUtil.getSession().getMapper(DcBasePurchaseDeliveryMapper.class);
                                        mapper2.upsertSelective(dcBasePurchaseDelivery);
                                        SessionUtil.getSession().commit();
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                        throw new RuntimeException("MYbatis操作DB失败", e);
                                    } finally {
                                        SessionUtil.closeSession();
                                    }
                                }
                                break;
                            case 3:
                                for (PurchaseDetailDTO purchaseDetailDTO : purchaseDetailDTOList) {
                                    DcBasePurchaseArrival dcBasePurchaseVerify = new DcBasePurchaseArrival();
                                    try {
                                        BeanUtils.copyProperties(dcBasePurchaseVerify, purchaseDetailDTO);
                                        dcBasePurchaseVerify.setArrivalId(purchaseDetailDTO.getCommonId());
                                        dcBasePurchaseVerify.setCreateTime(purchaseDetailDTO.getUpdatedTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());
                                        dcBasePurchaseVerify.setUpdateTime(purchaseDetailDTO.getUpdatedTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());
                                        dcBasePurchaseVerify.setGmtModified(LocalDateTime.now());
                                    } catch (Exception e) {
                                        throw new RuntimeException("解析采购单sku流水BeanUtils.copyProperties失败", e);
                                    }
                                    try {
                                        DcBasePurchaseArrivalMapper mapper3 = SessionUtil.getSession().getMapper(DcBasePurchaseArrivalMapper.class);
                                        mapper3.upsertSelective(dcBasePurchaseVerify);
                                        SessionUtil.getSession().commit();
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                        throw new RuntimeException("MYbatis操作DB失败", e);
                                    }
                                    finally {
                                        SessionUtil.closeSession();
                                    }
                                }
                                break;
                            case 4:
                                for (PurchaseDetailDTO purchaseDetailDTO : purchaseDetailDTOList) {
                                    DcBasePurchaseInspect dcBasePurchaseTransit = new DcBasePurchaseInspect();
                                    try {
                                        BeanUtils.copyProperties(dcBasePurchaseTransit, purchaseDetailDTO);
                                        dcBasePurchaseTransit.setInspectId(purchaseDetailDTO.getCommonId());
                                        dcBasePurchaseTransit.setCreateTime(purchaseDetailDTO.getUpdatedTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());
                                        dcBasePurchaseTransit.setUpdateTime(purchaseDetailDTO.getUpdatedTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());
                                        dcBasePurchaseTransit.setGmtModified(LocalDateTime.now());
                                    } catch (Exception e) {
                                        throw new RuntimeException("解析采购单sku流水BeanUtils.copyProperties失败", e);
                                    }
                                    try {
                                        DcBasePurchaseInspectMapper mapper4 = SessionUtil.getSession().getMapper(DcBasePurchaseInspectMapper.class);
                                        mapper4.upsertSelective(dcBasePurchaseTransit);
                                        SessionUtil.getSession().commit();
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                        throw new RuntimeException("MYbatis操作DB失败", e);
                                    } finally {
                                        SessionUtil.closeSession();
                                    }
                                }
                                break;
                            case 5:
                                for (PurchaseDetailDTO purchaseDetailDTO : purchaseDetailDTOList) {
                                    DcBasePurchaseInbound dcBasePurchaseInbound = new DcBasePurchaseInbound();
                                    try {
                                        BeanUtils.copyProperties(dcBasePurchaseInbound, purchaseDetailDTO);
                                        dcBasePurchaseInbound.setInboundId(purchaseDetailDTO.getCommonId());
                                        dcBasePurchaseInbound.setCreateTime(purchaseDetailDTO.getUpdatedTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());
                                        dcBasePurchaseInbound.setUpdateTime(purchaseDetailDTO.getUpdatedTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());
                                        dcBasePurchaseInbound.setGmtModified(LocalDateTime.now());
                                    } catch (Exception e) {
                                        throw new RuntimeException("解析采购单sku流水BeanUtils.copyProperties失败", e);
                                    }
                                    try {
                                        DcBasePurchaseInboundMapper mapper5 = SessionUtil.getSession().getMapper(DcBasePurchaseInboundMapper.class);
                                        mapper5.upsertSelective(dcBasePurchaseInbound);
                                        SessionUtil.getSession().commit();
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                        throw new RuntimeException("MYbatis操作DB失败", e);
                                    } finally {
                                        SessionUtil.closeSession();
                                    }
                                }
                                break;
                        }
                    }
                } else{
                    throw new RuntimeException("调用采购单sku流水接口失败");
                }
            } else{
                throw new RuntimeException("调用采购单sku流水接口失败");
            }
            jobPointLog.setPageIndex(jobPointLog.getPageIndex() - 1);
        } while (jobPointLog.getPageIndex() > 0);
        jobPointLog.setStartTime(jobPointLog.getEndTime());
        jobPointLog.setEndTime(jobPointLog.getStartTime().plusDays(jobPointLog.getIntervalTime().longValue()).isAfter(LocalDateTime.now()) ? LocalDateTime.now() : jobPointLog.getStartTime().plusDays(jobPointLog.getIntervalTime().longValue()));
    }
}
