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.DcSemiPurchaseInfo;
import com.bailuntec.domain.entity.JobPointLog;
import com.bailuntec.domain.example.DcSemiPurchaseInfoExample;
import com.bailuntec.mapper.DcSemiPurchaseInfoMapper;
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 SyncSemiPurchaseDetailsJob 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<>(4);
        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("SEMI_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 {
                            DcSemiPurchaseInfoMapper mapper = SessionUtil.getSession().getMapper(DcSemiPurchaseInfoMapper.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());
                                DcSemiPurchaseInfo dcSemiPurchaseInfo = new DcSemiPurchaseInfo();
                                try {
                                    BeanUtils.copyProperties(dcSemiPurchaseInfo, purchaseDetail);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                    throw new RuntimeException("BeanUtils.copyProperties采购单sku详细信息异常");
                                }
                                dcSemiPurchaseInfo.setQuantityNotInbound(purchaseDetail.getQuantityPurchase() - purchaseDetail.getQuantityInbound());
                                dcSemiPurchaseInfo.setCreateTime(LocalDateTime.parse(purchaseDetail.getCreateTimed(), DateTimeFormatter.ofPattern("yyyy/M/d H:m:s")));
                                dcSemiPurchaseInfo.setUpdateTime(LocalDateTime.parse(purchaseDetail.getUpdateTimed(), DateTimeFormatter.ofPattern("yyyy/M/d H:m:s")));
                                dcSemiPurchaseInfo.setGmtModified(LocalDateTime.now());
                                int i = mapper.updateByExampleSelective(dcSemiPurchaseInfo, DcSemiPurchaseInfoExample.newAndCreateCriteria().andBailunSkuEqualTo(dcSemiPurchaseInfo.getBailunSku()).andPurchaseIdEqualTo(dcSemiPurchaseInfo.getPurchaseId()).example());
                                if (i == 0) {
                                    mapper.insertSelective(dcSemiPurchaseInfo);
                                }
                            });
                        } catch (Exception e) {
                            e.printStackTrace();
                            throw new RuntimeException("MYBATIS操作DB失败");
                        } finally {
                            SessionUtil.closeSession();
                        }
                    }else {
                        break;
                    }
                } else {
                    throw new RuntimeException("调用采购单sku详细信息接口失败");
                }
            } else {
                throw new RuntimeException("调用采购单sku详细信息接口失败");
            }
            jobPointLog.setPageIndex(jobPointLog.getPageIndex() + 1);
        } while (true);
        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()));
    }
}
