package com.bailuntec.job;

import com.bailuntec.domain.entity.DcBaseCompanyAccount;
import com.bailuntec.domain.entity.DcBaseFinanceEbay;
import com.bailuntec.domain.entity.JobAccountLog;
import com.bailuntec.domain.entity.JobPointLog;
import com.bailuntec.domain.enumerate.CurrencyType;
import com.bailuntec.domain.example.DcBaseCompanyAccountExample;
import com.bailuntec.domain.example.DcBaseFinanceEbayExample;
import com.bailuntec.mapper.DcBaseCompanyAccountMapper;
import com.bailuntec.mapper.DcBaseFinanceEbayMapper;
import com.bailuntec.mapper.JobAccountLogMapper;
import com.bailuntec.support.CallBailunSystem;
import com.bailuntec.support.PointJob;
import com.bailuntec.utils.SessionUtil;
import com.dangdang.ddframe.job.api.ShardingContext;
import com.ebay.sdk.ApiContext;
import com.ebay.sdk.ApiCredential;
import com.ebay.sdk.TimeFilter;
import com.ebay.sdk.call.GetAccountCall;
import com.ebay.soap.eBLBaseComponents.AccountEntryType;
import com.ebay.soap.eBLBaseComponents.AccountHistorySelectionCodeType;
import com.ebay.soap.eBLBaseComponents.DetailLevelCodeType;
import com.ebay.soap.eBLBaseComponents.PaginationType;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.math.BigDecimal;
import java.time.*;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Slf4j
public class EbayFinanceAdSyncJob extends PointJob {

    @Override
    public void executeJob(ShardingContext shardingContext, JobPointLog jobPointLog) {

        try {
            JobAccountLogMapper jobAccountLogMapper = SessionUtil.getSession().getMapper(JobAccountLogMapper.class);
            DcBaseFinanceEbayMapper dcBaseFinanceEbayMapper = SessionUtil.getSession().getMapper(DcBaseFinanceEbayMapper.class);

            //拿到账号集合
            List<JobAccountLog> listByPage = jobAccountLogMapper.getListByPageEbay(12);


            LocalDateTime startTime = LocalDateTime.of(jobPointLog.getStartTime().toLocalDate(), LocalTime.of(0, 0));
            LocalDateTime endTime = startTime.plusDays(1);

            if (startTime.toLocalDate().compareTo(LocalDate.now()) < 0) {

                listByPage.parallelStream().forEach(jobAccountLog -> {
                    //先删除再更新
                    dcBaseFinanceEbayMapper.deleteByExample(DcBaseFinanceEbayExample.newAndCreateCriteria()
                            .andBjDateBetween(startTime, endTime)
                            .andAccountIdEqualTo(jobAccountLog.getAccountId())
                            .example());


                    jobAccountLog.setStartTime(startTime.plusHours(15));
                    jobAccountLog.setEndTime(endTime.plusHours(15));

                    this.callSaaSApi(jobAccountLog, shardingContext);

                    log.info("帐号:{} 日期:{} ebay广告费用同步完成", jobAccountLog.getAccountId(), startTime);
                });

                jobPointLog.setStartTime(startTime.plusDays(1));
                jobPointLog.setEndTime(endTime.plusDays(1));
                jobPointLog.setGmtModified(LocalDateTime.now());
            }

        } catch (Exception e) {
            log.error("Ebay定时同步费用接口错误", e);
        } finally {
            SessionUtil.closeSession();
        }
    }


    public void callSaaSApi(JobAccountLog jobAccountLog, ShardingContext shardingContext) {

        try {
            DcBaseCompanyAccount dcBaseCompanyAccount = getToken(jobAccountLog);
            ApiContext apiContext = getApiContext(dcBaseCompanyAccount.getSoapAuthToken());
            GetAccountCall getAccountCall = new GetAccountCall(apiContext);
            getAccountCall.setDetailLevel(new DetailLevelCodeType[]{DetailLevelCodeType.RETURN_ALL});
            AccountHistorySelectionCodeType accountHistorySelectionCodeType = AccountHistorySelectionCodeType.BETWEEN_SPECIFIED_DATES;
            getAccountCall.setViewType(accountHistorySelectionCodeType);

            ZoneId zone = ZoneId.systemDefault();
            Calendar cal = Calendar.getInstance();
            Calendar cal1 = Calendar.getInstance();
            Instant instant = jobAccountLog.getStartTime().atZone(zone).toInstant();
            Date date = Date.from(instant);
            cal.setTime(date);

            Instant instant1 = jobAccountLog.getEndTime().atZone(zone).toInstant();
            Date date1 = Date.from(instant1);
            cal1.setTime(date1);

            TimeFilter timeFilter = new TimeFilter(cal, cal1);
            getAccountCall.setViewPeriod(timeFilter);
            getAccountCall.setInvoiceDate(cal);

            getAccountInfo(getAccountCall, dcBaseCompanyAccount, jobAccountLog, shardingContext);
        } catch (Exception e) {
            e.printStackTrace();
            jobAccountLog.setMessage("执行失败" + e);
        }
    }

