package com.cmeeting;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import com.cmeeting.pojo.MeetingInfo;
import com.cmeeting.pojo.MeetingRecordTemplate;
import com.cmeeting.service.MeetingRecordTemplateService;
import com.cmeeting.util.SignatureUtil;
import com.cmeeting.util.TencentMeetingApiUtil;
import com.cmeeting.vo.CorpRecordsVO;
import com.google.gson.*;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import javax.annotation.Resource;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

@SpringBootTest
public class MeetingApiTest {

    @Test
    public void test() {
        MeetingInfo info = TencentMeetingApiUtil.getStartAndEndTimeByMeetingId("4391367006554084716");
        System.out.println(info.getMeetingId());
        System.out.println(info.getStartTime());
        System.out.println(info.getEndTime());
    }

    @Resource
    private MeetingRecordTemplateService meetingRecordTemplateService;

    @Test
    public void test2() {
        String userId = "00010786";
        Long templateType = 96L;
        List<Long> list = new ArrayList<>();
        list.add(templateType);
        MeetingRecordTemplate enabledRecordTemplate = meetingRecordTemplateService.getEnabledRecordTemplate(list, userId);
        System.out.println(enabledRecordTemplate.getName());
    }

    @Test
    public void test3() {
        ZonedDateTime now = ZonedDateTime.now();
        long startTime = now.minusDays(31).toEpochSecond();
        long endTime = now.toEpochSecond();

        String TENCENT_APPID = "210468336";
        String TENCENT_SDKI = "28790143843";
        String TENCENT_SECRETID = "0ks7u8cgQ8DGVtlYZeRA9TxZCjvUT3oL";
        String TENCENT_SECRETKEY = "gQU09rkJjiQfiGcUYdhiKq5Ol6LebXg4w7F7Ol0rwvvdv3Xy";
        String TENCENT_ADMIN_USERID = "woaJARCQAAftcvU6GGoOn66rdSZ4IrOA";
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        int page = 1;
        int pageSize = 20;

        String filePath = "D:/desktop/meetTime.txt";
        File file = new File(filePath);



        try {
            int i = 1;
            int sum = 0;
            while (true) {
                String uri = String.format(
                        "/v1/corp/records?start_time=%d&end_time=%d&page=%d&page_size=%d&operator_id=%s&operator_id_type=%d",
                        startTime, endTime, page, pageSize, TENCENT_ADMIN_USERID, 1
                );

                String httpMethod = "GET";
                String nonce = String.valueOf(new Random().nextInt(100000));
                String timestamp = String.valueOf(Instant.now().getEpochSecond());

                // 3. 生成签名
                String signature = SignatureUtil.generateSignature(TENCENT_SECRETID, TENCENT_SECRETKEY, httpMethod, nonce, timestamp, uri, "");
                // 4. 发送请求
                try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
                    HttpGet request = new HttpGet("https://api.meeting.qq.com" + uri);
                    request.setHeader("X-TC-Key", TENCENT_SECRETID);
                    request.setHeader("X-TC-Timestamp", timestamp);
                    request.setHeader("X-TC-Nonce", nonce);
                    request.setHeader("X-TC-Signature", signature);
                    request.setHeader("AppId", TENCENT_APPID);
                    request.setHeader("SdkId", TENCENT_SDKI);

                    // 5. 解析响应
                    String response = EntityUtils.toString(httpClient.execute(request).getEntity());
                    JsonObject jsonResponse = JsonParser.parseString(response).getAsJsonObject();
                    Gson gson = new GsonBuilder()
                            .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
                            .create();

                    // 将 JsonObject 转换为实体类
                    CorpRecordsVO data = gson.fromJson(jsonResponse, CorpRecordsVO.class);
                    if (data != null && data.getRecordMeetings() != null && !data.getRecordMeetings().isEmpty()) {
                        List<CorpRecordsVO.RecordMeeting> meetings = data.getRecordMeetings();
                        for (CorpRecordsVO.RecordMeeting meeting : meetings) {
                            //录制文件未转码完成，跳过 1：录制中 2：转码中 3：转码完成
                            if (meeting.getState() != 3) {
                                continue;
                            }

                            MeetingInfo meetingInfo = TencentMeetingApiUtil.getStartAndEndTimeByMeetingId(meeting.getMeetingId());
                            if (meetingInfo == null) {
                                continue;
                            }
                            LocalDateTime startTime1 = meetingInfo.getStartTime();
                            LocalDateTime endTime1 = meetingInfo.getEndTime();

                            if (startTime1 == null || endTime1 == null) {
                                continue;
                            }

                            String s = startTime1.format(formatter);
                            String e = endTime1.format(formatter);
                            long secondsDiff = ChronoUnit.SECONDS.between(startTime1, endTime1);

                            List<String> list = FileUtil.readLines(file, StandardCharsets.UTF_8);
                            if (CollUtil.isEmpty(list)) {
                                list = new ArrayList<>();
                            }
                            String prin = i + "---->" + s + "---->" + e + "---->" + secondsDiff;
                            list.add(prin);
                            System.out.println(prin);
                            FileUtil.writeLines(list, file, StandardCharsets.UTF_8);

                            sum += secondsDiff;
                            i++;
                        }
                    }
                }
                if (i >= 10000) {
                    System.out.println("sum: " + sum);
                    break;
                }
                page++;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
