package com.bailuntec.job;


import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.bailuntec.domain.constant.CommonConstant;
import com.bailuntec.domain.entity.DcSemiStockProd;
import com.bailuntec.domain.entity.DcSemiStockReport;
import com.bailuntec.domain.entity.JobPointLog;
import com.bailuntec.domain.pojo.SemiStockReportInfo;
import com.bailuntec.mapper.DcSemiStockProdMapper;
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 SemiStockProdSyncJob 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<>(2);
        map.put("rows", jobPointLog.getPageSize().toString());
        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_PROD"), 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<DcSemiStockProd> stockResultRoot = JSONObject.parseObject(palResultStr, new TypeReference<SemiStockReportInfo<DcSemiStockProd>>(){});
                if (stockResultRoot != null && stockResultRoot.getSuccess().booleanValue()) {
                    if (jobPointLog.getPageIndex().equals(0)) {
                        jobPointLog.setPageIndex(stockResultRoot.getData().getTotalPages() + 1);
                    }
                    List<DcSemiStockProd> resultData = stockResultRoot.getData() == null ? null : stockResultRoot.getData().getItems();
                    totalPage = stockResultRoot.getData().getTotalPages();
                    if (resultData != null && resultData.size() > 0) {
                        for(DcSemiStockProd semiStockProd : resultData) {
                            semiStockProd.setId(null);
                            DcSemiStockProdMapper mapper = SessionUtil.getSession().getMapper(DcSemiStockProdMapper.class);
                            mapper.upsertSelective(semiStockProd);
                        }
                    }
                } 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().minusHours(3)) ? LocalDateTime.now().minusHours(3) : jobPointLog.getEndTime().plusDays(jobPointLog.getIntervalTime()));
    }
}
