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.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.ai.domain.AiSensitiveWord;
import org.dromara.ai.domain.bo.AiSensitiveWordBo;
import org.dromara.ai.domain.vo.AiSensitiveWordVo;
import org.dromara.ai.mapper.AiSensitiveWordMapper;
import org.dromara.ai.service.AiSensitiveWordService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * AI敏感词Service业务层处理
 *
 * @author pengles
 */
@RequiredArgsConstructor
@Service
public class AiSensitiveWordServiceImpl implements AiSensitiveWordService {

    private final AiSensitiveWordMapper baseMapper;

    /**
     * 查询AI敏感词
     */
    @Override
    public AiSensitiveWordVo queryById(Long id) {
        AiSensitiveWordVo vo = baseMapper.selectVoById(id);
        if (vo != null) {
            convertFields(vo);
        }
        return vo;
    }

    /**
     * 查询AI敏感词列表
     */
    @Override
    public TableDataInfo<AiSensitiveWordVo> queryPageList(AiSensitiveWordBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<AiSensitiveWord> lqw = buildQueryWrapper(bo);
        Page<AiSensitiveWordVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        result.getRecords().forEach(this::convertFields);
        return TableDataInfo.build(result);
    }

    /**
     * 查询AI敏感词列表
     */
    @Override
    public List<AiSensitiveWordVo> queryList(AiSensitiveWordBo bo) {
        LambdaQueryWrapper<AiSensitiveWord> lqw = buildQueryWrapper(bo);
        List<AiSensitiveWordVo> list = baseMapper.selectVoList(lqw);
        list.forEach(this::convertFields);
        return list;
    }

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

    /**
     * 转换字段（用于显示）
     */
    private void convertFields(AiSensitiveWordVo vo) {
        // 转换启用状态
        vo.setEnabledStr(vo.getEnabled() != null && vo.getEnabled() == 1 ? "启用" : "禁用");
        // 转换词类型
        vo.setWordTypeStr(convertWordType(vo.getWordType()));
    }

    /**
     * 转换词类型
     */
    private String convertWordType(String wordType) {
        if (StringUtils.isBlank(wordType)) {
            return "";
        }
        return switch (wordType) {
            case "PROFANITY" -> "脏话";
            case "HATE_SPEECH" -> "仇恨言论";
            case "VIOLENCE" -> "暴力内容";
            case "SEXUAL_CONTENT" -> "性内容";
            case "ILLEGAL_ACTIVITY" -> "非法活动";
            case "PERSONAL_INFO" -> "个人信息";
            case "SPAM" -> "垃圾信息";
            case "MALICIOUS_CODE" -> "恶意代码";
            case "POLITICAL_SENSITIVE" -> "政治敏感";
            case "COMMERCIAL_AD" -> "商业广告";
            default -> wordType;
        };
    }

    /**
     * 新增AI敏感词
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertByBo(AiSensitiveWordBo bo) {
        AiSensitiveWord add = MapstructUtils.convert(bo, AiSensitiveWord.class);
        validEntityBeforeSave(add);
        // 设置默认值
        if (add.getEnabled() == null) {
            add.setEnabled(1); // 默认启用
        }
        if (add.getPriority() == null) {
            add.setPriority(0);
        }
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改AI敏感词
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateByBo(AiSensitiveWordBo bo) {
        AiSensitiveWord update = MapstructUtils.convert(bo, AiSensitiveWord.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

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

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

    /**
     * 启用/禁用敏感词
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean changeEnabled(Long id, Integer enabled) {
        AiSensitiveWord word = baseMapper.selectById(id);
        if (word == null) {
            throw new ServiceException("敏感词不存在");
        }
        word.setEnabled(enabled);
        return baseMapper.updateById(word) > 0;
    }

    /**
     * 根据词类型获取启用的敏感词集合
     */
    @Override
    public Set<String> getEnabledWordsByType(String wordType) {
        LambdaQueryWrapper<AiSensitiveWord> lqw = new LambdaQueryWrapper<>();
        lqw.eq(AiSensitiveWord::getWordType, wordType);
        lqw.eq(AiSensitiveWord::getEnabled, 1);
        List<AiSensitiveWord> list = baseMapper.selectList(lqw);
        return list.stream()
                .map(AiSensitiveWord::getWord)
                .collect(Collectors.toSet());
    }

    /**
     * 获取所有启用的敏感词集合（按类型分组）
     */
    @Override
    public Map<String, Set<String>> getAllEnabledWords() {
        LambdaQueryWrapper<AiSensitiveWord> lqw = new LambdaQueryWrapper<>();
        lqw.eq(AiSensitiveWord::getEnabled, 1);
        List<AiSensitiveWord> list = baseMapper.selectList(lqw);
        
        Map<String, Set<String>> result = new HashMap<>();
        for (AiSensitiveWord word : list) {
            result.computeIfAbsent(word.getWordType(), k -> new HashSet<>())
                    .add(word.getWord());
        }
        return result;
    }

}