package com.bailuntec.job;

import com.alibaba.fastjson.JSON;
import com.bailuntec.domain.entity.DcBaseCostFirst;
import com.bailuntec.domain.entity.JobPointLog;
import com.bailuntec.domain.example.DcBaseCostFirstExample;
import com.bailuntec.domain.pojo.CostFirstData;
import com.bailuntec.domain.pojo.CostFirstResult;
import com.bailuntec.domain.pojo.CostFirstSku;
import com.bailuntec.mapper.DcBaseCostFirstMapper;
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 okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;

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

    @Override
    public void executeJob(ShardingContext shardingContext, JobPointLog jobPointLog) {
        OkHttpClient client = OkHttpUtil.getInstance();
        HashMap<String, String> map = new HashMap<>();
        map.put("startTime", jobPointLog.getStartTime().minusMinutes(3).format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
        map.put("endTime", jobPointLog.getEndTime().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
        Integer totalPage = 0;
        do {
            map.put("currentPage", jobPointLog.getPageIndex().toString());
            Request request = new Request.Builder()
                    .url(OkHttpUtil.attachHttpGetParams(propertiesUtil.getPropertyAsString("COST_FIRST_URL"), map))
                    .get()
                    .addHeader("Content-Type", "application/json")
                    .addHeader("cache-control", "no-cache")
                    .build();
            Response response = null;
            String result;
            try {
                response = client.newCall(request).execute();
                result = response.body().string();
            } catch (IOException e) {
                e.printStackTrace();
                throw new RuntimeException("调用头程费接口失败", e);
            } finally {
                if (response != null) {
                    response.close();
                }
            }
            if (StringUtils.isNotBlank(result)) {
                CostFirstResult costFirstResult = JSON.parseObject(result, CostFirstResult.class);
                totalPage = costFirstResult.getPageCount();
                if (costFirstResult.getData() != null && costFirstResult.getData().size() > 0) {
                    handleCostFirstData(costFirstResult.getData());
                }
            } else {
                throw new RuntimeException("调用头程费接口失败,返回200");
            }
            jobPointLog.setPageIndex(jobPointLog.getPageIndex() + 1);
            if (jobPointLog.getPageIndex() % 8 == 0) {
                JobPointLogMapper mapper = SessionUtil.getSession().getMapper(JobPointLogMapper.class);
                mapper.upsertSelective(jobPointLog);
            }
        } while (jobPointLog.getPageIndex() <= totalPage);
        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()));
    }

    private void handleCostFirstData(List<CostFirstData> costFirstDataList) {
        try {
            DcBaseCostFirstMapper baseCostFirstMapper = SessionUtil.getSession().getMapper(DcBaseCostFirstMapper.class);
            for (CostFirstData costFirstData : costFirstDataList) {
                //将费用处理一下, 给过来的数据很长的小数
                costFirstData.setCostDuty(costFirstData.getCostDuty().setScale(3, RoundingMode.HALF_EVEN));
                costFirstData.setCostCustomsClearance(costFirstData.getCostCustomsClearance().setScale(3, RoundingMode.HALF_EVEN));
                costFirstData.setCostGoodsClearance(costFirstData.getCostGoodsClearance().setScale(3, RoundingMode.HALF_EVEN));
                costFirstData.setCostWeight(costFirstData.getCostWeight().setScale(3, RoundingMode.HALF_EVEN));
                costFirstData.setCostFuel(costFirstData.getCostFuel().setScale(3, RoundingMode.HALF_EVEN));
                costFirstData.setCostFirst(costFirstData.getCostFirst().setScale(3, RoundingMode.HALF_EVEN));
                DcBaseCostFirst dcBaseCostFirst = new DcBaseCostFirst();
                List<CostFirstSku> skus = costFirstData.getSkus();
                if (skus != null && skus.size() > 0) {
                    for (CostFirstSku costFirstSku : skus) {
                        dcBaseCostFirst.setBailunSku(costFirstSku.getBailunSku());
                        dcBaseCostFirst.setQuantity(costFirstSku.getQuantity());
                        try {
                            BeanUtils.copyProperties(dcBaseCostFirst, costFirstData);
                        } catch (Exception e) {
                            throw new RuntimeException("BeanUtils.copyProperties失败, ChannelId是" + costFirstData.getChannelId());
                        }
                        if(StringUtils.isNotBlank(dcBaseCostFirst.getBailunSku()) && StringUtils.isNotBlank(dcBaseCostFirst.getChannelOrderId()) && StringUtils.isNotBlank(dcBaseCostFirst.getBoxId()) && StringUtils.isNotBlank(dcBaseCostFirst.getTransferOrderId()) && StringUtils.isNotBlank(dcBaseCostFirst.getWarehouseCode())) {
                            int i = baseCostFirstMapper.updateByExampleSelective(dcBaseCostFirst, DcBaseCostFirstExample.newAndCreateCriteria().andBailunSkuEqualTo(dcBaseCostFirst.getBailunSku()).andChannelOrderIdEqualTo(dcBaseCostFirst.getChannelOrderId()).andBoxIdEqualTo(dcBaseCostFirst.getBoxId()).andTransferOrderIdEqualTo(dcBaseCostFirst.getTransferOrderId()).andWarehouseCodeEqualTo(dcBaseCostFirst.getWarehouseCode()).example());
                            if (i == 0) {
                                baseCostFirstMapper.upsertSelective(dcBaseCostFirst);
                            }
                        }
                    }
                }
            }
        } catch (RuntimeException e) {
            throw new RuntimeException("MYBATIS操作DB更新插入数据失败",e);
        } finally {
            SessionUtil.closeSession();
        }
    }
}
