package com.bailuntec.job;

import com.alibaba.fastjson.JSON;
import com.bailuntec.domain.ShopifyAuth;
import com.bailuntec.domain.entity.DcBaseCompanyAccount;
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.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.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.apache.commons.beanutils.BeanUtils;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.LinkedHashMap;
import java.util.List;

@Slf4j
public class ShopifySyncJob extends PointJob {

    private OkHttpClient okHttpClient = OkHttpUtil.getInstance();
    private PropertiesUtil propertiesUtil = PropertiesUtil.getInstance("const");

    @Override
    public void executeJob(ShardingContext shardingContext, JobPointLog jobPointLog) {

        int totalPage = getCount();
        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.Shopify.code(),pageSize * shardingContext.getShardingItem(), pageSize);
            if(listByPage != null && listByPage.size() > 0) {
                for (JobAccountLog jobAccountLog : listByPage) {
                    LocalDateTime localDateTime = jobAccountLog.getStartTime();
                    do{
                        if (jobAccountLog.getId() == null) {
                            BeanUtils.copyProperties(jobAccountLog, jobPointLog);
                            jobAccountLog.setId(null);
                        }
                        handleCampaign(jobAccountLog);
                        localDateTime = localDateTime.plusDays(1L);
                    }while (!localDateTime.isAfter(jobAccountLog.getEndTime()));
                    jobAccountLog.setStartTime(jobAccountLog.getEndTime());
                    jobAccountLog.setEndTime(jobAccountLog.getStartTime().plusDays(jobAccountLog.getIntervalTime()).isAfter(LocalDateTime.now()) ? LocalDateTime.now() : jobAccountLog.getEndTime().plusDays(jobAccountLog.getIntervalTime()));
                    jobAccountLogMapper = SessionUtil.getSession().getMapper(JobAccountLogMapper.class);
                    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("Shio获取广告费接口错误", e);
        }

    }

    private void handleCampaign(JobAccountLog jobAccountLog) {
        LinkedHashMap<String, String> map = new LinkedHashMap<>();
        DcBaseCompanyAccount dcBaseCompanyAccount = getToken(jobAccountLog);
        ShopifyAuth shopifyAuth = JSON.parseObject(dcBaseCompanyAccount.getAuthJson(), ShopifyAuth.class);
        String endUrl = propertiesUtil.getPropertyAsString("SHOPIFY_URL");
        String str = OkHttpUtil.attachHttpGetParams("https://"+shopifyAuth.getAPIKey()+"/"+shopifyAuth.getPassword()+"/"+shopifyAuth.getHostname()+"/"+ endUrl, map);
        String urlPath = "https://"+shopifyAuth.getAPIKey()+"/"+shopifyAuth.getPassword()+"/"+shopifyAuth.getHostname()+ endUrl;
        Response response = null;
        String palResultStr = null;
        try {
            Request request = new Request.Builder()
                    .get()
                    .url(urlPath)
                    .addHeader("Content-Type", "application/json")
                    .build();
            response = okHttpClient.newCall(request).execute();
            palResultStr = response.body().string();
        } catch (IOException e) {
            throw new RuntimeException(urlPath + "请求wish接口失败" + response, e);
        } finally {
            if (response != null) {
                response.close();
            }
        }

        System.out.println("======"+ palResultStr);
    }

    private DcBaseCompanyAccount getToken(JobAccountLog jobAccountLog) {
        DcBaseCompanyAccountMapper mapper = SessionUtil.getSession().getMapper(DcBaseCompanyAccountMapper.class);
        return  mapper.selectOneByExample(DcBaseCompanyAccountExample.newAndCreateCriteria().andCompanyIdEqualTo(jobAccountLog.getCompanyId()).andAccountIdEqualTo(jobAccountLog.getAccountId()).example());
    }


    private int getCount()  {
        int i = 0;
        try {
            DcBaseCompanyAccountMapper accountMapper = SessionUtil.getSession().getMapper(DcBaseCompanyAccountMapper.class);
            i = (int)accountMapper.countByExample(DcBaseCompanyAccountExample.newAndCreateCriteria().andPlatformIdEqualTo(AccountPlatformType.Shopify.code()).example());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            SessionUtil.closeSession();
        }
        return i;
    }
}
