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.JobAccountLogExample;
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 org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.math.BigDecimal;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
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) {
        int totalPage = getCount(jobPointLog);//分片即将处理的账号总数
         try {
            JobAccountLogMapper jobAccountLogMapper = SessionUtil.getSession().getMapper(JobAccountLogMapper.class);
            /*
             * 根据不同分片
             * 再分页去拿不同的账号执行任务
             */
            int pageSize = totalPage % shardingContext.getShardingTotalCount() == 0?  totalPage / shardingContext.getShardingTotalCount() : totalPage / shardingContext.getShardingTotalCount() + 1;
            //拿到账号集合
            List<JobAccountLog> listByPage = jobAccountLogMapper.getListByPageEbay(12,pageSize * shardingContext.getShardingItem(), pageSize);
            if (listByPage != null && listByPage.size() > 0) {
                LocalDateTime now = LocalDateTime.now();

                for (JobAccountLog jobAccountLog : listByPage) {
                    log.warn("分片: " + shardingContext.getShardingItem() + " 账号: " + jobAccountLog);
                    if (jobAccountLog.getId() == null) { //在任务表无记录
                         BeanUtils.copyProperties(jobAccountLog, jobPointLog);
                        jobAccountLog.setId(null);
                    }
                    if(!jobAccountLog.getStartTime().isAfter(LocalDateTime.now().withHour(0).withMinute(0).withSecond(0))) {
                        callSaasApi(jobAccountLog, shardingContext);
                    }
                    if (jobAccountLog.getId() == null) { //在任务表无记录
                        jobAccountLogMapper = SessionUtil.getSession().getMapper(JobAccountLogMapper.class);
                        jobAccountLogMapper.insertSelective(jobAccountLog);
                    } else {
                        jobAccountLogMapper = SessionUtil.getSession().getMapper(JobAccountLogMapper.class);
                        jobAccountLog.setBjModified(LocalDateTime.now());
                        jobAccountLogMapper.updateByExampleSelective(jobAccountLog,JobAccountLogExample.newAndCreateCriteria().andAccountIdEqualTo(jobAccountLog.getAccountId()).andJobNameEqualTo(jobAccountLog.getJobName()).example());
                    }
                }
            }
            jobPointLog.setStartTime(jobPointLog.getStartTime().plusDays(1));
            jobPointLog.setEndTime(jobPointLog.getEndTime().plusDays(1));
        } catch (Exception e) {
            e.printStackTrace();
            log.warn("Ebay定时同步费用接口错误",e);
        }  finally {
            SessionUtil.closeSession();
        }
    }

    private int getCount(JobPointLog jobPointLog)  {
        int i = 0;
        try {
            DcBaseCompanyAccountMapper accountMapper = SessionUtil.getSession().getMapper(DcBaseCompanyAccountMapper.class);
            i = (int)accountMapper.countByExample(DcBaseCompanyAccountExample.newAndCreateCriteria().andPlatformIdEqualTo(12).andCompanyIdEqualTo(1).andAccountNameNotLike("%test%").example());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            SessionUtil.closeSession();
        }
        return i;
    }

    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;
            //       AccountEntrySortTypeCodeType accountEntrySortTypeCodeType = AccountEntrySortTypeCodeType.ACCOUNT_ENTRY_ITEM_NUMBER_ASCENDING;
            getAccountCall.setViewType(accountHistorySelectionCodeType);
            //       getAccountCall.setAccountEntrySortType(accountEntrySortTypeCodeType);
            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();

        Integer 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) {
                        System.out.println(accountEntry.getDate().getTime().toString());
                        ZoneId zone = ZoneId.systemDefault();
                        LocalDateTime gmt = LocalDateTime.ofInstant(accountEntry.getDate().getTime().toInstant(), zone);
                        //    LocalDateTime gmt = LocalDateTime.from(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").parse(accountEntry.getDate().getTime()));
                        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());
                            log.warn(dcBaseFinanceEbay.getBjDate().toString());
                            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);
                /*int i = dcBaseFinanceEbayMapper.updateByExampleSelective(dcBaseFinanceEbay, DcBaseFinanceEbayExample.newAndCreateCriteria().andRefNumberEqualTo(dcBaseFinanceEbay.getRefNumber() == null ? "" : dcBaseFinanceEbay.getRefNumber()).andItemIdEqualTo(dcBaseFinanceEbay.getItemId() == null ? "" : dcBaseFinanceEbay.getItemId()).andAccountEntryTypeEqualTo(dcBaseFinanceEbay.getAccountEntryType() == null ? "" : dcBaseFinanceEbay.getAccountEntryType()).andGmtDateEqualTo(dcBaseFinanceEbay.getGmtDate()).example());
                if (i == 0) {*/
                if(StringUtils.isBlank(shardingContext.getJobParameter())) {
                    dcBaseFinanceEbayMapper.insertSelective(dcBaseFinanceEbay);
                }else {
                    dcBaseFinanceEbayMapper.insertTestSelective(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().andCompanyIdEqualTo(jobAccountLog.getCompanyId()).andAccountIdEqualTo(jobAccountLog.getAccountId()).example());
    }


}
