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

import cn.iocoder.yudao.framework.common.util.collection.CollectionUtils;
import cn.iocoder.yudao.module.llm.dal.dataobject.basemodel.BaseModelDO;
import cn.iocoder.yudao.module.llm.dal.dataobject.dataset.DatasetDO;
import cn.iocoder.yudao.module.llm.dal.mysql.dataset.DatasetMapper;
import cn.iocoder.yudao.module.llm.service.async.AsyncDataProcessService;
import cn.iocoder.yudao.module.llm.utils.DataProcessUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import cn.iocoder.yudao.module.llm.controller.admin.dataprocesstask.vo.*;
import cn.iocoder.yudao.module.llm.dal.dataobject.dataprocesstask.DataProcessTaskDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.llm.dal.mysql.dataprocesstask.DataProcessTaskMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.llm.enums.ErrorCodeConstants.*;

/**
 * 数据处理任务 Service 实现类
 *
 * @author 华大大模型
 */
@Service
@Validated
public class DataProcessTaskServiceImpl implements DataProcessTaskService {

    @Resource
    private DataProcessTaskMapper dataProcessTaskMapper;
    @Resource
    private DatasetMapper datasetMapper;
    @Resource
    private AsyncDataProcessService dataProcessService;

    @Override
    public Long createDataProcessTask(DataProcessTaskSaveReqVO createReqVO) {
        validateDataProcessTaskNameExists(createReqVO);
        // 插入
        DataProcessTaskDO dataProcessTask = BeanUtils.toBean(createReqVO, DataProcessTaskDO.class);
        dataProcessTask.setStatus(1);
        dataProcessTaskMapper.insert(dataProcessTask);
        dataProcessService.backups(dataProcessTask);
        // 返回
        return dataProcessTask.getId();
    }
    private void validateDataProcessTaskNameExists(DataProcessTaskSaveReqVO task) {
        LambdaQueryWrapper<DataProcessTaskDO> wrapper = new LambdaQueryWrapper<DataProcessTaskDO>()
                .eq(DataProcessTaskDO::getTaskName, task.getTaskName());

        if (task.getId() != null){
            wrapper.ne(DataProcessTaskDO::getId, task.getId());
        }
        List<DataProcessTaskDO> dataProcessTaskDO = dataProcessTaskMapper.selectList(wrapper);
        if (com.baomidou.mybatisplus.core.toolkit.CollectionUtils.isNotEmpty(dataProcessTaskDO)){
            throw exception(DATA_PROCESS_TASK_NAME_NOT_EXISTS);
        }
    }



    @Override
    public void updateDataProcessTask(DataProcessTaskSaveReqVO updateReqVO) {
        // 校验存在
        validateDataProcessTaskExists(updateReqVO.getId());
        validateDataProcessTaskNameExists(updateReqVO);
        // 更新
        DataProcessTaskDO updateObj = BeanUtils.toBean(updateReqVO, DataProcessTaskDO.class);
        dataProcessTaskMapper.updateById(updateObj);
    }

    @Override
    public void deleteDataProcessTask(Long id) {
        // 校验存在
        validateDataProcessTaskExists(id);
        // 删除
        dataProcessTaskMapper.deleteById(id);
    }

    private void validateDataProcessTaskExists(Long id) {
        if (dataProcessTaskMapper.selectById(id) == null) {
            throw exception(DATA_PROCESS_TASK_NOT_EXISTS);
        }
    }

    @Override
    public DataProcessTaskDO getDataProcessTask(Long id) {
        return dataProcessTaskMapper.selectById(id);
    }

    @Override
    public PageResult<DataProcessTaskDO> getDataProcessTaskPage(DataProcessTaskPageReqVO pageReqVO) {
        return dataProcessTaskMapper.selectPage(pageReqVO);
    }
    @Override
    public PageResult<DataProcessTaskRespVO> getDataProcessTaskPage1(DataProcessTaskPageReqVO pageReqVO) {
        PageResult<DataProcessTaskDO> dataProcessTaskDOPageResult = dataProcessTaskMapper.selectPage(pageReqVO);
        PageResult<DataProcessTaskRespVO> result = BeanUtils.toBean(dataProcessTaskDOPageResult, DataProcessTaskRespVO.class);
        if (!CollectionUtils.isAnyEmpty(dataProcessTaskDOPageResult.getList())){
            List<Long> collect = dataProcessTaskDOPageResult.getList().stream()
                    .map(DataProcessTaskDO::getDatasetId)
                    .collect(Collectors.toList());
            List<Long> collect1 = dataProcessTaskDOPageResult.getList()
                    .stream().map(DataProcessTaskDO::getDatasetPostId).collect(Collectors.toList());
            Set<Long> datasetIds = Stream.concat(collect.stream(), collect1.stream()).collect(Collectors.toSet());
            if (!CollectionUtils.isAnyEmpty(datasetIds)){
                List<Long> mergeDataList = new ArrayList<>(datasetIds);
                List<DatasetDO> datasetDOS = datasetMapper.selectList(new LambdaQueryWrapper<DatasetDO>().in(DatasetDO::getId, mergeDataList));
                Map<Long, DatasetDO> longDataDOMap = cn.iocoder.yudao.framework.common.util.collection.
                        CollectionUtils.convertMap(datasetDOS, DatasetDO::getId);
                result.getList().forEach(item->{
                    DatasetDO datasetDO = longDataDOMap.get(item.getDatasetId());
                    if(datasetDO != null){
                        item.setDatasetName(datasetDO.getDatasetName());
                    }
                    if (item.getStatus() == 2){
                        DatasetDO datasetDO1 = longDataDOMap.get(item.getDatasetPostId());
                        if (datasetDO1 != null){
                            item.setDatasetPostName(datasetDO1.getDatasetName());
                        }
                    }
                });
            }
        }
        return result;
    }
    @Override
    public void stopFineTuningTask(Long id) {
        dataProcessTaskMapper.updateStatus(id, 3);
    }

    @Override
    public void reStartFineTuningTask(Long id) {
        dataProcessService.backups(dataProcessTaskMapper.selectById(id));
        dataProcessTaskMapper.updateStatus(id, 1);
    }



}