package com.tzld.longarticle.recommend.server.service.odps;

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 lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * @author sunxy
 */
@Slf4j
@Component
public class ODPSManager {
    private final static String ACCESSID = "LTAIWYUujJAm7CbH";
    private final static String ACCESSKEY = "RfSjdiWwED1sGFlsjXv0DlfTnZTG1P";
    private final static String ENDPOINT = "http://service.cn.maxcompute.aliyun.com/api";

    public List<Record> query(String sql) {
        Account account = new AliyunAccount(ACCESSID, ACCESSKEY);
        Odps odps = new Odps(account);
        odps.setEndpoint(ENDPOINT);
        odps.setDefaultProject("loghubods");
        Instance i;
        try {
            i = SQLTask.run(odps, sql);
            i.waitForSuccess();
            List<Record> records = SQLTask.getResultByInstanceTunnel(i);
            if (Objects.nonNull(records) && records.size() != 0) {
                return records;
            }
        } catch (Exception e) {
            log.error("odps query error", e);
        }
        return Collections.emptyList();
    }

    public static void main(String[] args) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date());
        cal.add(Calendar.DATE, -1);
        Date date2 = cal.getTime();
        SimpleDateFormat format2 = new SimpleDateFormat("yyyyMMdd");

        Account account = new AliyunAccount(ACCESSID, ACCESSKEY);
        Odps odps = new Odps(account);
        odps.setEndpoint(ENDPOINT);
        odps.setDefaultProject("loghubods");
        String sql = "select * from yesterday_return_top1000 where dt='" + format2.format(date2) + "';";
        Instance i;
        try {
            i = SQLTask.run(odps, sql);
            i.waitForSuccess();
            List<Record> records = SQLTask.getResult(i);
            for (Record r : records) {
                System.out.println(Integer.parseInt(r.get(0).toString()));
                System.out.println(r.get(1).toString());
            }
        } catch (OdpsException e) {
            e.printStackTrace();
        }
    }
}
