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.exception.ServiceException;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.json.utils.JsonUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.ai.domain.AiProviderConfig;
import org.dromara.ai.domain.bo.AiProviderConfigBo;
import org.dromara.ai.domain.bo.AiProviderConfigHistoryBo;
import org.dromara.ai.domain.vo.AiProviderConfigVo;
import org.dromara.ai.mapper.AiProviderConfigMapper;
import org.dromara.ai.service.AiProviderConfigService;
import org.dromara.ai.service.AiProviderConfigHistoryService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * AI Provider配置Service业务层处理
 *
 * @author pengles
 */
@RequiredArgsConstructor
@Service
public class AiProviderConfigServiceImpl implements AiProviderConfigService {

    private final AiProviderConfigMapper baseMapper;
    private final AiProviderConfigHistoryService configHistoryService;

    /**
     * 查询AI Provider配置
     */
    @Override
    public AiProviderConfigVo queryById(Long id) {
        AiProviderConfigVo vo = baseMapper.selectVoById(id);
        if (vo != null) {
            // 转换启用状态字段
            vo.setEnabledStr(vo.getEnabled() != null && vo.getEnabled() == 1 ? "启用" : "禁用");
        }
        return vo;
    }

    /**
     * 查询AI Provider配置列表
     */
    @Override
    public TableDataInfo<AiProviderConfigVo> queryPageList(AiProviderConfigBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<AiProviderConfig> lqw = buildQueryWrapper(bo);
        Page<AiProviderConfigVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        // 转换启用状态字段
        result.getRecords().forEach(vo -> {
            vo.setEnabledStr(vo.getEnabled() != null && vo.getEnabled() == 1 ? "启用" : "禁用");
        });
        return TableDataInfo.build(result);
    }

    /**
     * 查询AI Provider配置列表
     */
    @Override
    public List<AiProviderConfigVo> queryList(AiProviderConfigBo bo) {
        LambdaQueryWrapper<AiProviderConfig> lqw = buildQueryWrapper(bo);
        List<AiProviderConfigVo> list = baseMapper.selectVoList(lqw);
        // 转换启用状态字段
        list.forEach(vo -> {
            vo.setEnabledStr(vo.getEnabled() != null && vo.getEnabled() == 1 ? "启用" : "禁用");
        });
        return list;
    }

    /**
     * 构建查询条件
     */
    private LambdaQueryWrapper<AiProviderConfig> buildQueryWrapper(AiProviderConfigBo bo) {
        LambdaQueryWrapper<AiProviderConfig> lqw = new LambdaQueryWrapper<>();
        lqw.eq(StringUtils.isNotBlank(bo.getProviderName()), AiProviderConfig::getProviderName, bo.getProviderName());
        lqw.eq(StringUtils.isNotBlank(bo.getProviderType()), AiProviderConfig::getProviderType, bo.getProviderType());
        lqw.eq(bo.getEnabled() != null, AiProviderConfig::getEnabled, bo.getEnabled());
        lqw.eq(bo.getPriority() != null, AiProviderConfig::getPriority, bo.getPriority());
        // 时间范围查询
        lqw.ge(bo.getCreateTimeStart() != null, AiProviderConfig::getCreateTime, bo.getCreateTimeStart());
        lqw.le(bo.getCreateTimeEnd() != null, AiProviderConfig::getCreateTime, bo.getCreateTimeEnd());
        // 按优先级和创建时间排序
        lqw.orderByAsc(AiProviderConfig::getPriority);
        lqw.orderByDesc(AiProviderConfig::getCreateTime);
        return lqw;
    }

