package cn.iocoder.yudao.module.llm.service.modelservice;

import cn.hutool.json.JSONObject;
import cn.iocoder.yudao.framework.common.util.collection.CollectionUtils;
import cn.iocoder.yudao.module.llm.controller.admin.dataset.dto.DataJsonTemplate;
import cn.iocoder.yudao.module.llm.dal.dataobject.modelservice.ModelServiceDO;
import cn.iocoder.yudao.module.llm.dal.mysql.modelservice.ModelServiceMapper;
import cn.iocoder.yudao.module.llm.enums.ModelDeployConstantEnum;
import cn.iocoder.yudao.module.llm.handler.AigcCustomDateTimeDeserializer;
import cn.iocoder.yudao.module.llm.service.http.TrainHttpService;
import cn.iocoder.yudao.module.llm.service.http.vo.AigcModelDeployVO;
import cn.iocoder.yudao.module.llm.service.http.vo.AigcRespVO;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.esotericsoftware.kryo.serializers.TimeSerializers;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;


import javax.annotation.Resource;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;


@Component
@Slf4j
public class ModelServiceTaskSyncService {
    @Resource
    private TrainHttpService trainHttpService;
    @Resource
    private ModelServiceMapper modelServiceMapper;



    @Scheduled(cron ="5 * * * * ?")
    public void syncStatusModels() {
        log.info("ModelServiceTaskSync 定时任务启动");
        LambdaQueryWrapper<ModelServiceDO> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ModelServiceDO::getStatus, 1);
        List<ModelServiceDO> modelServiceList = modelServiceMapper.selectList(wrapper);
        if (!CollectionUtils.isAnyEmpty(modelServiceList)){
            modelServiceList.forEach(modelServiceDO -> {
                Long jobid = modelServiceDO.getJobId();
                if (jobid == null){
                    return;
                }


                // 使用 TypeReference 解析 JSON 字符串为 List<String>
                try {
                    String query = "?filter={\"deploy_name\":"+modelServiceDO.getBaseModelName()+"}";
                    String res = trainHttpService.modelTableQuery(new HashMap<>(), "model_deploy",query);
                    log.info("获取 aigc model_deploy 表数据 info {}",res);
                    ObjectMapper mapper = new ObjectMapper();
                    mapper.registerModule(new JavaTimeModule());
                    SimpleModule module = new SimpleModule();
                    module.addDeserializer(LocalDateTime.class, new AigcCustomDateTimeDeserializer());
                    mapper.registerModule(module);
                    List<AigcModelDeployVO> aigcModelDeployVOS = mapper.readValue(res,new TypeReference<List<AigcModelDeployVO>>() {});
                    Collections.sort(aigcModelDeployVOS, Comparator.comparing(AigcModelDeployVO::getUpdatedAt).reversed());
                    // 获取最新的一条记录
                    if (!aigcModelDeployVOS.isEmpty()) {
                        AigcModelDeployVO latestRecord = aigcModelDeployVOS.get(0);
                        modelServiceMapper.updateStatus(modelServiceDO.getId(), ModelDeployConstantEnum.getStatusByName(latestRecord.getStatus()));
                        log.info("最新的 aigcModelDeployVO: {}", latestRecord);
                    }
                } catch (Exception e) {
                    throw new RuntimeException(e.getMessage());
                }

            });
        }
        log.info("ModelServiceTaskSync 定时任务结束");
    }
}
