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.DcBasePurchaseDetails;
import com.bailuntec.domain.entity.JobPointLog;
import com.bailuntec.domain.example.DcBasePurchaseDetailsExample;
import com.bailuntec.mapper.DcBasePurchaseDetailsMapper;
import com.bailuntec.mapper.JobPointLogMapper;
import com.bailuntec.support.PointJob;
import com.bailuntec.utils.OkHttpUtil;
import com.bailuntec.utils.PropertiesUtil;
import com.bailuntec.utils.SessionUtil;
import com.dangdang.ddframe.job.api.ShardingContext;
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.format.DateTimeFormatter;
import java.util.LinkedHashMap;
import java.util.List;

@Slf4j
public class SyncPurchaseDetailsJob extends PointJob {
    private static PropertiesUtil propertiesUtil = PropertiesUtil.getInstance("const");
    private static OkHttpClient client = OkHttpUtil.getInstance();

    @Override
    public void executeJob(ShardingContext shardingContext, 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(1L)));
        map.put("end", DateTimeFormatter.ofPattern(CommonConstant.TIME_FORMAT).format(jobPointLog.getEndTime()));
        map.put("pagesize", jobPointLog.getPageSize());
        List<PurchaseDetailDTO> purchaseDetailDTOList = null;
        do {
            map.put("page", jobPointLog.getPageIndex());
            RequestBody body = RequestBody.create(mediaType, JSON.toJSONString(map));
            String purchaseStr = null;
            Response response = null;
            if (purchaseDetailDTOList != null) purchaseDetailDTOList = 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) {
                log.error("调用采购单sku详细信息接口失败", e);
                throw new RuntimeException("调用采购单sku详细信息接口失败", e);
            } finally {
                if (response != null) {
                    response.close();
                }
            }
            if (StringUtils.isNotBlank(purchaseStr)) {
                JSONObject jsonObject = JSON.parseObject(purchaseStr);
                if (jsonObject != null) {
                    purchaseDetailDTOList = jsonObject.getObject("data", new TypeReference<List<PurchaseDetailDTO>>() {
                    });
                    if (purchaseDetailDTOList != null && purchaseDetailDTOList.size() > 0) {
                        try {
                            DcBasePurchaseDetailsMapper mapper = SessionUtil.getSession().getMapper(DcBasePurchaseDetailsMapper.class);
                            if (jobPointLog.getPageIndex() % 10 == 0) {
                                JobPointLogMapper pointLogMapper = SessionUtil.getSession().getMapper(JobPointLogMapper.class);
                                pointLogMapper.upsertSelective(jobPointLog);
                            }
                            purchaseDetailDTOList.forEach(purchaseDetail -> {
                                log.warn(purchaseDetail.getBailunSku() + "&" + purchaseDetail.getPurchaseId());
                                DcBasePurchaseDetails dcBasePurchaseDetails = new DcBasePurchaseDetails();
                                try {
                                    BeanUtils.copyProperties(dcBasePurchaseDetails, purchaseDetail);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                    throw new RuntimeException("BeanUtils.copyProperties采购单sku详细信息异常");
                                }
                                dcBasePurchaseDetails.setQuantityNotInbound(purchaseDetail.getQuantityPurchase() - purchaseDetail.getQuantityInbound());
                                dcBasePurchaseDetails.setCreateTime(LocalDateTime.parse(purchaseDetail.getCreateTimed(), DateTimeFormatter.ofPattern("yyyy/M/d H:m:s")));
                                dcBasePurchaseDetails.setUpdateTime(LocalDateTime.parse(purchaseDetail.getUpdateTimed(), DateTimeFormatter.ofPattern("yyyy/M/d H:m:s")));
                                dcBasePurchaseDetails.setGmtModified(LocalDateTime.now());
                                int i = mapper.updateByExampleSelective(dcBasePurchaseDetails, DcBasePurchaseDetailsExample.newAndCreateCriteria().andBailunSkuEqualTo(dcBasePurchaseDetails.getBailunSku()).andPurchaseIdEqualTo(dcBasePurchaseDetails.getPurchaseId()).example());
                                if (i == 0) {
                                    mapper.insertSelective(dcBasePurchaseDetails);
                                }
                            });
                        } catch (Exception e) {
                            e.printStackTrace();
                            throw new RuntimeException("MYBATIS操作DB失败");
                        } finally {
                            SessionUtil.closeSession();
                        }
                    }
                } else {
                    throw new RuntimeException("调用采购单sku详细信息接口失败");
                }
            } else {
                throw new RuntimeException("调用采购单sku详细信息接口失败");
            }
            jobPointLog.setPageIndex(jobPointLog.getPageIndex() + 1);
        } while (purchaseDetailDTOList != null && purchaseDetailDTOList.size() == jobPointLog.getPageSize());
        jobPointLog.setPageIndex(1);
        jobPointLog.setStartTime(jobPointLog.getEndTime());
        jobPointLog.setEndTime(jobPointLog.getStartTime().plusDays(jobPointLog.getIntervalTime().longValue()).isAfter(LocalDateTime.now()) ? LocalDateTime.now() : jobPointLog.getStartTime().plusDays(jobPointLog.getIntervalTime().longValue()));
    }
}
