package com.bailuntec.job;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bailuntec.domain.entity.DcBaseSku;
import com.bailuntec.domain.entity.DcBaseSkuTag;
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.DcBaseSkuTagMapper;
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.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

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

    @Override
    public void executeJob(ShardingContext shardingContext, JobPointLog jobPointLog) {
        SkumsRequest skumsRequest = new SkumsRequest();
        skumsRequest.setConditionJson(JSON.toJSONString(new SkuCondition(jobPointLog.getStartTime().minusMinutes(3), jobPointLog.getEndTime())));
        skumsRequest.setPageNumber(jobPointLog.getPageSize());
        do {
            MediaType mediaType = MediaType.parse("application/json");
            skumsRequest.setPageIndex(jobPointLog.getPageIndex() > 0?jobPointLog.getPageIndex() : 1);
            log.warn(JSON.toJSONString(skumsRequest));
            RequestBody body = RequestBody.create(mediaType, JSON.toJSONString(skumsRequest));
            Request request = new Request.Builder()
                    .url(propertiesUtil.getPropertyAsString("SKU_URL"))
                    .post(body)
                    .addHeader("Content-Type", "application/json")
                    .build();
            Response response = null;
            String resultStr = null;
            try {
                response = client.newCall(request).execute();
                resultStr = response.body().string();
            } catch (IOException e) {
                throw new RuntimeException("调用SKUMS系统接口失败", e);
            } finally {
                if (response != null) {
                    response.close();
                }
            }
            if (StringUtils.isNotBlank(resultStr)) {
                SkuMsResponse skuMsResponse = JSONObject.parseObject(resultStr, SkuMsResponse.class);
                if (skuMsResponse.getStatusCode()!= null && skuMsResponse.getStatusCode().equals(200)) {
                    SkuMsResult result = skuMsResponse.getResult();
                    if (result != null) {
                        List<SkuInfo> data = result.getData();
                        if (data != null && data.size() > 0) {
                            handleSkuMsJson(data,jobPointLog);
                        }
                        if (jobPointLog.getPageIndex().equals(0) && result.getTotalPage() != null) {
                            jobPointLog.setPageIndex(result.getTotalPage() + 1);
                        }
                    }
                } else {
                    throw new RuntimeException("调用SKUMS系统接口返回错误");
                }
            } 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()));
    }

    private void handleSkuMsJson(List<SkuInfo> data,JobPointLog jobPointLog) {
        DcBaseSku dcBaseSku = new DcBaseSku();
        DcBaseSkuWarehouse dcBaseSkuWarehouse = new DcBaseSkuWarehouse();
        DcBaseSkuTag dcBaseSkuTag = new DcBaseSkuTag();
        try {
            DcBaseSkuMapper mapper = SessionUtil.getSession().getMapper(DcBaseSkuMapper.class);
            DcBaseSkuWarehouseMapper dcBaseSkuWarehouseMapper = SessionUtil.getSession().getMapper(DcBaseSkuWarehouseMapper.class);
            DcBaseSkuTagMapper dcBaseSkuTagMapper = SessionUtil.getSession().getMapper(DcBaseSkuTagMapper.class);
            for (SkuInfo skuInfo : data) {
                if (StringUtils.isNotBlank(skuInfo.getBailunSku())) {
                    //逻辑删除仓库
                    dcBaseSkuWarehouseMapper.logicDeleteWarehouse(skuInfo.getBailunSku(),skuInfo.getCompanyId());
                    try {
                        BeanUtils.copyProperties(dcBaseSku, skuInfo);
                    } catch (Exception e) {
                        throw new RuntimeException("BeanUtils.copyProperties失败");
                    }
                    List<WarehouseInfo> warehouseList = skuInfo.getWarehouseList();
                    if (warehouseList != null && warehouseList.size() > 0) {
                        for (WarehouseInfo warehouseInfo : warehouseList) {
                            try {
                                BeanUtils.copyProperties(dcBaseSkuWarehouse, warehouseInfo);
                            } catch (Exception e) {
                                throw new RuntimeException("BeanUtils.copyProperties失败");
                            }
                            dcBaseSkuWarehouse.setBailunSku(skuInfo.getBailunSku());
                            dcBaseSkuWarehouse.setCompanyId(skuInfo.getCompanyId());
                            dcBaseSkuWarehouse.setStatus(0);
                            dcBaseSkuWarehouse.setGmtModified(LocalDateTime.now());
                            int i = dcBaseSkuWarehouseMapper.updateByExampleSelective(dcBaseSkuWarehouse, DcBaseSkuWarehouseExample.newAndCreateCriteria().andBailunSkuEqualTo(dcBaseSkuWarehouse.getBailunSku()).andCompanyIdEqualTo(dcBaseSkuWarehouse.getCompanyId()).andWarehouseCodeEqualTo(dcBaseSkuWarehouse.getWarehouseCode()).example());
                            if (i == 0) {
                                dcBaseSkuWarehouseMapper.insertSelective(dcBaseSkuWarehouse);
                            }
                        }
                    }
                    dcBaseSkuTag.setBailuinSku(skuInfo.getBailunSku());
                    for(GmtProductTag gmtProductTag : skuInfo.getTags()) {
                        dcBaseSkuTag.setTagCode(gmtProductTag.getTagCode() == null ? "" : gmtProductTag.getTagCode());
                        dcBaseSkuTag.setTagValuesCode(gmtProductTag.getTagValuesCode() == null ? "" : gmtProductTag.getTagValuesCode());
                        dcBaseSkuTag.setTagValuesName(gmtProductTag.getTagValuesName() == null ? "" : gmtProductTag.getTagValuesName());
                        dcBaseSkuTagMapper.upsertSelective(dcBaseSkuTag);
                    }
                    if(skuInfo.getTags() != null) {
                        String tagName = skuInfo.getTags().stream().map(GmtProductTag::getTagValuesName).collect(Collectors.joining(","));
                        dcBaseSku.setTags(tagName);
                    }
                    dcBaseSku.setGmtModified(LocalDateTime.now());
                    if(dcBaseSku.getPushTime().isBefore(LocalDateTime.of(1991, 01, 01, 00, 00, 00))) {
                        dcBaseSku.setPushTime(LocalDateTime.of(1991, 01, 01, 00, 00, 00));
                    }
                    int v = mapper.updateByExampleSelective(dcBaseSku, DcBaseSkuExample.newAndCreateCriteria().andBailunSkuEqualTo(dcBaseSku.getBailunSku()).example());
                    if (v == 0) {
                        mapper.insertSelective(dcBaseSku);
                    }
                }
            }
            if (jobPointLog.getPageIndex() % 4 == 0) {
                JobPointLogMapper jobPointLogMapper = SessionUtil.getSession().getMapper(JobPointLogMapper.class);
                jobPointLogMapper.upsertSelective(jobPointLog);
            }
        } catch (RuntimeException e) {
            throw new RuntimeException("MYBATIS操作SKU失败",e);
        } finally {
            SessionUtil.closeSession();
        }
    }


}
