package com.bailuntec.job;

import com.bailuntec.domain.dto.DcBaseFinanceAmazonItemDto;
import com.bailuntec.domain.dto.DcBaseSkuMappingItemDto;
import com.bailuntec.domain.entity.*;
import com.bailuntec.domain.example.DcBaseFinanceAmazonAdProductExample;
import com.bailuntec.domain.example.DcBaseFinanceAmazonExample;
import com.bailuntec.mapper.DcBaseFinanceAmazonAdProductMapper;
import com.bailuntec.mapper.DcBaseFinanceAmazonItemMapper;
import com.bailuntec.mapper.DcBaseFinanceAmazonMapper;
import com.bailuntec.support.PointJob;
import com.bailuntec.utils.SessionUtil;
import com.dangdang.ddframe.job.api.ShardingContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.BeanUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.List;

@Slf4j
public class CalculateAmazonItemJob extends PointJob {

    @Override
    public void executeJob(ShardingContext shardingContext, JobPointLog jobPointLog) {
        long countAmazon;
        try{
            DcBaseFinanceAmazonAdProductMapper dcBaseFinanceAmazonAdProductMapper = SessionUtil.getSession().getMapper(DcBaseFinanceAmazonAdProductMapper.class);
            countAmazon = dcBaseFinanceAmazonAdProductMapper.countByExample(DcBaseFinanceAmazonAdProductExample.newAndCreateCriteria().andReportDateGreaterThanOrEqualTo(jobPointLog.getStartTime().toLocalDate()).andReportDateLessThan(jobPointLog.getEndTime().toLocalDate()).example());
        }catch (Exception e){
            e.printStackTrace();
            throw new RuntimeException("MYBATIS操作DB失败", e);
        }finally {
            SessionUtil.closeSession();
        }
        long totalPage = getTotalPage(countAmazon, jobPointLog);
        do{
            List<DcBaseFinanceAmazonItemDto> dcBaseFinanceAmazonItemDtoList;
            try{
                DcBaseFinanceAmazonAdProductMapper dcBaseFinanceAmazonAdProductMapper = SessionUtil.getSession().getMapper(DcBaseFinanceAmazonAdProductMapper.class);
                dcBaseFinanceAmazonItemDtoList = dcBaseFinanceAmazonAdProductMapper.selectAmazonItem(jobPointLog);
                for(DcBaseFinanceAmazonItemDto dcBaseFinanceAmazonItemDto : dcBaseFinanceAmazonItemDtoList) {
                    if(dcBaseFinanceAmazonItemDto.getDcBaseSkuMappingList() != null && dcBaseFinanceAmazonItemDto.getDcBaseSkuMappingList().size() > 0) {
                        BigDecimal totalUnitPrice = getTotalUnitPrice(dcBaseFinanceAmazonItemDto.getDcBaseSkuMappingList());
                        for(DcBaseSkuMappingItemDto dcBaseSkuMappingItemDto : dcBaseFinanceAmazonItemDto.getDcBaseSkuMappingList()) {
                            DcBaseFinanceAmazonItem dcBaseFinanceAmazonItem = new DcBaseFinanceAmazonItem();
                            BeanUtils.copyProperties(dcBaseFinanceAmazonItem, dcBaseSkuMappingItemDto);
                            BigDecimal unitPrice = dcBaseSkuMappingItemDto.getUnitPrice() == null ? BigDecimal.ZERO : dcBaseSkuMappingItemDto.getUnitPrice();
                            BigDecimal unitPriceRadio;
                            if(totalUnitPrice.compareTo(BigDecimal.ZERO) == 0) {
                                unitPriceRadio = BigDecimal.ONE.divide(BigDecimal.valueOf(dcBaseFinanceAmazonItemDto.getDcBaseSkuMappingList().size()), 3, RoundingMode.HALF_EVEN);
                            }else {
                                unitPriceRadio = unitPrice.multiply(BigDecimal.valueOf(dcBaseSkuMappingItemDto.getCount())).divide(totalUnitPrice, 3, RoundingMode.HALF_EVEN);
                            }

                            dcBaseFinanceAmazonItem.setSkuRatio(unitPriceRadio);
                            dcBaseFinanceAmazonItem.setSku(dcBaseFinanceAmazonItemDto.getSku());
                            dcBaseFinanceAmazonItem.setAccountId(dcBaseFinanceAmazonItemDto.getAccountId());
                            dcBaseFinanceAmazonItem.setAdGroupId(dcBaseFinanceAmazonItemDto.getAdGroupId());
                            dcBaseFinanceAmazonItem.setAmazonId(dcBaseFinanceAmazonItemDto.getId());
                            dcBaseFinanceAmazonItem.setAsin(dcBaseFinanceAmazonItemDto.getAsin());
                            dcBaseFinanceAmazonItem.setBailunSku(dcBaseSkuMappingItemDto.getBailunSku());
                            dcBaseFinanceAmazonItem.setCampaignId(dcBaseFinanceAmazonItemDto.getCampaignId());
                            dcBaseFinanceAmazonItem.setCompanyId(dcBaseFinanceAmazonItemDto.getCompanyId());
                            dcBaseFinanceAmazonItem.setCost(dcBaseFinanceAmazonItemDto.getCost());
                            dcBaseFinanceAmazonItem.setCurrency(dcBaseFinanceAmazonItemDto.getCurrency());
                            dcBaseFinanceAmazonItem.setExchangeRate(dcBaseFinanceAmazonItemDto.getExchangeRate());
                            dcBaseFinanceAmazonItem.setExchangeRateUsd(dcBaseFinanceAmazonItemDto.getExchangeRateUsd());
                            dcBaseFinanceAmazonItem.setItemId(dcBaseSkuMappingItemDto.getItemId());
                            dcBaseFinanceAmazonItem.setReportDate(dcBaseFinanceAmazonItemDto.getReportDate());
                            dcBaseFinanceAmazonItem.setSkuCost(dcBaseFinanceAmazonItemDto.getCost().multiply(unitPriceRadio));
                            dcBaseFinanceAmazonItem.setSkuCount(dcBaseSkuMappingItemDto.getCount());
                            dcBaseFinanceAmazonItem.setSite(dcBaseFinanceAmazonItemDto.getSiteEn());
                            if(dcBaseFinanceAmazonItem.getBailunSku() == null) {
                                dcBaseFinanceAmazonItem.setBailunSku("无");
                            }
                            if(dcBaseFinanceAmazonItem.getItemId() == null) {
                                dcBaseFinanceAmazonItem.setItemId("无");
                            }
                            DcBaseFinanceAmazonItemMapper dcBaseFinanceAmazonItemMapper = SessionUtil.getSession().getMapper(DcBaseFinanceAmazonItemMapper.class);
                            dcBaseFinanceAmazonItemMapper.insertSelective(dcBaseFinanceAmazonItem);
                        }
                    }else {
                        DcBaseFinanceAmazonItem dcBaseFinanceAmazonItem = new DcBaseFinanceAmazonItem();
                        BeanUtils.copyProperties(dcBaseFinanceAmazonItem, dcBaseFinanceAmazonItemDto);
                        dcBaseFinanceAmazonItem.setAmazonId(dcBaseFinanceAmazonItemDto.getId());
                        dcBaseFinanceAmazonItem.setSite(dcBaseFinanceAmazonItemDto.getSiteEn());
                        dcBaseFinanceAmazonItem.setId(null);
                        dcBaseFinanceAmazonItem.setSkuCost(dcBaseFinanceAmazonItem.getCost());
                        dcBaseFinanceAmazonItem.setSkuRatio(BigDecimal.ONE);
                        DcBaseFinanceAmazonItemMapper dcBaseFinanceAmazonItemMapper = SessionUtil.getSession().getMapper(DcBaseFinanceAmazonItemMapper.class);
                        dcBaseFinanceAmazonItemMapper.insertSelective(dcBaseFinanceAmazonItem);
                    }
                }
            }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()));
    }

    private long getTotalPage(long countAmazon, JobPointLog jobPointLog) {
        if (countAmazon % jobPointLog.getPageSize() == 0) {
            return countAmazon / jobPointLog.getPageSize();
        }
        return countAmazon / jobPointLog.getPageSize() + 1;
    }

    BigDecimal getTotalUnitPrice(List<DcBaseSkuMappingItemDto> dcBaseSkuMappingList) {
        BigDecimal totalUnitPrice = BigDecimal.ZERO;
        for(DcBaseSkuMappingItemDto dcBaseSkuMappingItemDto : dcBaseSkuMappingList) {
            BigDecimal unitPrice = dcBaseSkuMappingItemDto.getUnitPrice() == null ? BigDecimal.ZERO : dcBaseSkuMappingItemDto.getUnitPrice();
            totalUnitPrice = totalUnitPrice.add(unitPrice.multiply(BigDecimal.valueOf(dcBaseSkuMappingItemDto.getCount())));
        }
        return totalUnitPrice;
    }

}
