package com.bailuntec.job;

import com.alibaba.fastjson.JSON;
import com.bailuntec.domain.entity.DcBaseCostFirst;
import com.bailuntec.domain.example.DcBaseCostFirstExample;
import com.bailuntec.domain.pojo.costfirst.CostFirstData;
import com.bailuntec.domain.pojo.costfirst.CostFirstResult;
import com.bailuntec.domain.pojo.costfirst.CostFirstSku;
import com.bailuntec.mapper.DcBaseCostFirstMapper;
import com.bailuntec.utils.OkHttpUtil;
import com.bailuntec.utils.PropertiesUtil;
import com.bailuntec.utils.SessionUtil;
import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
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;

@Slf4j
public class SyncCostFirstAllJob implements SimpleJob {
    private PropertiesUtil propertiesUtil = PropertiesUtil.getInstance("const");

    @Override
    public void execute(ShardingContext shardingContext) {

        OkHttpClient client = OkHttpUtil.getInstance();
        HashMap<String, String> map = new HashMap<>();
        map.put("startTime", LocalDateTime.now().minusMonths(4).format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
        map.put("endTime", LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
        Integer totalPage = 0;
        int currentPage = 1;
        do {
            map.put("currentPage", Integer.toString(currentPage));
            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;
            try {
                log.info("调用头程费用接口 starting");
                response = client.newCall(request).execute();

                String result = response.body().string();

                if (StringUtils.isNotBlank(result)) {
                    log.info("序列化头程费用头程费用 starting");
                    CostFirstResult costFirstResult = JSON.parseObject(result, CostFirstResult.class);
                    log.info("序列化头程费用头程费用 end");

                    log.info("头程费用当前请求页数 ：{} \n 头程费用当前总页数 ：{} \n 头程费用当前页码大小 ：{} \n",
                            currentPage,
                            costFirstResult.getPageCount(),
                            costFirstResult.getData().size());

                    totalPage = costFirstResult.getPageCount();
                    if (costFirstResult.getData() != null && costFirstResult.getData().size() > 0) {
                        handleCostFirstData(costFirstResult.getData());
                    }
                } else {
                    log.error("调用头程费接口失败,返回200,param:{}", new Gson().toJson(map));
                }

            } catch (IOException e) {
                log.error(e.getMessage(), e);
                log.error("调用头程费接口失败,param:{}", new Gson().toJson(map));

            } finally {
                if (response != null) {
                    response.close();
                }
            }
            log.info("调用头程费用接口 end");

            currentPage = currentPage + 1;

        } while (currentPage <= totalPage);

    }

    private void handleCostFirstData(List<CostFirstData> costFirstDataList) {
        try {
            DcBaseCostFirstMapper baseCostFirstMapper = SessionUtil.getSession().getMapper(DcBaseCostFirstMapper.class);
            //将费用处理一下, 给过来的数据很长的小数
            costFirstDataList.forEach(costFirstData -> {
                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);
                                log.info("百伦头程费信息, 是WMS根据线路估算而来 新增同步成功 ");
                            } else {
                                log.info("百伦头程费信息, 是WMS根据线路估算而来 更新同步成功 ");
                            }
                        }
                    }
                }
            });
        } catch (RuntimeException e) {
            log.error(e.getMessage(), e);
        } finally {
            SessionUtil.closeSession();
        }
    }
}
