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.TrsPolicyWords;
import com.ruoyi.project.domain.TrsPolicyWordsTenant;
import com.ruoyi.project.mapper.TrsPolicyWordsMapper;
import com.ruoyi.project.mapper.TrsPolicyWordsTenantMapper;
import com.ruoyi.project.service.ITrsPolicyWordsService;
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 TrsPolicyWordsServiceImpl implements ITrsPolicyWordsService {

    @Autowired
    private TrsPolicyWordsMapper trsPolicyWordsMapper;

    @Autowired
    private TrsPolicyWordsTenantMapper trsPolicyWordsTenantMapper;

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

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

        if (isPlatformAdmin()) {
            return trsPolicyWordsMapper.selectTrsPolicyWordsById(id);
        } else {
            TrsPolicyWordsTenant tenantResult = trsPolicyWordsTenantMapper.selectTrsPolicyWordsById(id);
            return convertFromTenantEntity(tenantResult);
        }
    }

    @Override
    public List<TrsPolicyWords> selectTrsPolicyWordsList(TrsPolicyWords query) {
        if (isPlatformAdmin()) {
            return trsPolicyWordsMapper.selectTrsPolicyWordsList(query);
        } else {
            List<TrsPolicyWordsTenant> tenantResults = trsPolicyWordsTenantMapper.selectTrsPolicyWordsList(convertToTenantEntity(query));
            return tenantResults.stream()
                    .map(this::convertFromTenantEntity)
                    .collect(Collectors.toList());
        }
    }

    @Override
    public int insertTrsPolicyWords(TrsPolicyWords trsPolicyWords) {
        if (isPlatformAdmin()) {
            List<TrsPolicyWords> existingWords = trsPolicyWordsMapper.selectTrsWordsListByErrorWord(trsPolicyWords.getWrongWord());
            if (!existingWords.isEmpty()) {
                return 401;
            }
            return trsPolicyWordsMapper.insertTrsPolicyWords(trsPolicyWords);
        } else {
            List<TrsPolicyWordsTenant> existingWords = trsPolicyWordsTenantMapper.selectTrsWordsListByErrorWord(trsPolicyWords.getWrongWord());
            if (!existingWords.isEmpty()) {
                return 401;
            }
            TrsPolicyWordsTenant tenantEntity = convertToTenantEntity(trsPolicyWords);
            return trsPolicyWordsTenantMapper.insertTrsPolicyWords(tenantEntity);
        }
    }

    @Override
    public int updateTrsPolicyWords(TrsPolicyWords trsPolicyWords) {
        if (isPlatformAdmin()) {
            return trsPolicyWordsMapper.updateTrsPolicyWords(trsPolicyWords);
        } else {
            TrsPolicyWordsTenant tenantEntity = convertToTenantEntity(trsPolicyWords);
            return trsPolicyWordsTenantMapper.updateTrsPolicyWords(tenantEntity);
        }
    }

    @Override
    public int deleteTrsPolicyWordsByIds(String ids) {
        if (isPlatformAdmin()) {
            return trsPolicyWordsMapper.deleteTrsPolicyWordsByIds(Convert.toStrArray(ids));
        } else {
            return trsPolicyWordsTenantMapper.deleteTrsPolicyWordsByIds(Convert.toStrArray(ids));
        }
    }

    @Override
    public int deleteTrsPolicyWordsById(Long id) {
        if (isPlatformAdmin()) {
            return trsPolicyWordsMapper.deleteTrsPolicyWordsById(id);
        } else {
            return trsPolicyWordsTenantMapper.deleteTrsPolicyWordsById(id);
        }
    }

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

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

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

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

        List<TrsPolicyWords> existingWords = trsPolicyWordsMapper.selectTrsWordsListByErrorWord(word.getWrongWord());

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

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

        List<TrsPolicyWordsTenant> existingWords = trsPolicyWordsTenantMapper.selectTrsWordsListByErrorWord(word.getWrongWord());

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

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

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