package com.bailuntec.job;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bailuntec.domain.constant.CommonConstant;
import com.bailuntec.domain.entity.DcBaseSku;
import com.bailuntec.domain.entity.DcBaseSkuMapping;
import com.bailuntec.domain.entity.DcBaseSkuWarehouse;
import com.bailuntec.domain.entity.JobPointLog;
import com.bailuntec.domain.example.DcBaseSkuExample;
import com.bailuntec.domain.example.DcBaseSkuWarehouseExample;
import com.bailuntec.domain.pojo.*;
import com.bailuntec.domain.request.SkuCondition;
import com.bailuntec.domain.request.SkumsRequest;
import com.bailuntec.mapper.DcBaseSkuMapper;
import com.bailuntec.mapper.DcBaseSkuMappingMapper;
import com.bailuntec.mapper.DcBaseSkuWarehouseMapper;
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 lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.LinkedHashMap;
import java.util.List;

@Slf4j
public class SkuMappingSyncJob extends PointJob {
    private PropertiesUtil propertiesUtil = PropertiesUtil.getInstance("const");
    private OkHttpClient client = OkHttpUtil.getInstance();

    @Override
    public void executeJob(ShardingContext shardingContext, JobPointLog jobPointLog) {
        LinkedHashMap<String, String> map = new LinkedHashMap<>(4);
        map.put("PageNumber", jobPointLog.getPageSize().toString());
        map.put("StartTime", DateTimeFormatter.ofPattern(CommonConstant.TIME_FORMAT).format(jobPointLog.getStartTime()));
        map.put("EndTime", DateTimeFormatter.ofPattern(CommonConstant.TIME_FORMAT).format(jobPointLog.getEndTime()));
        do {
            map.put("PageIndex", jobPointLog.getPageIndex().equals(0) ? "1" : jobPointLog.getPageIndex().toString());
            Response response = null;
            String resultStr = null;
            try {
                Request request = new Request.Builder()
                        .get()
                        .url(OkHttpUtil.attachHttpGetParams(propertiesUtil.getPropertyAsString("SKU_MAPPING_URL"), map))
                        .addHeader("Content-Type", "application/json")
                        .build();
                response = client.newCall(request).execute();
                resultStr = response.body().string();
            } catch (IOException e) {
                throw new RuntimeException(map + "请求sku映射同步百伦接口失败" + response, e);
            } finally {
                if (response != null) {
                    response.close();
                }
            }

            if (StringUtils.isNotBlank(resultStr)) {
                SkuMappingResponse skuMappingResponse = JSONObject.parseObject(resultStr, SkuMappingResponse.class);
                JobPointLogMapper pointLogMapper = SessionUtil.getSession().getMapper(JobPointLogMapper.class);
                pointLogMapper.upsertSelective(jobPointLog);
                if (skuMappingResponse.getData()!= null && skuMappingResponse.getData().size() > 0) {
                    List<DcBaseSkuMapping> skuMappingInfoList = skuMappingResponse.getData();
                    for(DcBaseSkuMapping dcBaseSkuMapping : skuMappingInfoList) {
                        dcBaseSkuMapping.setGmtModified(LocalDateTime.now());
                        DcBaseSkuMappingMapper dcBaseSkuMappingMapper = SessionUtil.getSession().getMapper(DcBaseSkuMappingMapper.class);
                        dcBaseSkuMappingMapper.upsertSelective(dcBaseSkuMapping);
                    }
                        if (jobPointLog.getPageIndex().equals(0) && skuMappingResponse.getTotalPage() != null) {
                            jobPointLog.setPageIndex(skuMappingResponse.getTotalPage() + 1);
                        }
                }
            } else {
                throw new RuntimeException("调用SKUMS系统接口返回null");
            }

            jobPointLog.setPageIndex(jobPointLog.getPageIndex() - 1);
        } while (jobPointLog.getPageIndex() > 0);
        jobPointLog.setPageIndex(0);
        jobPointLog.setStartTime(jobPointLog.getEndTime());
        jobPointLog.setEndTime(jobPointLog.getStartTime().plusDays(jobPointLog.getIntervalTime().longValue()).isAfter(LocalDateTime.now()) ? LocalDateTime.now() : jobPointLog.getStartTime().plusDays(jobPointLog.getIntervalTime().longValue()));
    }
}