    public void getAccountInfo(GetAccountCall getAccountCall, DcBaseCompanyAccount dcBaseCompanyAccount, JobAccountLog jobAccountLog, ShardingContext shardingContext) throws Exception {
        PaginationType paginationType = new PaginationType();

        int pageIndex = 1;
        try {
            do {
                paginationType.setPageNumber(pageIndex);
                getAccountCall.setPagination(paginationType);
                final AccountEntryType[] entries = getAccountCall.getAccount();
                if (entries != null) {
                    DcBaseFinanceEbay dcBaseFinanceEbay = new DcBaseFinanceEbay();

                    for (AccountEntryType accountEntry : entries) {

                        ZoneId zone = ZoneId.systemDefault();
                        LocalDateTime gmt = LocalDateTime.ofInstant(accountEntry.getDate().getTime().toInstant(), zone);

                        dcBaseFinanceEbay.setGmtDate(gmt);
                        dcBaseFinanceEbay.setBjDate(dcBaseFinanceEbay.getGmtDate().minusHours(15L));
                        dcBaseFinanceEbay.setAccountEntryType(accountEntry.getAccountDetailsEntryType() == null ? "" : accountEntry.getAccountDetailsEntryType().value());
                        dcBaseFinanceEbay.setVatPercent(accountEntry.getVATPercent());
                        dcBaseFinanceEbay.setItemId(accountEntry.getItemID());
                        dcBaseFinanceEbay.setTransactionId(accountEntry.getTransactionID());
                        dcBaseFinanceEbay.setOrderLineId(accountEntry.getOrderLineItemID());
                        dcBaseFinanceEbay.setReceivedTopRatedDiscount(accountEntry.isReceivedTopRatedDiscount());
                        dcBaseFinanceEbay.setDescription(accountEntry.getDescription());
                        dcBaseFinanceEbay.setMemo(accountEntry.getMemo());
                        dcBaseFinanceEbay.setRefNumber(accountEntry.getRefNumber());
                        dcBaseFinanceEbay.setTitle(accountEntry.getTitle());
                        dcBaseFinanceEbay.setReportDate(getAccountCall.getInvoiceDate().getTime());
                        if (accountEntry.getGrossDetailAmount() != null) {
                            dcBaseFinanceEbay.setGrossAmount(BigDecimal.valueOf(accountEntry.getGrossDetailAmount().getValue()));
                            dcBaseFinanceEbay.setCurrency(accountEntry.getGrossDetailAmount().getCurrencyID().value());
                            dcBaseFinanceEbay.setExchangeRate(CallBailunSystem.getExchangeRate(dcBaseFinanceEbay.getCurrency(), CurrencyType.CNY.value(), dcBaseFinanceEbay.getBjDate()));
                            dcBaseFinanceEbay.setExchangeRateUsd(CallBailunSystem.getExchangeRate(dcBaseFinanceEbay.getCurrency(), CurrencyType.USD.value(), dcBaseFinanceEbay.getBjDate()));
                        }
                        if (accountEntry.getGrossDetailAmount() != null) {
                            dcBaseFinanceEbay.setNetAmount(BigDecimal.valueOf(accountEntry.getGrossDetailAmount().getValue()));
                        }
                        dcBaseFinanceEbay.setAccountId(dcBaseCompanyAccount.getAccountId());
                        dcBaseFinanceEbay.setCompanyId(dcBaseCompanyAccount.getCompanyId());
                        dcBaseFinanceEbay.setBjModified(LocalDateTime.now());
                        DcBaseFinanceEbayMapper dcBaseFinanceEbayMapper = SessionUtil.getSession().getMapper(DcBaseFinanceEbayMapper.class);

                        dcBaseFinanceEbayMapper.insertSelective(dcBaseFinanceEbay);

                    }
                }
                pageIndex = pageIndex + 1;
            } while (getAccountCall.getHasMoreEntries());
            jobAccountLog.setPageIndex(1);
            jobAccountLog.setStartTime(jobAccountLog.getStartTime().plusDays(jobAccountLog.getIntervalTime()));
            jobAccountLog.setEndTime(jobAccountLog.getEndTime().plusDays(jobAccountLog.getIntervalTime()));
            jobAccountLog.setMessage("执行成功");
        } catch (Exception e) {
            jobAccountLog.setPageIndex(1);
            jobAccountLog.setStartTime(jobAccountLog.getStartTime().plusDays(jobAccountLog.getIntervalTime()));
            jobAccountLog.setEndTime(jobAccountLog.getEndTime().plusDays(jobAccountLog.getIntervalTime()));
            jobAccountLog.setMessage("下载报告失败：" + e);
        }

    }


    private static ApiContext getApiContext(String soapAuthToken) throws IOException {
        ApiContext apiContext = new ApiContext();
        ApiCredential cred = apiContext.getApiCredential();
        cred.seteBayToken(soapAuthToken);
        apiContext.setApiServerUrl("https://api.ebay.com/wsapi");
        return apiContext;
    }


    private DcBaseCompanyAccount getToken(JobAccountLog jobAccountLog) {
        DcBaseCompanyAccountMapper mapper = SessionUtil.getSession().getMapper(DcBaseCompanyAccountMapper.class);
        return mapper.selectOneByExample(DcBaseCompanyAccountExample.newAndCreateCriteria()
                .andAccountIdEqualTo(jobAccountLog.getAccountId())
                .example());
    }


}
