package org.jk.rag.service.impl;

import org.jk.common.core.utils.MapstructUtils;
import org.jk.common.core.utils.StringUtils;
import org.jk.common.mybatis.core.page.TableDataInfo;
import org.jk.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.jk.common.mybatis.helper.DataPermissionHelper;
import org.jk.rag.domain.ModelConfig;
import org.jk.rag.domain.bo.ModelConfigBo;
import org.jk.rag.domain.dto.ConfigReqDTO;
import org.jk.rag.domain.vo.ModelConfigVo;
import org.jk.rag.mapper.ModelConfigMapper;
import org.jk.rag.service.IModelConfigService;
import org.jk.system.domain.SysConfig;
import org.jk.system.domain.vo.SysConfigVo;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 模型配置Service业务层处理
 *
 * @author Lion Li
 * @date 2026-01-19
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class ModelConfigServiceImpl implements IModelConfigService {

    private final ModelConfigMapper baseMapper;

    /**
     * 查询模型配置
     *
     * @param id 主键
     * @return 模型配置
     */
    @Override
    public ModelConfigVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询模型配置列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 模型配置分页列表
     */
    @Override
    public TableDataInfo<ModelConfigVo> queryPageList(ModelConfigBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<ModelConfig> lqw = buildQueryWrapper(bo);
        Page<ModelConfigVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的模型配置列表
     *
     * @param bo 查询条件
     * @return 模型配置列表
     */
    @Override
    public List<ModelConfigVo> queryList(ModelConfigBo bo) {
        LambdaQueryWrapper<ModelConfig> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<ModelConfig> buildQueryWrapper(ModelConfigBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<ModelConfig> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(ModelConfig::getId);
        lqw.eq(StringUtils.isNotBlank(bo.getModel()), ModelConfig::getModel, bo.getModel());
        lqw.eq(StringUtils.isNotBlank(bo.getApiKey()), ModelConfig::getApiKey, bo.getApiKey());
        lqw.eq(StringUtils.isNotBlank(bo.getUrl()), ModelConfig::getUrl, bo.getUrl());
        lqw.eq(StringUtils.isNotBlank(bo.getMaxToken()), ModelConfig::getMaxToken, bo.getMaxToken());
        lqw.eq(StringUtils.isNotBlank(bo.getModelType()), ModelConfig::getModelType, bo.getModelType());
        lqw.eq(StringUtils.isNotBlank(bo.getFlg()), ModelConfig::getFlg, bo.getFlg());
        return lqw;
    }

    /**
     * 新增模型配置
     *
     * @param bo 模型配置
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(ModelConfigBo bo) {
        ModelConfig add = MapstructUtils.convert(bo, ModelConfig.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改模型配置
     *
     * @param bo 模型配置
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(ModelConfigBo bo) {
        ModelConfig update = MapstructUtils.convert(bo, ModelConfig.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(ModelConfig entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除模型配置信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }
    @Override
    public List<ModelConfigVo> queryRerankList(ModelConfigBo bo) {
        bo.setFlg("1");
        LambdaQueryWrapper<ModelConfig> lqw = buildQueryWrapper(bo);
        List<ModelConfigVo> result = baseMapper.queryConfig();
        //List<ModelConfigVo> result = DataPermissionHelper.ignore(() -> baseMapper.selectVoList(lqw));
        return result;
    }

    @Override
    public List<ModelConfigVo> queryModelList(ModelConfigBo bo) {
        LambdaQueryWrapper<ModelConfig> lqw = buildQueryWrapper(bo);
        List<ModelConfigVo> result = DataPermissionHelper.ignore(() -> baseMapper.selectVoList(lqw));
        return result;
    }

    @Override
    public int updateStatus(Long id) {
        ModelConfig modelConfig = new ModelConfig();
        modelConfig.setFlg("0");
        LambdaQueryWrapper<ModelConfig> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ModelConfig::getFlg,"1");
        baseMapper.update(modelConfig,wrapper);
        modelConfig.setId(id);
        modelConfig.setFlg("1");

        return baseMapper.updateById(modelConfig);
    }

    @Override
    public ConfigReqDTO queryConfig() {
        List<SysConfig> list = baseMapper.queryConfigTypeN();
        ConfigReqDTO configReqDTO = new ConfigReqDTO();
        for (SysConfig sysConfig : list) {
            if(sysConfig.getConfigKey().equals("model")) {
                configReqDTO.setModel(sysConfig.getConfigValue());
            } else if(sysConfig.getConfigKey().equals("rerank_model")) {
                configReqDTO.setRerankModel(sysConfig.getConfigValue());
            } else if(sysConfig.getConfigKey().equals("embedding_model")) {
                configReqDTO.setEmbeddingModel(sysConfig.getConfigValue());
            }
        }
        return configReqDTO;
    }

    @Override
    public void editSysConfig(ModelConfigBo bo) {
        baseMapper.editSysConfig(bo.getModel(), "model");
        baseMapper.editSysConfig(bo.getEmbeddingModel(), "embedding_model");
        baseMapper.editSysConfig(bo.getRerankModel(), "rerank_model");
    }
}
