package com.bailuntec.job;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bailuntec.domain.entity.DcBaseLogistics;
import com.bailuntec.domain.entity.DcBaseStock;
import com.bailuntec.domain.entity.JobPointLog;
import com.bailuntec.domain.example.DcBaseLogisticsExample;
import com.bailuntec.domain.example.DcBaseStockExample;
import com.bailuntec.domain.pojo.*;
import com.bailuntec.mapper.DcBaseLogisticsMapper;
import com.bailuntec.mapper.DcBaseStockMapper;
import com.bailuntec.mapper.DcBaseWarehouseMapper;
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.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.List;

@Slf4j
public class WmsLogisticsJob extends PointJob {
    private PropertiesUtil propertiesUtil = PropertiesUtil.getInstance("const");

    @Override
    public void executeJob(ShardingContext shardingContext, JobPointLog jobPointLog) {
        Logistics wmsLogistic = new Logistics();
        wmsLogistic.setStartModificationTime(jobPointLog.getStartTime().minusHours(9));
        wmsLogistic.setEndModificationTime(jobPointLog.getEndTime());
        wmsLogistic.setPageCount(jobPointLog.getPageSize());
        do {
            OkHttpClient client = OkHttpUtil.getInstance();
            MediaType mediaType = MediaType.parse("application/json");
            wmsLogistic.setPageIndex(jobPointLog.getPageIndex() > 0? jobPointLog.getPageIndex() : 1);
            RequestBody body = RequestBody.create(mediaType, JSON.toJSONString(wmsLogistic));
            Request request = new Request.Builder()
                    .url(propertiesUtil.getPropertyAsString("LOGISTICS_WMS_URL"))
                    .post(body)
                    .addHeader("Content-Type", "application/json")
                    .build();
            Response response = null;
            String resultStr = null;
            try {
                response = client.newCall(request).execute();
                resultStr = response.body().string();
            } catch (IOException e) {
                throw new RuntimeException("调用wms系统库存接口失败", e);
            } finally {
                if (response != null) {
                    response.close();
                }
            }
            if (StringUtils.isNotBlank(resultStr)) {
                WmsLogisticsInfo wmsLogisticsInfo = JSON.parseObject(resultStr, WmsLogisticsInfo.class);
                 if (wmsLogisticsInfo.getSuccess() != null && wmsLogisticsInfo.getSuccess()) {
                    WmsLogisticsInfo.Result result = wmsLogisticsInfo.getResult();
                    List<WmsLogisticsInfo.Result.LogisticsInner> items = result.getResult();
                    if (jobPointLog.getPageIndex().equals(0)) {
                        int totalPage = result.getTotal() % jobPointLog.getPageSize() == 0 ? result.getTotal() / jobPointLog.getPageSize() : result.getTotal() / jobPointLog.getPageSize() + 1;
                        jobPointLog.setPageIndex(totalPage + 1);
                    }
                    if (items != null && items.size() > 0) {
                        try {
                            DcBaseLogisticsMapper dcBaseLogisticsMapper = SessionUtil.getSession().getMapper(DcBaseLogisticsMapper.class);
                            DcBaseLogistics dcBaseLogistics = new DcBaseLogistics();
                            items.forEach(wmsStockItem -> {
                                try {
                                    BeanUtils.copyProperties(dcBaseLogistics, wmsStockItem);
                                    dcBaseLogistics.setMerchantOutputWeightKg(dcBaseLogistics.getMerchantOutputWeightKg() == null ? BigDecimal.ZERO : dcBaseLogistics.getMerchantOutputWeightKg().setScale(4, RoundingMode.HALF_EVEN));
                                    dcBaseLogistics.setMerchantShipmentCostCny(dcBaseLogistics.getMerchantShipmentCostCny() == null ? BigDecimal.ZERO : dcBaseLogistics.getMerchantShipmentCostCny().setScale(4, RoundingMode.HALF_EVEN));
                                    dcBaseLogistics.setOutputWeightKg(dcBaseLogistics.getOutputWeightKg() == null ? BigDecimal.ZERO : dcBaseLogistics.getOutputWeightKg().setScale(4, RoundingMode.HALF_EVEN));
                                    dcBaseLogistics.setBailunShipmentCostCny(dcBaseLogistics.getBailunShipmentCostCny() == null ? BigDecimal.ZERO : dcBaseLogistics.getBailunShipmentCostCny().setScale(4, RoundingMode.HALF_EVEN));
                                    dcBaseLogistics.setMerchantOutputWeightKgOriginal(dcBaseLogistics.getMerchantOutputWeightKgOriginal() == null ? BigDecimal.ZERO : dcBaseLogistics.getMerchantOutputWeightKgOriginal().setScale(4, RoundingMode.HALF_EVEN));
                                    dcBaseLogistics.setMerchantShipmentCostSnyOriginal(dcBaseLogistics.getMerchantShipmentCostSnyOriginal() == null ? BigDecimal.ZERO : dcBaseLogistics.getMerchantShipmentCostSnyOriginal().setScale(4, RoundingMode.HALF_EVEN));
                                    dcBaseLogistics.setCostDiffDecimal(dcBaseLogistics.getCostDiffDecimal() == null ? BigDecimal.ZERO : dcBaseLogistics.getCostDiffDecimal().setScale(4, RoundingMode.HALF_EVEN));
                                    dcBaseLogistics.setWeightDiffDecimal(dcBaseLogistics.getWeightDiffDecimal() == null ? BigDecimal.ZERO : dcBaseLogistics.getWeightDiffDecimal().setScale(4, RoundingMode.HALF_EVEN));
                                } catch (Exception e) {
                                    e.printStackTrace();
                                    throw new RuntimeException("WMS物流BeanUtils.copyProperties失败");
                                }
                                int i = dcBaseLogisticsMapper.updateByExampleSelective(dcBaseLogistics, DcBaseLogisticsExample.newAndCreateCriteria().andWmsIdEqualTo(dcBaseLogistics.getWmsId()).example());
                                if (i == 0) {
                                    dcBaseLogisticsMapper.insertSelective(dcBaseLogistics);
                                }
                            });
                            if (jobPointLog.getPageIndex() % 5 == 0) {
                                JobPointLogMapper jobPointLogMapper = SessionUtil.getSession().getMapper(JobPointLogMapper.class);
                                jobPointLogMapper.upsertSelective(jobPointLog);
                            }
                        } catch (Exception e) {
                            throw new RuntimeException("MYBATIS操作DB失败", e);
                        } finally {
                            SessionUtil.closeSession();
                        }
                    }
                } else {
                    throw new RuntimeException("调用wms物流费接口失败");
                }
            } else {
                throw new RuntimeException("调用wms物流费接口失败");
            }
            jobPointLog.setPageIndex(jobPointLog.getPageIndex() - 1);
        } while (jobPointLog.getPageIndex() > 0);
        jobPointLog.setPageIndex(0);
        jobPointLog.setStartTime(jobPointLog.getEndTime());
        jobPointLog.setEndTime(jobPointLog.getStartTime().plusDays(jobPointLog.getIntervalTime()).isAfter(LocalDateTime.now()) ? LocalDateTime.now() : jobPointLog.getEndTime().plusDays(jobPointLog.getIntervalTime()));
    }

}
