package cn.teammodel;

import cn.teammodel.common.PK;
import cn.teammodel.controller.admin.service.AdminAppraiseService;
import cn.teammodel.repository.*;
import cn.teammodel.manager.notification.DingAlertNotifier;
import cn.teammodel.model.dto.admin.appraise.TimeRangeDto;
import cn.teammodel.model.dto.admin.appraise.UpdateAchievementRuleDto;
import cn.teammodel.model.entity.appraise.*;
import cn.teammodel.model.entity.school.School;
import cn.teammodel.service.EvaluationService;
import cn.teammodel.service.impl.EvaluationServiceImpl;
import com.azure.cosmos.models.PartitionKey;
import com.azure.spring.data.cosmos.core.CosmosTemplate;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.temporal.WeekFields;
import java.util.*;

@SpringBootTest
class TeamModelExtensionApplicationTests {
    @Resource
    CosmosTemplate cosmosTemplate;

    @Autowired
    private DingAlertNotifier notifier;

    @Autowired
    AdminAppraiseService adminAppraiseService;
    @Autowired
    AppraiseRecordRepository appraiseRecordRepository;
    @Autowired
    StudentRepository studentRepository;
    @Autowired
    SchoolRepository schoolRepository;
    @Autowired
    ChatSessionRepository chatSessionRepository;
    @Autowired
    private AppraiseRepository appraiseRepository;

    @Test
    void contextLoads() {
        notifier.send("告警: 测试消息推送封装模块");
    }

    @Test
    public void testCrud() {
        Appraise appraise = new Appraise();
        appraise.setCode("evaluation");
        appraise.setPeriodId("default");
        List<AppraiseTreeNode> nodes = new ArrayList<>();

        // 1
        String rootId = UUID.randomUUID().toString();
        AppraiseTreeNode node = new AppraiseTreeNode();
        node.setId(rootId);
        node.setPid(null);
        node.setName("root");
        node.setScore(0);
        // 2
        AppraiseTreeNode node1 = new AppraiseTreeNode();
        String subId = UUID.randomUUID().toString();
        node1.setId(subId);
        node1.setPid(rootId);
        node1.setName("child-1");
        node1.setScore(0);
        // 3
        AppraiseTreeNode node2 = new AppraiseTreeNode();
        node2.setId(UUID.randomUUID().toString());
        node2.setPid(subId);
        node2.setName("child-2");
        node2.setScore(0);
        nodes.add(node);
        nodes.add(node1);
        nodes.add(node2);
        appraise.setNodes(nodes);

        Appraise saved = cosmosTemplate.insert(appraise, null);
        System.out.println(saved);
    }

    @Test
    public void testSelect() {
        //Appraise saved = appraiseRepository.findBySchoolId("hbcn", new PartitionKey("evaluation"));
        //EvaluationService service = new EvaluationServiceImpl();
        //System.out.println(JSONUtil.parse(service.buildTree(saved.getNodes())).toStringPretty());
        //List<AppraiseTreeNode> nodeById = appraiseRepository.findNodeById("habook", "default", "Appraise", "43e23f03-288c-4012-b5f3-4d5c022739a2");
        //System.out.println(nodeById);

        //System.out.println(schoolRepository.findSemestersById("habook", "50fdecdb-6cbd-4c9a-8dc2-a627f4d6b312"));
        // 评价记录
        long t1 = System.currentTimeMillis();
        //List<Student> student = studentRepository.findByIdAndCode("202201008", String.format(PK.STUDENT, "hbcn"));
        School hbcn = cosmosTemplate.findById("hbcn", School.class);
        long t2 = System.currentTimeMillis();
        System.out.println(t2 - t1);
        //System.out.println(RepositoryUtil.findOne(student, "error"));

        //List<AppraiseRecord> record = appraiseRecordRepository.findScoreAndPraise("fakeStudentId1",
        //        "2023-71fbd0bd-9a46-0490-f6b3-7d16cba4c017",
        //        String.format(PK.PK_APPRAISE_RECORD,"habook")
        //);
        //System.out.println(RepositoryUtil.findOne(record));
        //List<AppraiseRecordItem> record = appraiseRecordRepository.searchNodesByCondition(null,
        //        null, null,"1595321354","2023-71fbd0bd-9a46-0490-f6b3-7d16cba4c017",
        //        String.format(PK.PK_APPRAISE_RECORD,"habook")
        //);
        //System.out.println(record);
    }

    @Test
    public void testUpdate() {
        //EvaluationTree saved = evaluationTreeRepository.findBySchoolId("hbcn", new PartitionKey("evaluation"));
        Appraise saved = appraiseRepository.findBySchoolId("hbcn", new PartitionKey("evaluation"));
        EvaluationService service = new EvaluationServiceImpl();
        //System.out.println(JSONUtil.parse(service.buildTree(saved.getNodes())).toStringPretty());
        appraiseRepository.save(saved);
    }

