package com.bailuntec.job;

import com.alibaba.fastjson.JSON;
import com.bailuntec.domain.AdvertResultData;
import com.bailuntec.domain.AdvertResultInfo;
import com.bailuntec.domain.AmazonAdvert;
import com.bailuntec.domain.entity.JobAccountLog;
import com.bailuntec.domain.entity.JobPointLog;
import com.bailuntec.domain.enumerate.AccountPlatformType;
import com.bailuntec.domain.example.DcBaseCompanyAccountExample;
import com.bailuntec.domain.example.JobAccountLogExample;
import com.bailuntec.mapper.DcAmazonAdvertMapper;
import com.bailuntec.mapper.DcBaseCompanyAccountMapper;
import com.bailuntec.mapper.JobAccountLogMapper;
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.ArrayList;
import java.util.HashMap;
import java.util.List;

@Slf4j
public class AmazonFinanceSyncJob 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(AccountPlatformType.Amazon.code(), 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);
                    }
                    callAddTask(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("Amazon广告费定时同步费用接口错误", 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(AccountPlatformType.Amazon.code()).example());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            SessionUtil.closeSession();
        }
        return i;
    }

    public void callAddTask(JobAccountLog job) {
        LocalDateTime localDateTime = job.getStartTime();
        String resultStr = "";
        String str = "[\"campaignName\", \"campaignId\", \"campaignStatus\", \"campaignBudget\", \"attributedConversions1d\", \"attributedUnitsOrdered1d\", \"attributedSales1d\", \"attributedUnitsOrdered7d\", \"attributedSales1d\", \"impressions\", \"clicks\", \"cost\", \"attributedConversions30d\", \"attributedConversions14d\", \"attributedConversions7d\", \"attributedSales30d\", \"attributedSales14d\", \"attributedSales7d\"]";
        HashMap<String, Object> map = new HashMap<>();
        List listTasks = new ArrayList();
        HashMap<String, Object> mapTasks = new HashMap<>();
        HashMap<String, Object> mapTaskInfo = new HashMap<>();
        List listMetrics = JSON.parseObject(str, List.class);
        mapTaskInfo.put("type", "sp");
        mapTaskInfo.put("record_type", "campaigns");
        mapTaskInfo.put("segment", null);
        mapTaskInfo.put("metrics", listMetrics);
        mapTasks.put("account_id", job.getAccountId());
        mapTasks.put("task_type", "amazon:advertising:report");
        mapTasks.put("task_info", mapTaskInfo);
        map.put("app_id", 1);
        listTasks.add(mapTasks);
        map.put("tasks", listTasks);

        MediaType mediaType = MediaType.parse("application/json");
        Response response = null;
        List<List<Integer>> taskIdsLists = new ArrayList<>();
        try {
            do {
                mapTaskInfo.put("report_date", localDateTime.format(DateTimeFormatter.ofPattern("yyyyMMdd")));
                RequestBody body = RequestBody.create(mediaType, JSON.toJSONString(map));

                Request request = new Request.Builder()
                        .url(propertiesUtil.getPropertyAsString("ADDTASK_FINANCE_URL"))
                        .post(body)
                        .addHeader("Content-Type", "application/json")
                        .build();
                response = client.newCall(request).execute();
                AdvertResultInfo advertResult = JSON.parseObject(response.body().string(), AdvertResultInfo.class);
                if (advertResult != null && advertResult.getCode() == 0) {
                    resultStr = advertResult.getTaskIds();
                    List<Integer> idsLists = JSON.parseArray(resultStr, Integer.class);
                    taskIdsLists.add(idsLists);
                }
                localDateTime = localDateTime.plusDays(1L);
            } while (localDateTime.compareTo(job.getEndTime()) <= 0);

            for (List<Integer> taskIdsList : taskIdsLists) {
                callSaasApi(job, taskIdsList);
            }

            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();
            }
        }
    }

    ;

    public void callSaasApi(JobAccountLog job, List<Integer> ids) {
        HashMap<String, Object> map = new HashMap<>(2);
        map.put("app_id", 1);
        map.put("task_ids", ids);
        MediaType mediaType = MediaType.parse("application/json");
        Response response = null;
        try {
            DcAmazonAdvertMapper dcAmazonAdvertMapper = SessionUtil.getSession().getMapper(DcAmazonAdvertMapper.class);

            RequestBody body = RequestBody.create(mediaType, JSON.toJSONString(map));
            Request request = new Request.Builder()
                    .url(propertiesUtil.getPropertyAsString("GETRESULT_FINANCE_URL"))
                    .post(body)
                    .addHeader("Content-Type", "application/json")
                    .build();
            response = client.newCall(request).execute();
            if (response.isSuccessful()) {
                AdvertResultInfo advertResult = JSON.parseObject(response.body().string(), AdvertResultInfo.class);
                if (advertResult != null && advertResult.getCode() == 0) {
                    List<AdvertResultData> accountEntries = advertResult.getResults();
                    if (accountEntries != null && accountEntries.size() > 0) {
                        List<AmazonAdvert> advertList = JSON.parseArray(accountEntries.get(0).getData().get(0), AmazonAdvert.class);
                        for (AmazonAdvert amazonAdvert : advertList) {
                            amazonAdvert.setAccountId(job.getAccountId());
                            amazonAdvert.setCompanyId(job.getCompanyId());
                            dcAmazonAdvertMapper.upsertSelective(amazonAdvert);
                        }
                    }
                } else {
                    throw new RuntimeException("授权错误");
                }
            } else {
                throw new RuntimeException("接口调用失败");
            }
        } catch (Exception e) {
            job.setMessage(e.getMessage());
        } finally {
            if (response != null) {
                response.close();
            }
        }
    }

}
