package com.bailuntec.job;

import com.alibaba.fastjson.JSON;
import com.bailuntec.domain.constant.EbaySkuMappingRoot;
import com.bailuntec.domain.entity.*;
import com.bailuntec.mapper.DcBaseEbaySkuMappingMapper;
import com.bailuntec.mapper.DcBaseFinanceEbayMapper;
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.lang3.StringUtils;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;

@Slf4j
public class EbayItemSyncJob extends PointJob {

    private OkHttpClient okHttpClient = OkHttpUtil.getInstance();
    private PropertiesUtil propertiesUtil = PropertiesUtil.getInstance("const");

    @Override
    public void executeJob(ShardingContext shardingContext, JobPointLog jobPointLog) {
        long countEbayFee;
        try{
            DcBaseFinanceEbayMapper dcBaseFinanceEbayMapper = SessionUtil.getSession().getMapper(DcBaseFinanceEbayMapper.class);
            countEbayFee = dcBaseFinanceEbayMapper.countByGroup(jobPointLog);
        }catch (Exception e){
            e.printStackTrace();
            throw new RuntimeException("MYBATIS操作DB失败", e);
        }finally {
            SessionUtil.closeSession();
        }

        long totalPage = getEbayPage(countEbayFee, jobPointLog);

        do{
            List<String> dcBaseFinanceEbayItemDtoList;
            try{
                DcBaseFinanceEbayMapper dcBaseFinanceEbayMapper = SessionUtil.getSession().getMapper(DcBaseFinanceEbayMapper.class);
                dcBaseFinanceEbayItemDtoList = dcBaseFinanceEbayMapper.selectEbayItem(jobPointLog);
          //      for(DcBaseFinanceEbayItemDto dcBaseFinanceEbayItemDto : dcBaseFinanceEbayItemDtoList) {

                    MediaType mediaType = MediaType.parse("application/json");
                    RequestBody body = RequestBody.create(mediaType, JSON.toJSONString(dcBaseFinanceEbayItemDtoList));
                    Request request = new Request.Builder()
                            .url(propertiesUtil.getPropertyAsString("getSkuCodeInfoByItemId"))
                            .post(body)
                            .addHeader("Content-Type", "application/json")
                            .build();
                    Response response = null;
                    String ebaySkuMappingStr = null;
                    try {
                        response = okHttpClient.newCall(request).execute();
                        ebaySkuMappingStr = response.body().string();
                    } catch (IOException e) {
                        throw new RuntimeException(dcBaseFinanceEbayItemDtoList + "请求ebay广告费映射失败" + response, e);
                    } finally {
                        if (response != null) {
                            response.close();
                        }
                    }
                    DcBaseEbaySkuMapping dcBaseEbaySkuMapping = new DcBaseEbaySkuMapping();
                    if (StringUtils.isNoneBlank(ebaySkuMappingStr)) {
                        EbaySkuMappingRoot ebaySkuMappingRoot = JSON.parseObject(ebaySkuMappingStr, EbaySkuMappingRoot.class);
                        if (ebaySkuMappingRoot != null && ebaySkuMappingRoot.getIsSucceeded().booleanValue()) {
                            List<DcBaseEbaySkuMapping> dcBaseEbaySkuMappingList = ebaySkuMappingRoot.getObjData();
                            if (dcBaseEbaySkuMappingList != null && dcBaseEbaySkuMappingList.size() > 0) {
                                DcBaseEbaySkuMappingMapper dcBaseEbaySkuMappingMapper = SessionUtil.getSession().getMapper(DcBaseEbaySkuMappingMapper.class);
                                for(DcBaseEbaySkuMapping dcBaseEbaySkuMapping1 : dcBaseEbaySkuMappingList) {
                                    dcBaseEbaySkuMappingMapper.upsertSelective(dcBaseEbaySkuMapping1);
                                }
                            }
                        } else {
                            throw new RuntimeException("调用ebay广告费映射失败, 响应200, 请求参数" + dcBaseFinanceEbayItemDtoList);
                        }
                    }
             //   }
            }catch (Exception e){
                e.printStackTrace();
                throw new RuntimeException("MYBATIS操作DB失败", e);
            }finally {
                SessionUtil.closeSession();
            }
            jobPointLog.setPageIndex(jobPointLog.getPageIndex()+1);
        }while (jobPointLog.getPageIndex() <= totalPage);
        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()));
    }


    public long getEbayPage(long countEbayFee, JobPointLog jobPointLog) {

        if (countEbayFee % jobPointLog.getPageSize() == 0) {
            return countEbayFee / jobPointLog.getPageSize();
        }
        return countEbayFee / jobPointLog.getPageSize() + 1;
    }

}
