package com.bailuntec.job;

import com.alibaba.fastjson.JSON;
import com.bailuntec.domain.entity.DcBaseFinanceEbay;
import com.bailuntec.domain.entity.JobAccountLog;
import com.bailuntec.domain.entity.JobPointLog;
import com.bailuntec.domain.example.DcBaseCompanyAccountExample;
import com.bailuntec.domain.example.DcBaseFinanceEbayExample;
import com.bailuntec.domain.example.JobAccountLogExample;
import com.bailuntec.domain.pojo.AccountEntries;
import com.bailuntec.domain.pojo.AccountEntry;
import com.bailuntec.domain.pojo.EbayResult;
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.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 java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;

@Slf4j
public class EbayFinanceSyncJob extends PointJob {
    private PropertiesUtil propertiesUtil = PropertiesUtil.getInstance("const");
    private OkHttpClient client = OkHttpUtil.getInstance();

    @Override
    public void executeJob(ShardingContext shardingContext, JobPointLog jobPointLog) {
        try {
            JobAccountLogMapper jobAccountLogMapper = SessionUtil.getSession().getMapper(JobAccountLogMapper.class);
            int totalPage = getTotalPage(jobPointLog);
            /*
             * 根据不同分片
             * 再分页去处理数据
             */
            int shardingSize = totalPage % shardingContext.getShardingTotalCount() == 0 ? totalPage / shardingContext.getShardingTotalCount() : totalPage / shardingContext.getShardingTotalCount() + 1;
            if (shardingContext.getShardingItem() + 1 < shardingContext.getShardingTotalCount()) {
                totalPage = shardingSize * (shardingContext.getShardingItem() + 1);
            }
            int page = 0;
            if (shardingContext.getShardingItem() > 0)  {
                page = shardingSize * shardingContext.getShardingItem();
            }
            do {
                //拿到账号和任务信息去调接口
                List<JobAccountLog> listByPage = jobAccountLogMapper.getListByPage(12,page * jobPointLog.getPageSize(), jobPointLog.getPageSize());
                if (listByPage != null && listByPage.size() > 0) {
                    for (JobAccountLog jobAccountLog : listByPage) {
                        if (jobAccountLog.getId() == null) { //在任务表无记录
                             BeanUtils.copyProperties(jobAccountLog, jobPointLog);
                            jobAccountLog.setId(null);
                        }
                        callSaasApi(jobAccountLog);

                        if (jobAccountLog.getId() == null) { //在任务表无记录
                            jobAccountLogMapper.insertSelective(jobAccountLog);
                        } else {
                            jobAccountLog.setBjModified(LocalDateTime.now());
                            jobAccountLogMapper.updateByExampleSelective(jobAccountLog,JobAccountLogExample.newAndCreateCriteria().andAccountIdEqualTo(jobAccountLog.getAccountId()).andJobNameEqualTo(jobAccountLog.getJobName()).example());
                        }
                    }
                }
                jobPointLog.setPageIndex(jobPointLog.getPageIndex() + 1);
            } while (jobPointLog.getPageIndex() <= totalPage);
        } catch (Exception e) {
            e.printStackTrace();
            log.warn("Ebay定时同步费用接口错误",e);
        }  finally {
            SessionUtil.closeSession();
        }
    }

    private int getTotalPage(JobPointLog jobPointLog) throws Exception {
        DcBaseCompanyAccountMapper accountMapper = SessionUtil.getSession().getMapper(DcBaseCompanyAccountMapper.class);
        int l = (int)accountMapper.countByExample(DcBaseCompanyAccountExample.newAndCreateCriteria().andPlatformIdEqualTo(12).example());
        return l % jobPointLog.getPageSize() == 0? l % jobPointLog.getPageSize() :  l % jobPointLog.getPageSize() + 1;
    }

