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.TrsNameWords;
import com.ruoyi.project.domain.TrsNameWordsTenant;
import com.ruoyi.project.mapper.TrsNameWordsMapper;
import com.ruoyi.project.mapper.TrsNameWordsTenantMapper;
import com.ruoyi.project.service.ITrsNameWordsService;
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 TrsNameWordsServiceImpl implements ITrsNameWordsService {

    @Autowired
    private TrsNameWordsMapper trsNameWordsMapper;

    @Autowired
    private TrsNameWordsTenantMapper trsNameWordsTenantMapper;

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

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

        if (isPlatformAdmin()) {
            return trsNameWordsMapper.selectTrsNameWordsById(id);
        } else {
            TrsNameWordsTenant tenantResult = trsNameWordsTenantMapper.selectTrsNameWordsById(id);
            return convertFromTenantEntity(tenantResult);
        }
    }

    @Override
    public List<TrsNameWords> selectTrsNameWordsList(TrsNameWords query) {
        if (isPlatformAdmin()) {
            return trsNameWordsMapper.selectTrsNameWordsList(query);
        } else {
            List<TrsNameWordsTenant> tenantResults = trsNameWordsTenantMapper.selectTrsNameWordsList(convertToTenantEntity(query));
            return tenantResults.stream()
                    .map(this::convertFromTenantEntity)
                    .collect(Collectors.toList());
        }
    }

    @Override
    public int insertTrsNameWords(TrsNameWords trsNameWords) {
        if (isPlatformAdmin()) {
            List<TrsNameWords> existingWords = trsNameWordsMapper.selectTrsWordsListByErrorWord(trsNameWords.getWrongWord());
            if (!existingWords.isEmpty()) {
                return 401;
            }
            return trsNameWordsMapper.insertTrsNameWords(trsNameWords);
        } else {
            List<TrsNameWordsTenant> existingWords = trsNameWordsTenantMapper.selectTrsWordsListByErrorWord(trsNameWords.getWrongWord());
            if (!existingWords.isEmpty()) {
                return 401;
            }
            TrsNameWordsTenant tenantEntity = convertToTenantEntity(trsNameWords);
            return trsNameWordsTenantMapper.insertTrsNameWords(tenantEntity);
        }
    }

    @Override
    public int updateTrsNameWords(TrsNameWords trsNameWords) {
        if (isPlatformAdmin()) {
            return trsNameWordsMapper.updateTrsNameWords(trsNameWords);
        } else {
            TrsNameWordsTenant tenantEntity = convertToTenantEntity(trsNameWords);
            return trsNameWordsTenantMapper.updateTrsNameWords(tenantEntity);
        }
    }

    @Override
    public int deleteTrsNameWordsByIds(String ids) {
        if (isPlatformAdmin()) {
            return trsNameWordsMapper.deleteTrsNameWordsByIds(Convert.toStrArray(ids));
        } else {
            return trsNameWordsTenantMapper.deleteTrsNameWordsByIds(Convert.toStrArray(ids));
        }
    }

    @Override
    public int deleteTrsNameWordsById(Long id) {
        if (isPlatformAdmin()) {
            return trsNameWordsMapper.deleteTrsNameWordsById(id);
        } else {
            return trsNameWordsTenantMapper.deleteTrsNameWordsById(id);
        }
    }

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

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

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

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

        List<TrsNameWords> existingWords = trsNameWordsMapper.selectTrsWordsListByErrorWord(word.getWrongWord());

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

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

        List<TrsNameWordsTenant> existingWords = trsNameWordsTenantMapper.selectTrsWordsListByErrorWord(word.getWrongWord());

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

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

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