package com.bailuntec.job;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bailuntec.domain.entity.DcBaseCompanyAccount;
import com.bailuntec.domain.entity.JobAmazonAdLog;
import com.bailuntec.domain.example.DcBaseCompanyAccountExample;
import com.bailuntec.domain.example.JobAmazonAdLogExample;
import com.bailuntec.domain.pojo.AmazonAdAuth;
import com.bailuntec.domain.pojo.AmazonAdSuccessResult;
import com.bailuntec.domain.pojo.AmazonURI;
import com.bailuntec.mapper.DcBaseCompanyAccountMapper;
import com.bailuntec.mapper.JobAmazonAdLogMapper;
import com.bailuntec.utils.OkHttpUtil;
import com.bailuntec.utils.PropertiesUtil;
import com.bailuntec.utils.SessionUtil;
import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.SqlSession;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Slf4j
public class AmazonAdGenerateReportIdJob implements SimpleJob {
    private static final PropertiesUtil propertiesUtil = PropertiesUtil.getInstance("const");
    private final OkHttpClient client = OkHttpUtil.getInstance();

    @Override
    public void execute(ShardingContext shardingContext) {

        try (SqlSession sqlSession = SessionUtil.getFactory().openSession(true)) {

            DcBaseCompanyAccountMapper dcBaseCompanyAccountMapper = sqlSession.getMapper(DcBaseCompanyAccountMapper.class);
            JobAmazonAdLogMapper jobAmazonAdLogMapper = sqlSession.getMapper(JobAmazonAdLogMapper.class);

            int platformId = 15;
            List<DcBaseCompanyAccount> dcBaseCompanyAccountList = dcBaseCompanyAccountMapper.selectByExample(DcBaseCompanyAccountExample.newAndCreateCriteria()
                    .andPlatformIdEqualTo(platformId)
                    .andAmazonAdAuthJsonNotEqualTo("")
                    .example());

            for (int i = 17; i <= 19; i++) {
                int finalI = i;
                dcBaseCompanyAccountList
//                        .stream()
//                        .filter(dcBaseCompanyAccount -> dcBaseCompanyAccount.getAccountId().equals(671))
                        .forEach(dcBaseCompanyAccount -> {
                            LocalDateTime reportDate = LocalDateTime.of(2020, 9, finalI, 0, 0);
                            //productAds
                            try {
//                                LocalDateTime reportDate = LocalDateTime.of(2020, 9, 1, 0, 0);

//                            LocalDateTime reportDate = LocalDateTime.now().minusDays(1).minusHours(12);
                                JSONObject jsonObject = new JSONObject();
                                jsonObject.put("reportDate", reportDate.format(DateTimeFormatter.ofPattern("yyyyMMdd")));
                                jsonObject.put("metrics", propertiesUtil.getPropertyAsString("METRICS"));
                                MediaType mediaType = MediaType.parse("application/json");
                                Response response;

                                AmazonAdAuth amazonAdAuth = JSON.parseObject(dcBaseCompanyAccount.getAmazonAdAuthJson(), AmazonAdAuth.class);

                                RequestBody body = RequestBody.create(mediaType, jsonObject.toJSONString());
                                Request request = new Request.Builder()
                                        .url(switchSiteUrl(dcBaseCompanyAccount.getSiteEn(), null))
                                        .post(body)
                                        .addHeader("Authorization", amazonAdAuth.getAccessToken())
                                        .addHeader("Amazon-Advertising-API-ClientId", amazonAdAuth.getClientId())
                                        .addHeader("Amazon-Advertising-API-Scope", amazonAdAuth.getProfileId())
                                        .addHeader("Content-Type", "application/json")
                                        .build();
                                response = client.newCall(request).execute();

                                String string = response.body().string();

                                if (response.isSuccessful()) {
                                    AmazonAdSuccessResult amazonAdSuccessResult = JSON.parseObject(string, AmazonAdSuccessResult.class);


                                    JobAmazonAdLog jobAmazonAdLog = jobAmazonAdLogMapper.selectOneByExample(JobAmazonAdLogExample
                                            .newAndCreateCriteria()
                                            .andAccountIdEqualTo(dcBaseCompanyAccount.getAccountId())
                                            .andCompanyIdEqualTo(dcBaseCompanyAccount.getCompanyId())
                                            .andReportDateEqualTo(reportDate.toLocalDate())
                                            .andTypeEqualTo(1)
                                            .example());

                                    if (jobAmazonAdLog == null) {
                                        jobAmazonAdLog = new JobAmazonAdLog(null,
                                                dcBaseCompanyAccount.getAccountId(),
                                                amazonAdSuccessResult.getReportId(),
                                                reportDate.toLocalDate(),
                                                false,
                                                LocalDateTime.now(),
                                                LocalDateTime.now(),
                                                dcBaseCompanyAccount.getSiteEn(),
                                                dcBaseCompanyAccount.getCompanyId(),
                                                1);
                                    }
                                    //如果已经生成了报告 是否设置为需要重新下载？//yes
                                    else {
                                        jobAmazonAdLog.setReportId(amazonAdSuccessResult.getReportId());
                                        jobAmazonAdLog.setStatus(false);
                                        jobAmazonAdLog.setBjModified(LocalDateTime.now());
                                    }

                                    jobAmazonAdLogMapper.upsert(jobAmazonAdLog);

                                    log.info("生成报告成功，报告日志:{}", JSON.toJSONString(jobAmazonAdLog));

                                } else {
                                    log.error("下载商品报告失败 帐号id :{} 日期:{} response:{} ", dcBaseCompanyAccount.getAccountId(), reportDate, JSON.toJSONString(response));
                                }

                            } catch (Exception ex) {
                                log.error("下载商品报告异常 帐号id :{} 日期:{} 异常信息:{} ", dcBaseCompanyAccount.getAccountId(), reportDate, ex.getMessage(), ex);

                            }

                            //display
                            try {
                                AmazonAdAuth amazonAdAuth = JSON.parseObject(dcBaseCompanyAccount.getAmazonAdAuthJson(), AmazonAdAuth.class);


//                            LocalDateTime reportDate = LocalDateTime.of(2020, 9, 1, 0, 0);

//                                LocalDateTime reportDate = LocalDateTime.now().minusDays(1).minusHours(12);
                                JSONObject jsonObject = new JSONObject();
                                jsonObject.put("reportDate", reportDate.format(DateTimeFormatter.ofPattern("yyyyMMdd")));
                                jsonObject.put("metrics", "campaignName,campaignId,impressions,adGroupId,adGroupName,asin,sku,adId,clicks,cost,currency,attributedConversions1d,attributedConversions7d,attributedConversions14d,attributedConversions30d,attributedConversions1dSameSKU,attributedConversions7dSameSKU,attributedConversions14dSameSKU,attributedConversions30dSameSKU,attributedUnitsOrdered1d,attributedUnitsOrdered7d,attributedUnitsOrdered14d,attributedUnitsOrdered30d,attributedSales1d,attributedSales7d,attributedSales14d,attributedSales30d,attributedSales1dSameSKU,attributedSales7dSameSKU,attributedSales14dSameSKU,attributedSales30dSameSKU");
                                //tactic = "T00020"
                                jsonObject.put("tactic", "T00020");
                                MediaType mediaType = MediaType.parse("application/json");
                                Response response;

                                RequestBody body = RequestBody.create(mediaType, jsonObject.toJSONString());
                                Request request = new Request.Builder()
                                        .url(AmazonURI.getAmazonAdSiteUri(dcBaseCompanyAccount.getSiteEn()).toString() + "/sd/productAds/report")
                                        .post(body)
                                        .addHeader("Authorization", amazonAdAuth.getAccessToken())
                                        .addHeader("Amazon-Advertising-API-ClientId", amazonAdAuth.getClientId())
                                        .addHeader("Amazon-Advertising-API-Scope", amazonAdAuth.getProfileId())
                                        .addHeader("Content-Type", "application/json")
                                        .build();
                                response = client.newCall(request).execute();
                                String string = response.body().string();

                                if (response.isSuccessful()) {

                                    AmazonAdSuccessResult reportResp = JSON.parseObject(string, AmazonAdSuccessResult.class);
                                    JobAmazonAdLog jobAmazonAdLog = jobAmazonAdLogMapper.selectOneByExample(JobAmazonAdLogExample
                                            .newAndCreateCriteria()
                                            .andAccountIdEqualTo(dcBaseCompanyAccount.getAccountId())
                                            .andCompanyIdEqualTo(dcBaseCompanyAccount.getCompanyId())
                                            .andReportDateEqualTo(reportDate.toLocalDate())
                                            .andTypeEqualTo(4)
                                            .example());

                                    if (jobAmazonAdLog == null) {
                                        jobAmazonAdLog = new JobAmazonAdLog();
                                        jobAmazonAdLog.setAccountId(dcBaseCompanyAccount.getAccountId());
                                        jobAmazonAdLog.setCompanyId(dcBaseCompanyAccount.getCompanyId());
                                        jobAmazonAdLog.setBjCreate(LocalDateTime.now());
                                        jobAmazonAdLog.setBjModified(LocalDateTime.now());
                                        jobAmazonAdLog.setReportDate(reportDate.toLocalDate());
                                        jobAmazonAdLog.setType(4);
                                        jobAmazonAdLog.setSiteEn(dcBaseCompanyAccount.getSiteEn());
                                        jobAmazonAdLog.setReportId(reportResp.getReportId());
                                        jobAmazonAdLog.setStatus(false);

                                        jobAmazonAdLogMapper.insert(jobAmazonAdLog);
                                    } else {
                                        jobAmazonAdLog.setStatus(false);
                                        jobAmazonAdLog.setReportId(reportResp.getReportId());
                                        jobAmazonAdLogMapper.updateByPrimaryKeySelective(jobAmazonAdLog);
                                    }

                                    log.info("生成报告成功，报告日志:{}", JSON.toJSONString(jobAmazonAdLog));

                                } else {
                                    log.error("下载展示报告失败 帐号id :{} 日期:{} response:{} ", dcBaseCompanyAccount.getAccountId(), reportDate, JSON.toJSONString(response));
                                }

                            } catch (Exception ex) {
                                log.error("下载展示报告异常 帐号id :{} 日期:{} 异常信息:{} ", dcBaseCompanyAccount.getAccountId(), reportDate, ex.getMessage(), ex);
                            }


                        });
            }
        }

    }

    protected static String switchSiteUrl(String siteEn, String param) {
        switch (siteEn.toUpperCase()) {
            case "UK":
            case "FR":
            case "IT":
            case "ES":
            case "DE":
                return getURL("EU_URL", param);
            case "AU":
            case "JP":
            case "IN":
                return getURL("FE_URL", param);
            case "US":
            case "CA":
            case "MX":
            default:
                return getURL("NA_URL", param);
        }

    }

    protected static String getURL(String siteUrl, String param) {
        if (StringUtils.isBlank(param)) {
            return propertiesUtil.getPropertyAsString(siteUrl) + propertiesUtil.getPropertyAsString("POST_PRODUCT_ADS_REPORT_ID");
        }
        return propertiesUtil.getPropertyAsString(siteUrl) + propertiesUtil.getPropertyAsString("GET_PRODUCT_ADS_REPORT_DOWNLOAD_PREFIX") + param + propertiesUtil.getPropertyAsString("GET_PRODUCT_ADS_REPORT_DOWNLOAD_SUFFIX");
    }
}
