package com.bailuntec.job;

import com.alibaba.fastjson.JSON;
import com.bailuntec.domain.constant.CommonConstant;
import com.bailuntec.domain.entity.DcSemiOrder;
import com.bailuntec.domain.entity.JobPointLog;
import com.bailuntec.domain.pojo.SemiOrderResultInfo;
import com.bailuntec.mapper.DcSemiOrderMapper;
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.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
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 SemiOrderSyncJob extends PointJob {
    private OkHttpClient okHttpClient = OkHttpUtil.getInstance();
    private PropertiesUtil propertiesUtil = PropertiesUtil.getInstance("const");

    @Override
    public void executeJob(ShardingContext shardingContext, JobPointLog jobPointLog) {
        LinkedHashMap<String, String> map = new LinkedHashMap<>(4);
        map.put("rows", jobPointLog.getPageSize().toString());
        map.put("btime", DateTimeFormatter.ofPattern(CommonConstant.TIME_FORMAT).format(jobPointLog.getStartTime()));
        map.put("etime", DateTimeFormatter.ofPattern(CommonConstant.TIME_FORMAT).format(jobPointLog.getEndTime()));
        do {
            map.put("page", jobPointLog.getPageIndex().equals(0) ? "1" : jobPointLog.getPageIndex().toString());
            Response response = null;
            String palResultStr = null;
            try {
                Request request = new Request.Builder()
                        .get()
                        .url(OkHttpUtil.attachHttpGetParams(propertiesUtil.getPropertyAsString("SEMI_ORDER_URL"), map))
                        .addHeader("Content-Type", "application/json")
                        .build();
                response = okHttpClient.newCall(request).execute();
                palResultStr = response.body().string();
            } catch (IOException e) {
                throw new RuntimeException(map + "请求流水接口同步百伦接口失败" + response, e);
            } finally {
                if (response != null) {
                    response.close();
                }
            }
            if (StringUtils.isNoneBlank(palResultStr)) {
                SemiOrderResultInfo palResultRoot = JSON.parseObject(palResultStr, SemiOrderResultInfo.class);
                if (palResultRoot != null && palResultRoot.getSuccess().booleanValue()) {
                    List<DcSemiOrder> resultData = palResultRoot.getData();
                    if (resultData != null && resultData.size() > 0) {
                        for (DcSemiOrder semiOrder : resultData) {
                            semiOrder.setId(null);
                            DcSemiOrderMapper mapper = SessionUtil.getSession().getMapper(DcSemiOrderMapper.class);
                            mapper.upsertSelective(semiOrder);
                            log.info("同步一条semi订单 orderNo:{}",semiOrder.getOrderNo());
                        }
                    } else {
                        break;
                    }
                } else {
                    throw new RuntimeException("调用流水接口同步百伦流水失败, 响应200, 请求参数" + map.toString());
                }
            } else {
                throw new RuntimeException("调用流水接口同步百伦流水失败, 响应为null, 请求参数" + map.toString());
            }
            jobPointLog.setPageIndex(jobPointLog.getPageIndex() + 1);
        } while (true);
        jobPointLog.setPageIndex(0);
        jobPointLog.setStartTime(jobPointLog.getEndTime());
        jobPointLog.setEndTime(jobPointLog.getEndTime().plusDays(jobPointLog.getIntervalTime()).isAfter(LocalDateTime.now()) ? LocalDateTime.now() : jobPointLog.getEndTime().plusDays(jobPointLog.getIntervalTime()));
    }
}
