package com.ai.da.service.impl;

import com.ai.da.mapper.primary.APIGenerateMapper;
import com.ai.da.mapper.primary.entity.APIGenerate;
import com.ai.da.service.APIGenerateService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.netty.util.internal.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

import static com.ai.da.common.enums.FluxTaskStatusEnum.PENDING_F;
import static com.ai.da.common.enums.WangXiangTaskStatusEnum.PENDING_W;
import static com.ai.da.common.enums.WangXiangTaskStatusEnum.RUNNING;

@Slf4j
@Service
public class APIGenerateServiceImpl extends ServiceImpl<APIGenerateMapper, APIGenerate> implements APIGenerateService {

    @Async
    public void addAPIGenerateRecordAsync(Long accountId, String taskId, String function, String modelName, String status){
        log.info("异步执行添加");
        if (!StringUtil.isNullOrEmpty(taskId) && !StringUtil.isNullOrEmpty(modelName)){
            APIGenerate apiGenerate = new APIGenerate();
            apiGenerate.setAccountId(accountId);
            apiGenerate.setTaskId(taskId);
            apiGenerate.setFunc(function);
            apiGenerate.setModelName(modelName);
            apiGenerate.setStatus(status);
            apiGenerate.setRetry_count(0);
            apiGenerate.setCreateTime(LocalDateTime.now());
            addAPIGenerateRecord(apiGenerate); // 调用同步方法
        }
    }

    @Transactional
    public void addAPIGenerateRecord(APIGenerate apiGenerate) {
        baseMapper.insert(apiGenerate);
    }

    @Async
    public void updateAPIGenerateStatusAsync(String taskId, String status){
        try {
            log.info("异步执行修改");
            QueryWrapper<APIGenerate> qw = new QueryWrapper<>();
            qw.lambda().eq(APIGenerate::getTaskId, taskId);
            APIGenerate apiGenerate = baseMapper.selectOne(qw);
            if (Objects.nonNull(apiGenerate)){
                if (apiGenerate.getStatus().equals("Ready") || apiGenerate.getStatus().equals("SUCCEEDED")
                        || apiGenerate.getStatus().equals("Success")) {
                    log.warn("当前任务 {} 状态已达Success, 不做修改", taskId);
                } else {
                    apiGenerate.setStatus(status);
                    apiGenerate.setUpdateTime(LocalDateTime.now());
                    updateAPIGenerateRecord(apiGenerate);
                }
            } else {
                log.error("任务 {} 在api_generate表中找不到", taskId);
            }
        } catch (Exception e) {
            log.error("更新任务状态失败, taskId: {}, status: {}", taskId, status, e);
        }
    }

    @Transactional
    public void updateAPIGenerateRecord(APIGenerate apiGenerate){
        baseMapper.updateById(apiGenerate);
    }

    public List<APIGenerate> getPendingTaskByStatus(String modelName){
        QueryWrapper<APIGenerate> qw = new QueryWrapper<>();
        // 仅获取还在运行中的任务，成功的，失败的，均需排除
        // flux 任务状态：
        List<String> pendingStatus = Arrays.asList(PENDING_F.getName(), PENDING_W.getName(), RUNNING.getName());
        qw.lambda().eq(APIGenerate::getModelName, modelName).in(APIGenerate::getStatus, pendingStatus);

        return baseMapper.selectList(qw);
    }
}
