package com.tzld.piaoquan.ad.engine.service.predict.container;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.odps.Instance;
import com.aliyun.odps.Odps;
import com.aliyun.odps.OdpsException;
import com.aliyun.odps.account.Account;
import com.aliyun.odps.account.AliyunAccount;
import com.aliyun.odps.data.Record;
import com.aliyun.odps.task.SQLTask;
import com.tzld.piaoquan.ad.engine.commons.util.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.*;

@Component
public class TopOneVideoContainer {
    private final static Logger log = LoggerFactory.getLogger(TopOneVideoContainer.class);
    Map<Long,List<Long>> videoMap=new HashMap<>();

    @Value("${ad.odps.access.id:LTAIWYUujJAm7CbH}")
    public String odpsAccessId;
    @Value("${ad.odps.access.key:RfSjdiWwED1sGFlsjXv0DlfTnZTG1P}")
    public String odpsAccessKey;
    @Value("${ad.odps.endpoint:http://service.cn.maxcompute.aliyun.com/api}")
    public String odpsEndpoint;
    public static final String sqlExp="select * from top_return_videolist_hh where dt={dt};";

    private Timer timer;

    @PostConstruct
    public void init(){
//        refreshTopVideoIdCache();
//         timer = new Timer();
//         timer.schedule(new TimerTask() {
//             @Override
//             public void run() {
//                 try {
//                     refreshTopVideoIdCache();
//                 }catch (Exception e){
//                     log.error("svc=timerTask taskName=refreshTopVideoIdCache e={}",Arrays.toString(e.getStackTrace()));
//                 }
//             }
//         }, 0);

    }
    public void refreshTopVideoIdCache(){
        Account account = new AliyunAccount(odpsAccessId, odpsAccessKey);
        Odps odps = new Odps(account);
        odps.setEndpoint(odpsEndpoint);
        odps.setDefaultProject("loghubods");
        List<Record> recordList=new ArrayList<>();
        Instance i;
        try {
            i = SQLTask.run(odps, sqlExp.replace("{dt}", DateUtils.getCurrentDateStr("yyyyMMddHH")));
            i.waitForSuccess();
            recordList = SQLTask.getResult(i);
        } catch (OdpsException e) {
            e.printStackTrace();
        }
        Map<Long,List<Long>> tempMap=new HashMap<>();
        for(Record record:recordList){
            List<Long> idList=tempMap.getOrDefault(Long.parseLong(record.get("apptype").toString()),new ArrayList<>());
            if(idList.size()==0){
                tempMap.put(Long.parseLong(record.get("apptype").toString()),idList);
            }
            idList.add(Long.parseLong(record.get("videoid").toString()));
        }
        //保持之前加载的缓存
        if(tempMap.size()!=0){
            videoMap=tempMap;
            log.info("svc=timerTask taskName=refreshTopVideoIdCache status=success videoMap={}",JSONObject.toJSONString(videoMap));
        }
        //缓存加载失败的时候加快更新频率
        if(tempMap.size()==0){
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    try {
                        refreshTopVideoIdCache();
                    }catch (Exception e){
                        log.error("svc=timerTask taskName=refreshTopVideoIdCache e={}",Arrays.toString(e.getStackTrace()));
                    }
                }
            }, 30*1000);
        }else {
            // 计算距离下一个小时的第15分钟还有多少毫秒
            long delay = calculateDelay();
            // 定时任务在每小时的第15分钟执行
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    try {
                        refreshTopVideoIdCache();
                    }catch (Exception e){
                        log.error("svc=timerTask taskName=refreshTopVideoIdCache status=failed e={}",Arrays.toString(e.getStackTrace()));
                    }
                }
            }, delay);
        }

    }

    public boolean inNoAdTopVideo(Long appType,Long videoId){

        if(videoMap.getOrDefault(appType,new ArrayList<>()).contains(videoId)){
            return true;
        }
        return false;
    }

    private static long calculateDelay() {
        long currentTime = System.currentTimeMillis();
        int currentMinute = (int) ((currentTime / 60000) % 60);
        int secondsUntilNextHour = (60 - currentMinute) * 60;
        int secondsUntilNextQuarterHour = (15 - (currentMinute % 15)) * 60;
        long delay = (secondsUntilNextHour + secondsUntilNextQuarterHour) * 1000;
        return delay;
    }

    public static void main(String[] args){
        Account account = new AliyunAccount("LTAIWYUujJAm7CbH", "RfSjdiWwED1sGFlsjXv0DlfTnZTG1P");
        Odps odps = new Odps(account);
        odps.setEndpoint("http://service.cn.maxcompute.aliyun.com/api");
        odps.setDefaultProject("loghubods");
        List<Record> recordList=new ArrayList<>();
        Instance i;
        try {
            i = SQLTask.run(odps, sqlExp.replace("{dt}", DateUtils.getCurrentDateStr("yyyyMMddHH")));
            i.waitForSuccess();
            recordList = SQLTask.getResult(i);
        } catch (OdpsException e) {
            e.printStackTrace();
        }
        Map<Long,List<Long>> tempMap=new HashMap<>();
        for(Record record:recordList){
            List<Long> idList=tempMap.getOrDefault(Long.parseLong(record.get("apptype").toString()),new ArrayList<>());
            if(idList.size()==0){
                tempMap.put(Long.parseLong(record.get("apptype").toString()),idList);
            }
            idList.add(Long.parseLong(record.get("videoid").toString()));
        }
        System.out.println(JSONObject.toJSONString(tempMap));
    }

}
