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

import com.aliyun.odps.Instance;
import com.aliyun.odps.Odps;
import com.aliyun.odps.OdpsException;
import com.aliyun.odps.PartitionSpec;
import com.aliyun.odps.account.Account;
import com.aliyun.odps.account.AliyunAccount;
import com.aliyun.odps.data.Record;
import com.aliyun.odps.data.RecordReader;
import com.aliyun.odps.task.SQLTask;
import com.aliyun.odps.tunnel.TableTunnel;
import com.aliyun.odps.tunnel.TunnelException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.IOException;
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";
    private final static String VPC_ENDPOINT = "http://service.cn-hangzhou-vpc.maxcompute.aliyun-inc.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 String getNowHour() {
        return LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHH"));
    }

    public List<Record> tableTunnelQuery(String project, String table, String partition){
        Account account = new AliyunAccount(ACCESSID, ACCESSKEY);
        Odps odps = new Odps(account);
        odps.setEndpoint(VPC_ENDPOINT);
        odps.setDefaultProject(project);
        TableTunnel tunnel = new TableTunnel(odps);
        List<Record> records = new ArrayList<>();
        RecordReader recordReader = null;
        try {
            TableTunnel.DownloadSession downloadSession = tunnel.createDownloadSession(project, table, new PartitionSpec(partition));
            long count = downloadSession.getRecordCount();
            recordReader = downloadSession.openRecordReader(0, count);
            Record record;
            while ((record = recordReader.read()) != null) {
                records.add(record);
            }
        } catch (Exception e) {
            log.error("tableTunnelQuery error", e);
        } finally {
            if (!Objects.isNull(recordReader)) {
                try {
                    recordReader.close();
                } catch (Exception e) {
                    log.error("error: ", e);
                }
            }
        }
        return records;
    }

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