package com.bailuntec.job;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.bailuntec.domain.constant.CommonConstant;
import com.bailuntec.domain.entity.DcSemiStockReport;
import com.bailuntec.domain.entity.JobPointLog;
import com.bailuntec.domain.pojo.SemiStockReportInfo;
import com.bailuntec.mapper.DcSemiStockReportMapper;
import com.bailuntec.mapper.JobPointLogMapper;
import com.bailuntec.support.PointJob;
import com.bailuntec.utils.ExceptionUtil;
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 SemiStockReportSyncJob 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()));
        Integer totalPage = 0;
        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_STOCK_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)) {
                SemiStockReportInfo<DcSemiStockReport> stockResultRoot = JSONObject.parseObject(palResultStr, new TypeReference<SemiStockReportInfo<DcSemiStockReport>>(){});
                if (stockResultRoot != null && stockResultRoot.getSuccess().booleanValue()) {
                    if (jobPointLog.getPageIndex().equals(0)) {
                        jobPointLog.setPageIndex(stockResultRoot.getData().getTotalPages() + 1);
                    }
                    List<DcSemiStockReport> resultData = stockResultRoot.getData() == null ? null : stockResultRoot.getData().getItems();
                    totalPage = stockResultRoot.getData().getTotalPages();
                    if (resultData != null && resultData.size() > 0) {
                        for(DcSemiStockReport semiStockReport : resultData) {
                            semiStockReport.setId(null);
                            DcSemiStockReportMapper mapper = SessionUtil.getSession().getMapper(DcSemiStockReportMapper.class);
                            mapper.upsertSelective(semiStockReport);
                        }
                    }
                } else {
                    log.warn("返回数据错误："+ palResultStr);
                    throw new RuntimeException("调用库存流水报表接口同步百伦库存流水失败, 响应200, 请求参数" + map.toString());
                }
            } else {
                throw new RuntimeException("调用库存流水报表接口同步百伦库存流水失败, 响应为null, 请求参数" + map.toString());
            }
            if (jobPointLog.getPageIndex() % 10 == 0) {
                try {
                    JobPointLogMapper mapper = SessionUtil.getSession().getMapper(JobPointLogMapper.class);
                    mapper.upsertSelective(jobPointLog);
                } catch (Exception e) {
                    e.printStackTrace();
                    throw new RuntimeException(ExceptionUtil.transform(e), e);
                } finally {
                    SessionUtil.closeSession();
                }
            }
            jobPointLog.setPageIndex(jobPointLog.getPageIndex() - 1);
        } while (0 < jobPointLog.getPageIndex());
        jobPointLog.setPageIndex(0);
        jobPointLog.setStartTime(jobPointLog.getEndTime());
        jobPointLog.setEndTime(jobPointLog.getEndTime().plusDays(jobPointLog.getIntervalTime()).isAfter(LocalDateTime.now()) ? LocalDateTime.now() : jobPointLog.getEndTime().plusDays(jobPointLog.getIntervalTime()));
    }
}
