package com.ruoyi.project.service.impl;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import com.ruoyi.common.core.domain.platform.vo.PlatformUserVO;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.project.domain.TrsSensitiveWords;
import com.ruoyi.project.domain.TrsSensitiveWordsTenant;
import com.ruoyi.project.mapper.TrsSensitiveWordsMapper;
import com.ruoyi.project.mapper.TrsSensitiveWordsTenantMapper;
import com.ruoyi.project.service.ITrsSensitiveWordsService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import static com.ruoyi.common.utils.ShiroUtils.getSubject;

@Service
public class TrsSensitiveWordsServiceImpl implements ITrsSensitiveWordsService {

    @Autowired
    private TrsSensitiveWordsMapper trsSensitiveWordsMapper;

    @Autowired
    private TrsSensitiveWordsTenantMapper trsSensitiveWordsTenantMapper;

    private boolean isPlatformAdmin() {
        Object principal = getSubject().getPrincipal();
        return principal instanceof PlatformUserVO;
    }

    @Override
    public TrsSensitiveWords selectTrsSensitiveWordsById(Long id) {
        if (id == null) {
            throw new IllegalArgumentException("ID不能为空");
        }

        if (isPlatformAdmin()) {
            return trsSensitiveWordsMapper.selectTrsSensitiveWordsById(id);
        } else {
            TrsSensitiveWordsTenant tenantResult = trsSensitiveWordsTenantMapper.selectTrsSensitiveWordsById(id);
            return convertFromTenantEntity(tenantResult);
        }
    }

    @Override
    public List<TrsSensitiveWords> selectTrsSensitiveWordsList(TrsSensitiveWords query) {
        if (isPlatformAdmin()) {
            // 平台管理员查询主表
            return trsSensitiveWordsMapper.selectTrsSensitiveWordsList(query);
        } else {
            // 租户用户查询租户表
            List<TrsSensitiveWordsTenant> tenantResults = trsSensitiveWordsTenantMapper.selectTrsSensitiveWordsList(convertToTenantEntity(query));
            return tenantResults.stream()
                    .map(this::convertFromTenantEntity)
                    .collect(Collectors.toList());
        }
    }

    // 其他方法保持不变...
    @Override
    public int insertTrsSensitiveWords(TrsSensitiveWords trsSensitiveWords) {
        if (isPlatformAdmin()) {
            List<TrsSensitiveWords> sensitiveWords = trsSensitiveWordsMapper.selectTrsWordsListByErrorWord(trsSensitiveWords.getWrongWord());
            if (!sensitiveWords.isEmpty()) {
                return 401;
            }
            return trsSensitiveWordsMapper.insertTrsSensitiveWords(trsSensitiveWords);
        } else {
            List<TrsSensitiveWordsTenant> sensitiveWords = trsSensitiveWordsTenantMapper.selectTrsWordsListByErrorWord(trsSensitiveWords.getWrongWord());
            if (!sensitiveWords.isEmpty()) {
                return 401;
            }
            TrsSensitiveWordsTenant tenantEntity = convertToTenantEntity(trsSensitiveWords);
            return trsSensitiveWordsTenantMapper.insertTrsSensitiveWords(tenantEntity);
        }
    }

    @Override
    public int updateTrsSensitiveWords(TrsSensitiveWords trsSensitiveWords) {
        if (isPlatformAdmin()) {
            return trsSensitiveWordsMapper.updateTrsSensitiveWords(trsSensitiveWords);
        } else {
            TrsSensitiveWordsTenant tenantEntity = convertToTenantEntity(trsSensitiveWords);
            return trsSensitiveWordsTenantMapper.updateTrsSensitiveWords(tenantEntity);
        }
    }

    @Override
    public int deleteTrsSensitiveWordsByIds(String ids) {
        if (isPlatformAdmin()) {
            return trsSensitiveWordsMapper.deleteTrsSensitiveWordsByIds(Convert.toStrArray(ids));
        } else {
            return trsSensitiveWordsTenantMapper.deleteTrsSensitiveWordsByIds(Convert.toStrArray(ids));
        }
    }

    @Override
    public int deleteTrsSensitiveWordsById(Long id) {
        if (isPlatformAdmin()) {
            return trsSensitiveWordsMapper.deleteTrsSensitiveWordsById(id);
        } else {
            return trsSensitiveWordsTenantMapper.deleteTrsSensitiveWordsById(id);
        }
    }

    @Override
    @Transactional
    public String importWords(List<TrsSensitiveWords> wordList, boolean updateSupport) {
        StringBuilder message = new StringBuilder("导入成功").append(System.lineSeparator());

        for (TrsSensitiveWords word : wordList) {
            word.setTime(new Date());

            if (isPlatformAdmin()) {
                handleMainImport(word, updateSupport, message);
            } else {
                handleTenantImport(convertToTenantEntity(word), updateSupport, message);
            }
        }
        return message.toString();
    }

    private void handleMainImport(TrsSensitiveWords word, boolean updateSupport, StringBuilder message) {
        if (word.getWrongWord() == null || word.getWrongWord().trim().isEmpty()) {
            return;
        }

        List<TrsSensitiveWords> existingWords = trsSensitiveWordsMapper.selectTrsWordsListByErrorWord(word.getWrongWord());

        if (updateSupport && !existingWords.isEmpty()) {
            message.append(word.getWrongWord()).append(" 已存在").append(System.lineSeparator());
            word.setId(existingWords.get(0).getId());
            word.setStatus("待审核");
            trsSensitiveWordsMapper.updateTrsSensitiveWords(word);
        } else {
            word.setStatus("待审核");
            trsSensitiveWordsMapper.insertTrsSensitiveWords(word);
        }
    }

    private void handleTenantImport(TrsSensitiveWordsTenant word, boolean updateSupport, StringBuilder message) {
        if (word.getWrongWord() == null || word.getWrongWord().trim().isEmpty()) {
            return;
        }

        List<TrsSensitiveWordsTenant> existingWords = trsSensitiveWordsTenantMapper.selectTrsWordsListByErrorWord(word.getWrongWord());

        if (updateSupport && !existingWords.isEmpty()) {
            message.append(word.getWrongWord()).append(" 已存在").append(System.lineSeparator());
            word.setId(existingWords.get(0).getId());
            word.setStatus("待审核");
            trsSensitiveWordsTenantMapper.updateTrsSensitiveWords(word);
        } else {
            word.setStatus("待审核");
            trsSensitiveWordsTenantMapper.insertTrsSensitiveWords(word);
        }
    }

    private TrsSensitiveWords convertFromTenantEntity(TrsSensitiveWordsTenant tenantEntity) {
        if (tenantEntity == null) {
            return null;
        }
        TrsSensitiveWords result = new TrsSensitiveWords();
        BeanUtils.copyProperties(tenantEntity, result);
        return result;
    }

    private TrsSensitiveWordsTenant convertToTenantEntity(TrsSensitiveWords words) {
        if (words == null) {
            return null;
        }
        TrsSensitiveWordsTenant result = new TrsSensitiveWordsTenant();
        BeanUtils.copyProperties(words, result);
        return result;
    }
}