package com.cmvr.evaluation.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cmvr.common.exception.GlobalException;
import com.cmvr.evaluation.model.domain.AeEvaluation;
import com.cmvr.evaluation.service.AeCallbackService;
import com.cmvr.evaluation.service.ExTiProjectService;
import com.cmvr.evaluation.service.ExViProjectService;
import com.cmvr.evaluation.service.IAeEvaluationService;
import com.cmvr.test.enums.RunModeEnum;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Objects;


@Slf4j
@Service
@RequiredArgsConstructor
public class AeCallbackServiceImpl implements AeCallbackService {

    private final IAeEvaluationService aeEvaluationService;
    private final ExViProjectService exViProjectService;
    private final ExTiProjectService exTiProjectService;

    @Override
    public void callback(AeEvaluation aeEvaluation) {
        String aeId = aeEvaluation.getAeId();
        if (StrUtil.isEmpty(aeId)) {
            throw new GlobalException("AI评估ID不能为空!");
        }
        String result = aeEvaluation.getResult();
        if (StrUtil.isEmpty(result)) {
            throw new GlobalException("AI评估结果不能为空!");
        }
        AeEvaluation byId = aeEvaluationService.getById(aeId);
        if (Objects.isNull(byId)) {
            log.error("ID为 {} 的评估对象不存在!", aeId);
        }
        JSONObject jsonObject = JSON.parseObject(result);
        String overallResult = jsonObject.getString("overall_result");
        log.info("时间：{} id:{} overall_result:{}", LocalDateTime.now(), aeId, overallResult);
        int status;
        if (StrUtil.isNotEmpty(overallResult) && overallResult.equals("成功")) {
            status = 2;
        } else {
            status = 3;
        }
        LambdaUpdateWrapper<AeEvaluation> wrapper = Wrappers.lambdaUpdate();
        wrapper.eq(AeEvaluation::getAeId, aeId)
                .set(AeEvaluation::getResult, result)
                .set(AeEvaluation::getStatus, status); // 评估完成/失败

        boolean update = aeEvaluationService.update(wrapper);
        log.info("时间:{} id:{} update:{}", LocalDateTime.now(), aeId, update);

        // 判断是否是最后一次评估 更改项目状态
        boolean finished = aeEvaluationService.isAllEvaluationsFinished(byId.getInstId());
        if (!finished) {
            return;
        }
        String aeType = aeEvaluation.getAeType();
        if (RunModeEnum.TI_PROJECT.name().equals(aeType)) {
            exTiProjectService.updateProjectStatus(byId.getTaskId(), 2);
        } else {
            exViProjectService.updateStatus(byId.getTaskId());
        }
    }
}