    @Test
    public void testSave() {
        Appraise appraise = new Appraise();
        appraise.setId("1b69e5d1-5c22-453a-9f67-ed82e1075b62");
        appraise.setCode("Appraise");
        appraise.setPeriodId("default");
        appraise.setSchoolId("test_modified");
        //System.out.println(cosmosTemplate.insert(appraise, PK.of(PK.PK_APPRAISE)));
        // 使用这个似乎必须要有 id,因为是依据 id 判断是否存在 (由 id 和 partitionKey 唯一定位)
        cosmosTemplate.upsert(appraise);
    }

    @Test
    public void testAggressiveFunc() {
        long t1 = System.currentTimeMillis();
        //System.out.println(appraiseRecordRepository.countRecords(null, "AppraiseRecord-habook"));
        //System.out.println(appraiseRecordRepository.countRecords(false, "AppraiseRecord-habook"));
        long t2 = System.currentTimeMillis();
        System.out.println(t2 - t1);
    }

    @Test
    public void testSlice() {
//        CosmosPageRequest pageRequest = new CosmosPageRequest(0, 10, null);
//        Slice<RecordVo> slice;
//        Map<Integer, Integer> countByWeek = new HashMap<>();
//
//        do {
//            slice = appraiseRecordRepository.findAllByAcademicYearId("AppraiseRecord-habook", "2023-71fbd0bd-9a46-0490-f6b3-7d16cba4c017", pageRequest);
//
//            slice.getContent().forEach(item -> {
//                int weekNum = calculateWeekNum(item.getCreateTime());
//                countByWeek.put(weekNum, countByWeek.getOrDefault(weekNum, 0) + 1);
//            });
//
//            if (slice.hasNext()) {
//                pageRequest = (CosmosPageRequest) slice.nextPageable();
//            }
//        } while (slice.hasNext());
//
//        countByWeek.forEach((item, count) -> System.out.println(item + ": " + count));
    }

    private int calculateWeekNum(LocalDateTime localDateTime) {
        // 获取周字段
        WeekFields weekFields = WeekFields.of(Locale.getDefault());
        // 获取当前日期时间所在年的周数
        return localDateTime.get(weekFields.weekOfWeekBasedYear());
    }

    @Test
    public void testIndexData() {
        TimeRangeDto timeRangeDto = new TimeRangeDto();
        timeRangeDto.setAcademicYearId("2023-71fbd0bd-9a46-0490-f6b3-7d16cba4c017");
//        List<RankPo> list = adminAppraiseService.appraiseNodeRank(timeRangeDto);
//        System.out.println(list);
    }

    @Test
    public void batchUpdateTimeFormat() {
        // 批量更改所有 appraiseRecord 的时间格式为标准的 utf
        List<AppraiseRecord> appraiseRecords = appraiseRecordRepository.findByCode(String.format(PK.PK_APPRAISE_RECORD, "habook"));
        for (AppraiseRecord appraiseRecord : appraiseRecords) {
            List<AppraiseRecordItem> nodes = appraiseRecord.getNodes();
            // 处理 node 中的时间
            for (AppraiseRecordItem node : nodes) {
                Long createTime = node.getCreateTime();
                int length = String.valueOf(createTime).length();
                // 让所有十位的时间戳转为十三位
                if (length == 10) {
                    createTime = createTime * 1000L;
                }
                node.setCreateTime(createTime);
            }
            cosmosTemplate.upsert(appraiseRecord);
            System.out.println("更新完毕");
        }
    }

    @Test
    public void batchAppraiseSelect() {
        UpdateAchievementRuleDto ruleDto = new UpdateAchievementRuleDto();
        ruleDto.setPeriodId("template");
        AchievementRule rule = new AchievementRule();
        rule.setId("1");
        rule.setLevelCount(10);
        rule.setPromotionLevel(5);
        rule.setLogo("https://www.baidu.com");
//        ruleDto.setUpdateRule(rule);
        System.out.println(adminAppraiseService.updateAchieveRule(ruleDto));
    }

    @Test
    public void testSelectChatSession() {
//        System.out.println(chatSessionRepository.findByUserId("1595321354"));
        // insert message
//        ChatSession.Message message = new ChatSession.Message();
//        message.setId("0");
//        message.setUserText("aaa");
//        message.setGptText("bbb");
//        message.setCost(0);
//        message.setCreateTime(Instant.now().toEpochMilli());
//        CosmosPatchOperations options = CosmosPatchOperations.create().add("/history/-", message);
//        System.out.println(chatSessionRepository.save("111e90e5-6afd-413b-ae0f-646d957aedf8", PK.of(PK.CHAT_SESSION), ChatSession.class, options));

//        System.out.println(chatSessionRepository.findLatestMessage("111e90e5-6afd-413b-ae0f-646d957aedf8"));
        System.out.println(appraiseRecordRepository.findAppraiseRecordInNames("AppraiseRecord-hbcn", "2023-08b81e76-e7d2-4001-8b4c-e7c789ef4bs1", Arrays.asList("能够感知美")));
    }


}