    /**
     * 新增AI Provider配置
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertByBo(AiProviderConfigBo bo) {
        AiProviderConfig add = MapstructUtils.convert(bo, AiProviderConfig.class);
        validEntityBeforeSave(add);
        // 设置默认值
        if (add.getEnabled() == null) {
            add.setEnabled(1); // 默认启用
        }
        if (add.getPriority() == null) {
            add.setPriority(0);
        }
        if (add.getWeight() == null) {
            add.setWeight(1);
        }
        if (add.getMaxConcurrency() == null) {
            add.setMaxConcurrency(10);
        }
        if (add.getTimeoutSeconds() == null) {
            add.setTimeoutSeconds(30);
        }
        if (add.getMaxRetries() == null) {
            add.setMaxRetries(3);
        }
        if (add.getHealthCheckInterval() == null) {
            add.setHealthCheckInterval(60);
        }
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
            // 记录历史
            saveConfigHistory(add.getId(), add.getProviderName(), add, "CREATE", null);
        }
        return flag;
    }

    /**
     * 修改AI Provider配置
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateByBo(AiProviderConfigBo bo) {
        // 查询原配置
        AiProviderConfig oldConfig = baseMapper.selectById(bo.getId());
        if (oldConfig == null) {
            throw new ServiceException("Provider配置不存在");
        }
        
        AiProviderConfig update = MapstructUtils.convert(bo, AiProviderConfig.class);
        validEntityBeforeSave(update);
        boolean flag = baseMapper.updateById(update) > 0;
        if (flag) {
            // 查询更新后的配置
            AiProviderConfig newConfig = baseMapper.selectById(bo.getId());
            // 记录历史
            saveConfigHistory(newConfig.getId(), newConfig.getProviderName(), newConfig, "UPDATE", null);
        }
        return flag;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(AiProviderConfig entity) {
        // 检查Provider名称是否重复
        LambdaQueryWrapper<AiProviderConfig> lqw = new LambdaQueryWrapper<>();
        lqw.eq(AiProviderConfig::getProviderName, entity.getProviderName());
        if (entity.getId() != null) {
            lqw.ne(AiProviderConfig::getId, entity.getId());
        }
        Long count = baseMapper.selectCount(lqw);
        if (count > 0) {
            throw new ServiceException("Provider名称已存在");
        }
    }

    /**
     * 批量删除AI Provider配置
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            // 可以添加业务校验逻辑
        }
        // 查询待删除的配置，记录历史
        for (Long id : ids) {
            AiProviderConfig config = baseMapper.selectById(id);
            if (config != null) {
                saveConfigHistory(config.getId(), config.getProviderName(), config, "DELETE", null);
            }
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    /**
     * 启用/禁用Provider配置
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean changeEnabled(Long id, Integer enabled) {
        AiProviderConfig config = baseMapper.selectById(id);
        if (config == null) {
            throw new ServiceException("Provider配置不存在");
        }
        config.setEnabled(enabled);
        boolean flag = baseMapper.updateById(config) > 0;
        if (flag) {
            // 查询更新后的配置
            AiProviderConfig updatedConfig = baseMapper.selectById(id);
            // 记录历史
            String remark = enabled == 1 ? "启用配置" : "禁用配置";
            saveConfigHistory(updatedConfig.getId(), updatedConfig.getProviderName(), updatedConfig, "UPDATE", remark);
        }
        return flag;
    }

    /**
     * 根据Provider名称查询配置
     */
    @Override
    public AiProviderConfigVo queryByProviderName(String providerName) {
        LambdaQueryWrapper<AiProviderConfig> lqw = new LambdaQueryWrapper<>();
        lqw.eq(StringUtils.isNotBlank(providerName), AiProviderConfig::getProviderName, providerName);
        AiProviderConfig config = baseMapper.selectOne(lqw);
        if (config != null) {
            AiProviderConfigVo vo = MapstructUtils.convert(config, AiProviderConfigVo.class);
            vo.setEnabledStr(vo.getEnabled() != null && vo.getEnabled() == 1 ? "启用" : "禁用");
            return vo;
        }
        return null;
    }

    /**
     * 保存配置历史
     */
    private void saveConfigHistory(Long configId, String providerName, AiProviderConfig config, String operationType, String remark) {
        try {
            AiProviderConfigHistoryBo historyBo = new AiProviderConfigHistoryBo();
            historyBo.setConfigId(configId);
            historyBo.setProviderName(providerName);
            // 将配置对象序列化为JSON字符串
            historyBo.setConfigData(JsonUtils.toJsonString(config));
            historyBo.setOperationType(operationType);
            historyBo.setOperationTime(new Date());
            // 获取当前登录用户
            try {
                String username = LoginHelper.getUsername();
                historyBo.setOperationBy(username != null ? username : "system");
            } catch (Exception e) {
                historyBo.setOperationBy("system");
            }
            historyBo.setRemark(remark);
            configHistoryService.insertByBo(historyBo);
        } catch (Exception e) {
            // 记录历史失败不影响主流程，只记录日志
            // 注意：这里不要使用log，因为可能没有引入日志依赖，或者可以导入日志类
            // log.warn("保存Provider配置历史失败", e);
        }
    }

}
