package com.bailuntec.job;

import com.alibaba.fastjson.JSON;
import com.bailuntec.domain.constant.EbaySkuMappingRoot;
import com.bailuntec.domain.dto.DcBaseFinanceEbayItemDto;
import com.bailuntec.domain.entity.*;
import com.bailuntec.domain.example.DcBaseFinanceEbayExample;
import com.bailuntec.mapper.DcBaseFinanceEbayItemMapper;
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.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class CalculateEbayItemJob 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.countByExample(DcBaseFinanceEbayExample.newAndCreateCriteria().andBjDateGreaterThanOrEqualTo(jobPointLog.getStartTime()).andBjDateLessThan(jobPointLog.getEndTime()).example());
        }catch (Exception e){
            e.printStackTrace();
            throw new RuntimeException("MYBATIS操作DB失败", e);
        }finally {
            SessionUtil.closeSession();
        }

        long totalPage = getEbayPage(countEbayFee, jobPointLog);

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

                    List<String> list = new ArrayList<>();
                    list.add(dcBaseFinanceEbayItemDto.getItemId());

                    MediaType mediaType = MediaType.parse("application/json");
                    RequestBody body = RequestBody.create(mediaType, JSON.toJSONString(list));
                    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(dcBaseFinanceEbayItemDto.getItemId() + "请求ebay广告费映射失败" + response, e);
                    } finally {
                        if (response != null) {
                            response.close();
                        }
                    }
                    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) {
                                BigDecimal totalUnitPrice = getTotalUnitPrice(dcBaseEbaySkuMappingList);
                                for(DcBaseEbaySkuMapping ebaySkuMapping : dcBaseEbaySkuMappingList) {
                                    DcBaseFinanceEbayItem dcBaseFinanceEbayItem = new DcBaseFinanceEbayItem();
                                    BeanUtils.copyProperties(dcBaseFinanceEbayItem, dcBaseFinanceEbayItemDto);
                                    BigDecimal unitPriceRadio;
                                    if(totalUnitPrice.compareTo(BigDecimal.ZERO) == 0) {
                                        unitPriceRadio = BigDecimal.ONE.divide(BigDecimal.valueOf(dcBaseEbaySkuMappingList.size()), 3, RoundingMode.HALF_EVEN);
                                    }else {
                                        unitPriceRadio = ebaySkuMapping.getSkuPrice().divide(totalUnitPrice, 3, RoundingMode.HALF_EVEN);
                                    }

                                    dcBaseFinanceEbayItem.setSkuRatio(unitPriceRadio);
                                    dcBaseFinanceEbayItem.setSkuAmount(dcBaseFinanceEbayItemDto.getGrossAmount().multiply(unitPriceRadio));
                                    dcBaseFinanceEbayItem.setAccountId(dcBaseFinanceEbayItemDto.getAccountId());
                                    dcBaseFinanceEbayItem.setGrossAmount(dcBaseFinanceEbayItemDto.getGrossAmount());
                                    dcBaseFinanceEbayItem.setAccountEntryType(dcBaseFinanceEbayItemDto.getAccountEntryType());
                                    dcBaseFinanceEbayItem.setBjDate(dcBaseFinanceEbayItemDto.getBjDate());
                                    dcBaseFinanceEbayItem.setGmtDate(dcBaseFinanceEbayItemDto.getGmtDate());
                                    dcBaseFinanceEbayItem.setItemId(dcBaseFinanceEbayItemDto.getItemId());
                                    dcBaseFinanceEbayItem.setEbayId(dcBaseFinanceEbayItemDto.getId());
                                    dcBaseFinanceEbayItem.setCurrency(dcBaseFinanceEbayItemDto.getCurrency());
                                    dcBaseFinanceEbayItem.setExchangeRate(dcBaseFinanceEbayItemDto.getExchangeRate());
                                    dcBaseFinanceEbayItem.setExchangeRateUsd(dcBaseFinanceEbayItemDto.getExchangeRateUsd());
                                    dcBaseFinanceEbayItem.setSkuCount(1);
                                    dcBaseFinanceEbayItem.setBailunSku(ebaySkuMapping.getSkuCode());
                                    dcBaseFinanceEbayItem.setId(null);
                                    if(ebaySkuMapping.getSkuCode() == null) {
                                        dcBaseFinanceEbayItem.setBailunSku("无");
                                    }
                                    DcBaseFinanceEbayItemMapper dcBaseFinanceEbayItemMapper = SessionUtil.getSession().getMapper(DcBaseFinanceEbayItemMapper.class);
                                    dcBaseFinanceEbayItemMapper.insertSelective(dcBaseFinanceEbayItem);
                                }
                            }else {
                                DcBaseFinanceEbayItem dcBaseFinanceEbayItem = new DcBaseFinanceEbayItem();
                                dcBaseFinanceEbayItem.setSkuAmount(BigDecimal.ZERO);
                                dcBaseFinanceEbayItem.setAccountId(dcBaseFinanceEbayItemDto.getAccountId());
                                dcBaseFinanceEbayItem.setGrossAmount(dcBaseFinanceEbayItemDto.getGrossAmount());
                                dcBaseFinanceEbayItem.setAccountEntryType(dcBaseFinanceEbayItemDto.getAccountEntryType());
                                dcBaseFinanceEbayItem.setBjDate(dcBaseFinanceEbayItemDto.getBjDate());
                                dcBaseFinanceEbayItem.setGmtDate(dcBaseFinanceEbayItemDto.getGmtDate());
                                dcBaseFinanceEbayItem.setItemId(dcBaseFinanceEbayItemDto.getItemId());
                                dcBaseFinanceEbayItem.setEbayId(dcBaseFinanceEbayItemDto.getId());
                                dcBaseFinanceEbayItem.setCurrency(dcBaseFinanceEbayItemDto.getCurrency());
                                dcBaseFinanceEbayItem.setExchangeRate(dcBaseFinanceEbayItemDto.getExchangeRate());
                                dcBaseFinanceEbayItem.setExchangeRateUsd(dcBaseFinanceEbayItemDto.getExchangeRateUsd());
                                dcBaseFinanceEbayItem.setId(null);
                                DcBaseFinanceEbayItemMapper dcBaseFinanceEbayItemMapper = SessionUtil.getSession().getMapper(DcBaseFinanceEbayItemMapper.class);
                                dcBaseFinanceEbayItemMapper.insertSelective(dcBaseFinanceEbayItem);
                            }
                        } else {
                            throw new RuntimeException("调用ebay广告费映射失败, 响应200, 请求参数" + dcBaseFinanceEbayItemDto.getItemId());
                        }
                    }
                }
            }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;
    }

    BigDecimal getTotalUnitPrice(List<DcBaseEbaySkuMapping> dcBaseEbaySkuMappingList) {
        BigDecimal totalUnitPrice = BigDecimal.ZERO;
        DcBaseFinanceEbayMapper dcBaseFinanceEbayMapper = SessionUtil.getSession().getMapper(DcBaseFinanceEbayMapper.class);
        for(DcBaseEbaySkuMapping dcBaseEbaySkuMapping : dcBaseEbaySkuMappingList) {
            BigDecimal unitPrice = BigDecimal.ZERO;
            if(dcBaseEbaySkuMapping.getSkuCode() != null) {
                unitPrice = dcBaseFinanceEbayMapper.selectSkuPrice(dcBaseEbaySkuMapping.getSkuCode());
                unitPrice = unitPrice == null ? BigDecimal.ZERO : unitPrice;
            }
            dcBaseEbaySkuMapping.setSkuPrice(unitPrice);
            totalUnitPrice = totalUnitPrice.add(unitPrice);
        }
        return totalUnitPrice;
    }
}
