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

import cn.hutool.core.util.ObjectUtil;
import cn.iocoder.yudao.framework.common.exception.ErrorCode;
import cn.iocoder.yudao.framework.common.exception.ServiceException;
import cn.iocoder.yudao.framework.common.util.collection.CollectionUtils;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.module.llm.controller.admin.datarefluxconfig.vo.DataRefluxConfigPageReqVO;
import cn.iocoder.yudao.module.llm.dal.dataobject.datarefluxconfig.DataRefluxConfigDO;
import cn.iocoder.yudao.module.llm.dal.dataobject.dataset.DatasetAnswerDO;
import cn.iocoder.yudao.module.llm.dal.dataobject.dataset.DatasetDO;
import cn.iocoder.yudao.module.llm.dal.dataobject.dataset.DatasetQuestionDO;
import cn.iocoder.yudao.module.llm.dal.mysql.datarefluxconfig.DataRefluxConfigMapper;
import cn.iocoder.yudao.module.llm.dal.mysql.dataset.DatasetAnswerMapper;
import cn.iocoder.yudao.module.llm.dal.mysql.dataset.DatasetMapper;
import cn.iocoder.yudao.module.llm.dal.mysql.dataset.DatasetQuestionMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import cn.iocoder.yudao.module.llm.controller.admin.datarefluxdata.vo.*;
import cn.iocoder.yudao.module.llm.dal.dataobject.datarefluxdata.DataRefluxDataDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.llm.dal.mysql.datarefluxdata.DataRefluxDataMapper;

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 DataRefluxDataServiceImpl implements DataRefluxDataService {

    @Resource
    private DataRefluxDataMapper dataRefluxDataMapper;
    @Resource
    private DataRefluxConfigMapper dataRefluxConfigMapper;
    @Resource
    private DatasetMapper datasetMapper;
    @Resource
    private DatasetQuestionMapper datasetQuestionMapper;
    @Resource
    private DatasetAnswerMapper datasetAnswerMapper;

    @Override
    public Long createDataRefluxData(DataRefluxDataSaveReqVO createReqVO) {
        // 插入
        DataRefluxDataDO dataRefluxData = BeanUtils.toBean(createReqVO, DataRefluxDataDO.class);
        LambdaQueryWrapper<DataRefluxConfigDO> eq = new LambdaQueryWrapper<DataRefluxConfigDO>()
                .eq(DataRefluxConfigDO::getModelServiceId, dataRefluxData.getModelServiceId())
                .eq(DataRefluxConfigDO::getModelType, dataRefluxData.getModelType())
                .like(DataRefluxConfigDO::getCreator, dataRefluxData.getCreator());
        List<DataRefluxConfigDO> dataRefluxConfigDOS = dataRefluxConfigMapper.selectList(eq);
        dataRefluxData.setConfigId(dataRefluxConfigDOS.get(0).getId());
        dataRefluxDataMapper.insert(dataRefluxData);
        // 返回
        return dataRefluxData.getId();
    }

    @Override
    public void updateDataRefluxData(DataRefluxDataSaveReqVO updateReqVO) {
        // 校验存在
        validateDataRefluxDataExists(updateReqVO.getId());
        // 更新
        DataRefluxDataDO updateObj = BeanUtils.toBean(updateReqVO, DataRefluxDataDO.class);
        dataRefluxDataMapper.updateById(updateObj);
    }

    @Override
    public void deleteDataRefluxData(Long id) {
        // 校验存在
        validateDataRefluxDataExists(id);
        // 删除
        dataRefluxDataMapper.deleteById(id);
    }

    private void validateDataRefluxDataExists(Long id) {
        if (dataRefluxDataMapper.selectById(id) == null) {
            throw exception(DATA_REFLUX_DATA_NOT_EXISTS);
        }
    }

    @Override
    public DataRefluxDataDO getDataRefluxData(Long id) {
        return dataRefluxDataMapper.selectById(id);
    }

    @Override
    public PageResult<DataRefluxDataDO> getDataRefluxDataPage(DataRefluxDataPageReqVO pageReqVO) {
        return dataRefluxDataMapper.selectPage(pageReqVO);
    }

    @Override
    public PageResult<DataRefluxDataDO> getTheDetails(DataRefluxConfigPageReqVO pageReqVO) {
//        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        // 解析字符串为 LocalDate
        LocalDateTime startDate = null;
        LocalDateTime endDate = null;
        if (pageReqVO.getStartTime() != null&& pageReqVO.getStartTime()!=""){
            startDate = LocalDate.parse(pageReqVO.getStartTime(), formatter).atStartOfDay();;
        }
        if (pageReqVO.getEndTime() != null && pageReqVO.getEndTime()!=""){
            endDate = LocalDate.parse(pageReqVO.getEndTime(), formatter).atTime(LocalTime.MAX);
        }

        // 解析字符串为 LocalDate
        LambdaQueryWrapper<DataRefluxDataDO> eq = new LambdaQueryWrapper<DataRefluxDataDO>()
                .eq(ObjectUtil.isNotNull(pageReqVO.getId()),DataRefluxDataDO::getConfigId, pageReqVO.getId())
                .ge(ObjectUtil.isNotNull(startDate),DataRefluxDataDO::getCreateTime, startDate)
                .le(ObjectUtil.isNotNull(endDate),DataRefluxDataDO::getCreateTime,endDate);
        return dataRefluxDataMapper.selectPage(pageReqVO, eq);
    }

    @Override
    public Long saveDataRefluxData(DataRefluxDataSaveReqVO createReqVO) {
        // 插入
        DataRefluxDataDO dataRefluxData = BeanUtils.toBean(createReqVO, DataRefluxDataDO.class);
        LambdaQueryWrapper<DataRefluxConfigDO> eq = new LambdaQueryWrapper<DataRefluxConfigDO>()
                .eq(DataRefluxConfigDO::getModelServiceId, dataRefluxData.getModelServiceId())
                .eq(DataRefluxConfigDO::getModelType, dataRefluxData.getModelType());
        List<DataRefluxConfigDO> dataRefluxConfigDOS = dataRefluxConfigMapper.selectList(eq);
        if (!dataRefluxConfigDOS.isEmpty()) {
            dataRefluxData.setConfigId(dataRefluxConfigDOS.get(0).getId());
            dataRefluxDataMapper.insert(dataRefluxData);
            // 返回
            return dataRefluxData.getId();
        }
        return 0L;
    }

    @Override
    public void getDataRefluxDataIDs(DataRefluxDataReqVO pageReqVO) {
        LambdaQueryWrapper<DataRefluxDataDO> wrapper = new LambdaQueryWrapper<>();
        if (pageReqVO.getDataids()==null|| pageReqVO.getDataids().size()==0){
            throw exception(new ErrorCode(11000,"改数据回流没有保存的数据"));
        }
        wrapper.in(pageReqVO.getDataids().size()>0,DataRefluxDataDO::getId, pageReqVO.getDataids());
        List<DataRefluxDataDO> dataRefluxDataDOS = dataRefluxDataMapper.selectList(wrapper);
        DatasetDO dataRespVO = BeanUtils.toBean(pageReqVO, DatasetDO.class);
        dataRespVO.setDataLength((long) pageReqVO.getDataids().size());
        dataRespVO.setDatasetCategory(Math.toIntExact(pageReqVO.getDatasetType()));
        if (pageReqVO.getSaveField()==0){
            dataRespVO.setAnnotateProgress(0);
            dataRespVO.setStatus(0);
        }else if (pageReqVO.getSaveField()==1){
            dataRespVO.setAnnotateProgress(100);
            dataRespVO.setStatus(2);
        }
        dataRespVO.setId(null);
        List<DatasetDO> datasetDO = datasetMapper.selectList(new LambdaQueryWrapper<DatasetDO>().eq(DatasetDO::getDatasetName, dataRespVO.getDatasetName()));
        if (!CollectionUtils.isAnyEmpty(datasetDO)){
            throw exception(new ErrorCode(11000,"数据集名称重复"));
        }
        datasetMapper.insert(dataRespVO);
        for (DataRefluxDataDO dataRefluxDataDO : dataRefluxDataDOS){
            DatasetQuestionDO datasetQuestionDO = new DatasetQuestionDO();
            datasetQuestionDO.setDatasetId(dataRespVO.getId());
            datasetQuestionDO.setQuestion(dataRefluxDataDO.getPrompt());
            datasetQuestionDO.setSystem(dataRefluxDataDO.getSystem());
            if (pageReqVO.getSaveField()==0){
                datasetQuestionDO.setStatus(0);
            }else if (pageReqVO.getSaveField()==1){
                datasetQuestionDO.setStatus(2);
            }
            datasetQuestionMapper.insert(datasetQuestionDO);
            if (pageReqVO.getSaveField()==1) {
                DatasetAnswerDO datasetAnswerDO = new DatasetAnswerDO();
                datasetAnswerDO.setDatasetId(dataRespVO.getId());
                datasetAnswerDO.setQuestionId(datasetQuestionDO.getId());
                datasetAnswerDO.setAnswer(dataRefluxDataDO.getResponse());
                datasetAnswerMapper.insert(datasetAnswerDO);
            }
        }

    }

}
