package com.tangguo.service.impl;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tangguo.common.core.redis.RedisCache;
import com.tangguo.common.exception.ServiceException;
import com.tangguo.common.utils.StringUtils;
import com.tangguo.domain.BbsSensitiveWord;
import com.tangguo.domain.result.DataImportResult;
import com.tangguo.mapper.BbsSensitiveWordMapper;
import com.tangguo.service.IBbsSensitiveWordService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.*;
import java.nio.file.Files;
import java.util.*;

/**
 * 敏感词库Service业务层处理
 *
 * @author ruoyi
 * @date 2025-08-27
 */
@Slf4j
@Service
public class BbsSensitiveWordServiceImpl extends ServiceImpl<BbsSensitiveWordMapper, BbsSensitiveWord> implements IBbsSensitiveWordService {

	private static final String WORD_CACHE_KEY = "sensitive:words";

	@Resource
	private BbsSensitiveWordMapper bbsSensitiveWordMapper;

	@Resource
	private RedisCache redisCache;


	@PostConstruct
	private void initCacheWords() {
		Set<String> dbWords = this.getDbWords();
		this.redisCache.setCacheSet(WORD_CACHE_KEY, new HashSet<>(dbWords));
		log.info("=> 数据库敏感词已缓存，敏感词数量：{}", dbWords.size());
	}


	/**
	 * 查询敏感词
	 *
	 * @return 敏感词
	 */
	@Override
	public Set<String> getDbWords() {
		List<String> dbWords = this.listObjs(
			Wrappers.lambdaQuery(BbsSensitiveWord.class).select(BbsSensitiveWord::getName), Objects::toString
		);
		return new HashSet<>(dbWords);
	}


	/**
	 * 查询敏感词库列表
	 *
	 * @param word 敏感词库
	 * @return 敏感词库
	 */
	@Override
	public List<BbsSensitiveWord> selectBbsSensitiveWordList(BbsSensitiveWord word) {
		LambdaQueryWrapper<BbsSensitiveWord> lqw = Wrappers.lambdaQuery();
		lqw.orderByDesc(BbsSensitiveWord::getCreateTime);
		lqw.like(StringUtils.isNotBlank(word.getName()), BbsSensitiveWord::getName, word.getName());
		return bbsSensitiveWordMapper.selectList(lqw);
	}


	/**
	 * 新增敏感词
	 *
	 * @param word 敏感词
	 */
	@Transactional(rollbackFor = Exception.class)
	@Override
	public void addWord(BbsSensitiveWord word) {
		long wordCount = this.count(
			Wrappers.lambdaQuery(BbsSensitiveWord.class).eq(BbsSensitiveWord::getName, word.getName())
		);
		if (wordCount > 0) {
			throw new ServiceException("添加失败，当前敏感词已存在。");
		}

		BbsSensitiveWord addWord = new BbsSensitiveWord();
		addWord.setName(word.getName());
		addWord.setSort(word.getSort());
		addWord.setEnableStatus(1);
		this.save(addWord);
		this.redisCache.setAddValues(WORD_CACHE_KEY, word.getName());
	}


	/**
	 * 修改敏感词
	 *
	 * @param word 敏感词
	 */
	@Override
	public void editWord(BbsSensitiveWord word) {
		BbsSensitiveWord dbWord = this.getById(word.getId());
		if (Objects.isNull(dbWord)) {
			throw new ServiceException("修改失败，未查询到当前敏感词数据。");
		}

		if (!dbWord.getName().equals(word.getName())) {
			long wordCount = this.count(
				Wrappers.lambdaQuery(BbsSensitiveWord.class).eq(BbsSensitiveWord::getName, word.getName())
			);
			if (wordCount > 0) {
				throw new ServiceException("修改失败，当前敏感词已存在。");
			}
		}

		BbsSensitiveWord updWord = new BbsSensitiveWord();
		updWord.setId(word.getId());
		updWord.setName(word.getName());
		updWord.setSort(word.getSort());
		this.updateById(updWord);

		this.redisCache.setDeleteValues(WORD_CACHE_KEY, dbWord.getName());
		this.redisCache.setAddValues(WORD_CACHE_KEY, word.getName());
	}


	/**
	 * 删除敏感词
	 *
	 * @param wordId 敏感词Id
	 */
	@Override
	public void deleteWord(Long wordId) {
		BbsSensitiveWord dbWord = this.getById(wordId);
		if (Objects.nonNull(dbWord)) {
			this.removeById(wordId);
			this.redisCache.setDeleteValues(WORD_CACHE_KEY, dbWord.getName());
		}
	}


	/**
	 * 导入敏感词
	 *
	 * @param file 铭感词文件
	 * @return 导入结果
	 */
	@Override
	public DataImportResult<String> importWords(MultipartFile file) {
		DataImportResult<String> result = new DataImportResult<>();
		BufferedReader reader = null;
		try {
			// 读取敏感词
			reader = new BufferedReader(new InputStreamReader(file.getInputStream()));
			String word;
			Set<String> words = new LinkedHashSet<>(10);
			while (Objects.nonNull(word = reader.readLine())) {
				if (StrUtil.isNotBlank(word)) {
					words.add(word);
				}
			}

			// 校验敏感词
			Set<String> cacheWords = this.redisCache.getCacheSet(WORD_CACHE_KEY);
			List<String> addWords = new ArrayList<>(words.size());
			for (String w : words) {
				if (cacheWords.contains(w)) {
					DataImportResult.Row<String> row = new DataImportResult.Row<>();
					row.setRowData(w);
					row.setMessage("当前敏感词已存在");
					result.getFailRows().add(row);
				} else {
					addWords.add(w);
				}
			}

			// 添加敏感词
			List<BbsSensitiveWord> newWords = new ArrayList<>(addWords.size());
			for (String addWord : addWords) {
				BbsSensitiveWord newWord = new BbsSensitiveWord();
				newWord.setName(addWord);
				newWords.add(newWord);
			}
			super.saveBatch(newWords);

			// 缓存敏感词
			this.redisCache.setAddValues(WORD_CACHE_KEY, addWords.toArray());

			result.setTotalCount(words.size());
			result.setSuccessCount(addWords.size());
			result.setFailCount(words.size() - addWords.size());

		} catch (Exception e) {
			log.error("=> 导入敏感词失败：", e);
		} finally {
			IoUtil.close(reader);
		}
		return result;
	}

}
