package com.bailuntec.job;

import com.alibaba.fastjson.JSON;
import com.bailuntec.domain.entity.DcBaseLogisticsReconciliation;
import com.bailuntec.domain.entity.JobPointLog;
import com.bailuntec.domain.example.DcBaseLogisticsReconciliationExample;
import com.bailuntec.domain.pojo.LogisticsReconciliation;
import com.bailuntec.domain.pojo.WmsLogisticsReconciliationInfo;
import com.bailuntec.mapper.DcBaseLogisticsReconciliationMapper;
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.Arrays;
import java.util.List;

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

    @Override
    public void executeJob(ShardingContext shardingContext, JobPointLog jobPointLog) {
        LogisticsReconciliation logisticsReconciliation = new LogisticsReconciliation();
        logisticsReconciliation.setStartModificationTime(jobPointLog.getStartTime().minusHours(9));
        logisticsReconciliation.setEndModificationTime(jobPointLog.getEndTime());
        logisticsReconciliation.setPageCount(jobPointLog.getPageSize());
        logisticsReconciliation.setDiffStateTypes(Arrays.asList("0"));
        do {
            OkHttpClient client = OkHttpUtil.getInstance();
            MediaType mediaType = MediaType.parse("application/json");
            logisticsReconciliation.setPageIndex(jobPointLog.getPageIndex() > 0? jobPointLog.getPageIndex() : 1);
            RequestBody body = RequestBody.create(mediaType, JSON.toJSONString(logisticsReconciliation));
            Request request = new Request.Builder()
                    .url(propertiesUtil.getPropertyAsString("LOGISTICS_WMS_RECONCILIATION_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)) {
                WmsLogisticsReconciliationInfo wmsLogisticsReconciliationInfo = JSON.parseObject(resultStr, WmsLogisticsReconciliationInfo.class);
                 if (wmsLogisticsReconciliationInfo.getSuccess() != null && wmsLogisticsReconciliationInfo.getSuccess()) {
                     WmsLogisticsReconciliationInfo.Result result = wmsLogisticsReconciliationInfo.getResult();
                    List<WmsLogisticsReconciliationInfo.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 {
                            DcBaseLogisticsReconciliationMapper dcBaseLogisticsReconciliationMapper = SessionUtil.getSession().getMapper(DcBaseLogisticsReconciliationMapper.class);
                            DcBaseLogisticsReconciliation dcBaseLogisticsReconciliation = new DcBaseLogisticsReconciliation();
                            items.forEach(wmsStockItem -> {
                                try {
                                    BeanUtils.copyProperties(dcBaseLogisticsReconciliation, wmsStockItem);
                                    dcBaseLogisticsReconciliation.setOutputweightkg(dcBaseLogisticsReconciliation.getOutputweightkg() == null ? BigDecimal.ZERO : dcBaseLogisticsReconciliation.getOutputweightkg().setScale(4, RoundingMode.HALF_EVEN));
                                    dcBaseLogisticsReconciliation.setBailunshipmentcostcny(dcBaseLogisticsReconciliation.getBailunshipmentcostcny() == null ? BigDecimal.ZERO : dcBaseLogisticsReconciliation.getBailunshipmentcostcny().setScale(4, RoundingMode.HALF_EVEN));
                                    dcBaseLogisticsReconciliation.setMerchantoutputweightkg(dcBaseLogisticsReconciliation.getMerchantoutputweightkg() == null ? BigDecimal.ZERO : dcBaseLogisticsReconciliation.getMerchantoutputweightkg().setScale(4, RoundingMode.HALF_EVEN));
                                    dcBaseLogisticsReconciliation.setMerchantshipmentcostcny(dcBaseLogisticsReconciliation.getMerchantshipmentcostcny() == null ? BigDecimal.ZERO : dcBaseLogisticsReconciliation.getMerchantshipmentcostcny().setScale(4, RoundingMode.HALF_EVEN));
                                    dcBaseLogisticsReconciliation.setConfirmshipmentcostcny(dcBaseLogisticsReconciliation.getConfirmshipmentcostcny() == null ? BigDecimal.ZERO : dcBaseLogisticsReconciliation.getConfirmshipmentcostcny().setScale(4, RoundingMode.HALF_EVEN));
                                    dcBaseLogisticsReconciliation.setConfirmoutputweightkg(dcBaseLogisticsReconciliation.getConfirmoutputweightkg() == null ? BigDecimal.ZERO : dcBaseLogisticsReconciliation.getConfirmoutputweightkg().setScale(4, RoundingMode.HALF_EVEN));
                                } catch (Exception e) {
                                    e.printStackTrace();
                                    throw new RuntimeException("WMS物流BeanUtils.copyProperties失败");
                                }
                                int i = dcBaseLogisticsReconciliationMapper.updateByExampleSelective(dcBaseLogisticsReconciliation, DcBaseLogisticsReconciliationExample.newAndCreateCriteria().andWmsIdEqualTo(dcBaseLogisticsReconciliation.getWmsId()).example());
                                if (i == 0) {
                                    dcBaseLogisticsReconciliationMapper.insertSelective(dcBaseLogisticsReconciliation);
                                }
                            });
                            /*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()));
    }

}