    private void callSaasApi(JobAccountLog job)   {
        HashMap<String, Object> map = new HashMap<>(5);
        map.put("account_id",job.getAccountId());
        map.put("AccountEntrySortType","AccountEntryItemNumberAscending");
        map.put("BeginDate", job.getStartTime().minusHours(8).minusMinutes(2));
        map.put("EndDate",job.getEndTime().minusHours(8));
        MediaType mediaType = MediaType.parse("application/json");
        Integer pageNumber = 0;
        DcBaseFinanceEbay dcBaseFinanceEbay = new DcBaseFinanceEbay();
        Response response = null;
        try {
            DcBaseFinanceEbayMapper dcBaseFinanceEbayMapper = SessionUtil.getSession().getMapper(DcBaseFinanceEbayMapper.class);
            do {
                map.put("PageNumber",job.getPageIndex() > 0?job.getPageIndex(): 1);
                RequestBody body = RequestBody.create(mediaType, JSON.toJSONString(map));
                Request request = new Request.Builder()
                        .url(propertiesUtil.getPropertyAsString("EBAY_FINANCE_URL"))
                        .post(body)
                        .addHeader("Content-Type", "application/json")
                        .build();
                response = client.newCall(request).execute();
                log.warn(JSON.toJSONString(map));
                EbayResult ebayResult = JSON.parseObject(response.body().byteStream(), EbayResult.class);
                AccountEntries accountEntries = ebayResult.getAccountEntries();
                if (accountEntries != null) {
                    List<AccountEntry> accountEntryList = accountEntries.getAccountEntry();
                    if (accountEntryList != null && accountEntryList.size() > 0) {
                        for (AccountEntry accountEntry : accountEntryList) {
                            LocalDateTime gmt = LocalDateTime.from(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").parse(accountEntry.getGmtDate_()));
                            dcBaseFinanceEbay.setGmtDate(gmt);
                            dcBaseFinanceEbay.setBjDate(dcBaseFinanceEbay.getGmtDate().plusHours(8));
                            BeanUtils.copyProperties(dcBaseFinanceEbay, accountEntry);
                            if (accountEntry.getGrossAmount_() != null) {
                                dcBaseFinanceEbay.setGrossAmount(accountEntry.getGrossAmount_().getValue());
                                dcBaseFinanceEbay.setCurrency(accountEntry.getGrossAmount_().getCurrency());
                                dcBaseFinanceEbay.setExchangeRate(CallBailunSystem.getExchangeRate(dcBaseFinanceEbay.getCurrency(),"CNY",dcBaseFinanceEbay.getBjDate()));
                            }
                            if (accountEntry.getGrossAmount_() != null) {
                                dcBaseFinanceEbay.setNetAmount(accountEntry.getNetAmount_().getValue());
                            }
                            dcBaseFinanceEbay.setAccountId(job.getAccountId());
                            dcBaseFinanceEbay.setCompanyId(job.getCompanyId());
                            dcBaseFinanceEbay.setBjModified(LocalDateTime.now());
                            int i = dcBaseFinanceEbayMapper.updateByExampleSelective(dcBaseFinanceEbay, DcBaseFinanceEbayExample.newAndCreateCriteria().andAccountIdEqualTo(dcBaseFinanceEbay.getAccountId()).andRefNumberEqualTo(dcBaseFinanceEbay.getRefNumber()).example());
                            if (i == 0) {
                                dcBaseFinanceEbayMapper.insertSelective(dcBaseFinanceEbay);
                            }
                        }
                    }
                }
                pageNumber = ebayResult.getPageNumber();
                job.setPageIndex(job.getPageIndex() + 1);
            } while (job.getPageIndex() <= pageNumber);
            job.setPageIndex(1);
            job.setStartTime(job.getEndTime());
            job.setEndTime(job.getStartTime().plusDays(job.getIntervalTime()).isAfter(LocalDateTime.now()) ? LocalDateTime.now() : job.getEndTime().plusDays(job.getIntervalTime()));
            job.setMessage("success");
        } catch (Exception e) {
            e.printStackTrace();
            job.setMessage(e.getCause().toString());
        } finally {
            if (response != null) {
                response.close();
            }
        }
    }

}
