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.TrsDomainWords;
import com.ruoyi.project.domain.TrsDomainWordsTenant;
import com.ruoyi.project.mapper.TrsDomainWordsMapper;
import com.ruoyi.project.mapper.TrsDomainWordsTenantMapper;
import com.ruoyi.project.service.ITrsDomainWordsService;
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 TrsDomainWordsServiceImpl implements ITrsDomainWordsService {

    @Autowired
    private TrsDomainWordsMapper trsDomainWordsMapper;

    @Autowired
    private TrsDomainWordsTenantMapper trsDomainWordsTenantMapper;

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

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

        if (isPlatformAdmin()) {
            return trsDomainWordsMapper.selectTrsDomainWordsById(id);
        } else {
            TrsDomainWordsTenant tenantResult = trsDomainWordsTenantMapper.selectTrsDomainWordsById(id);
            return convertFromTenantEntity(tenantResult);
        }
    }

    @Override
    public List<TrsDomainWords> selectTrsDomainWordsList(TrsDomainWords query) {
        if (isPlatformAdmin()) {
            return trsDomainWordsMapper.selectTrsDomainWordsList(query);
        } else {
            List<TrsDomainWordsTenant> tenantResults = trsDomainWordsTenantMapper.selectTrsDomainWordsList(convertToTenantEntity(query));
            return tenantResults.stream()
                    .map(this::convertFromTenantEntity)
                    .collect(Collectors.toList());
        }
    }

    @Override
    public int insertTrsDomainWords(TrsDomainWords trsDomainWords) {
        if (isPlatformAdmin()) {
            List<TrsDomainWords> existingWords = trsDomainWordsMapper.selectTrsWordsListByErrorWord(trsDomainWords.getWrongWord());
            if (!existingWords.isEmpty()) {
                return 401;
            }
            return trsDomainWordsMapper.insertTrsDomainWords(trsDomainWords);
        } else {
            List<TrsDomainWordsTenant> existingWords = trsDomainWordsTenantMapper.selectTrsWordsListByErrorWord(trsDomainWords.getWrongWord());
            if (!existingWords.isEmpty()) {
                return 401;
            }
            TrsDomainWordsTenant tenantEntity = convertToTenantEntity(trsDomainWords);
            return trsDomainWordsTenantMapper.insertTrsDomainWords(tenantEntity);
        }
    }

    @Override
    public int updateTrsDomainWords(TrsDomainWords trsDomainWords) {
        if (isPlatformAdmin()) {
            return trsDomainWordsMapper.updateTrsDomainWords(trsDomainWords);
        } else {
            TrsDomainWordsTenant tenantEntity = convertToTenantEntity(trsDomainWords);
            return trsDomainWordsTenantMapper.updateTrsDomainWords(tenantEntity);
        }
    }

    @Override
    public int deleteTrsDomainWordsByIds(String ids) {
        if (isPlatformAdmin()) {
            return trsDomainWordsMapper.deleteTrsDomainWordsByIds(Convert.toStrArray(ids));
        } else {
            return trsDomainWordsTenantMapper.deleteTrsDomainWordsByIds(Convert.toStrArray(ids));
        }
    }

    @Override
    public int deleteTrsDomainWordsById(Long id) {
        if (isPlatformAdmin()) {
            return trsDomainWordsMapper.deleteTrsDomainWordsById(id);
        } else {
            return trsDomainWordsTenantMapper.deleteTrsDomainWordsById(id);
        }
    }

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

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

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

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

        List<TrsDomainWords> existingWords = trsDomainWordsMapper.selectTrsWordsListByErrorWord(word.getWrongWord());

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

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

        List<TrsDomainWordsTenant> existingWords = trsDomainWordsTenantMapper.selectTrsWordsListByErrorWord(word.getWrongWord());

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

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

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