package org.dromara.ai.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.ai.domain.AiProviderConfigHistory;
import org.dromara.ai.domain.bo.AiProviderConfigHistoryBo;
import org.dromara.ai.domain.vo.AiProviderConfigHistoryVo;
import org.dromara.ai.mapper.AiProviderConfigHistoryMapper;
import org.dromara.ai.service.AiProviderConfigHistoryService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.List;

/**
 * AI Provider配置历史Service业务层处理
 *
 * @author pengles
 */
@RequiredArgsConstructor
@Service
public class AiProviderConfigHistoryServiceImpl implements AiProviderConfigHistoryService {

    private final AiProviderConfigHistoryMapper baseMapper;

    /**
     * 查询AI Provider配置历史
     */
    @Override
    public AiProviderConfigHistoryVo queryById(Long id) {
        AiProviderConfigHistoryVo vo = baseMapper.selectVoById(id);
        if (vo != null) {
            // 转换操作类型字段
            vo.setOperationTypeStr(convertOperationType(vo.getOperationType()));
        }
        return vo;
    }

    /**
     * 查询AI Provider配置历史列表
     */
    @Override
    public TableDataInfo<AiProviderConfigHistoryVo> queryPageList(AiProviderConfigHistoryBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<AiProviderConfigHistory> lqw = buildQueryWrapper(bo);
        Page<AiProviderConfigHistoryVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        // 转换操作类型字段
        result.getRecords().forEach(vo -> {
            vo.setOperationTypeStr(convertOperationType(vo.getOperationType()));
        });
        return TableDataInfo.build(result);
    }

    /**
     * 查询AI Provider配置历史列表
     */
    @Override
    public List<AiProviderConfigHistoryVo> queryList(AiProviderConfigHistoryBo bo) {
        LambdaQueryWrapper<AiProviderConfigHistory> lqw = buildQueryWrapper(bo);
        List<AiProviderConfigHistoryVo> list = baseMapper.selectVoList(lqw);
        // 转换操作类型字段
        list.forEach(vo -> {
            vo.setOperationTypeStr(convertOperationType(vo.getOperationType()));
        });
        return list;
    }

    /**
     * 构建查询条件
     */
    private LambdaQueryWrapper<AiProviderConfigHistory> buildQueryWrapper(AiProviderConfigHistoryBo bo) {
        LambdaQueryWrapper<AiProviderConfigHistory> lqw = new LambdaQueryWrapper<>();
        lqw.eq(bo.getConfigId() != null, AiProviderConfigHistory::getConfigId, bo.getConfigId());
        lqw.eq(StringUtils.isNotBlank(bo.getProviderName()), AiProviderConfigHistory::getProviderName, bo.getProviderName());
        lqw.eq(StringUtils.isNotBlank(bo.getOperationType()), AiProviderConfigHistory::getOperationType, bo.getOperationType());
        lqw.eq(StringUtils.isNotBlank(bo.getOperationBy()), AiProviderConfigHistory::getOperationBy, bo.getOperationBy());
        // 时间范围查询
        lqw.ge(bo.getOperationTimeStart() != null, AiProviderConfigHistory::getOperationTime, bo.getOperationTimeStart());
        lqw.le(bo.getOperationTimeEnd() != null, AiProviderConfigHistory::getOperationTime, bo.getOperationTimeEnd());
        // 按操作时间倒序排序
        lqw.orderByDesc(AiProviderConfigHistory::getOperationTime);
        return lqw;
    }

    /**
     * 新增AI Provider配置历史
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertByBo(AiProviderConfigHistoryBo bo) {
        AiProviderConfigHistory add = MapstructUtils.convert(bo, AiProviderConfigHistory.class);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 批量删除AI Provider配置历史
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            // 可以添加业务校验逻辑
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    /**
     * 根据配置ID查询历史记录列表
     */
    @Override
    public List<AiProviderConfigHistoryVo> queryByConfigId(Long configId) {
        LambdaQueryWrapper<AiProviderConfigHistory> lqw = new LambdaQueryWrapper<>();
        lqw.eq(AiProviderConfigHistory::getConfigId, configId);
        lqw.orderByDesc(AiProviderConfigHistory::getOperationTime);
        List<AiProviderConfigHistoryVo> list = baseMapper.selectVoList(lqw);
        // 转换操作类型字段
        list.forEach(vo -> {
            vo.setOperationTypeStr(convertOperationType(vo.getOperationType()));
        });
        return list;
    }

    /**
     * 转换操作类型
     */
    private String convertOperationType(String operationType) {
        if (StringUtils.isBlank(operationType)) {
            return "";
        }
        return switch (operationType) {
            case "CREATE" -> "创建";
            case "UPDATE" -> "更新";
            case "DELETE" -> "删除";
            default -> operationType;
        };
    }

}