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) {
        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.getListByPage(12,pageSize * shardingContext.getShardingItem(), pageSize);
            if (listByPage != null && listByPage.size() > 0) {
                for (JobAccountLog jobAccountLog : listByPage) {
                    log.warn("分片: " + shardingContext.getShardingItem() + " 账号: " + jobAccountLog);
                    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());
                    }
                }
            }
        } 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).example());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            SessionUtil.closeSession();
        }
        return i;
    }

    public 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));
                if (response.isSuccessful()) {
                    EbayResult ebayResult = JSON.parseObject(response.body().byteStream(), EbayResult.class);
                    if (ebayResult != null && ebayResult.getAck() != null && ebayResult.getAck().equals("Success")) {
                        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.getEntriesPerPage();
                    } else {
                        throw new RuntimeException("授权错误");
                    }
                } else {
                    throw new RuntimeException("接口调用失败");
                }
                job.setPageIndex(job.getPageIndex() + 1);
            } while (!pageNumber.equals(0));
            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("执行成功");
        } catch (Exception e) {
            job.setMessage(e.getMessage());
        } finally {
            if (response != null) {
                response.close();
            }
        }
    }

}
