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.TrsTechnicalWords;
import com.ruoyi.project.domain.TrsTechnicalWordsTenant;
import com.ruoyi.project.mapper.TrsTechnicalWordsMapper;
import com.ruoyi.project.mapper.TrsTechnicalWordsTenantMapper;
import com.ruoyi.project.service.ITrsTechnicalWordsService;
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 TrsTechnicalWordsServiceImpl implements ITrsTechnicalWordsService {

    @Autowired
    private TrsTechnicalWordsMapper trsTechnicalWordsMapper;

    @Autowired
    private TrsTechnicalWordsTenantMapper trsTechnicalWordsTenantMapper;

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

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

        if (isPlatformAdmin()) {
            return trsTechnicalWordsMapper.selectTrsTechnicalWordsById(id);
        } else {
            TrsTechnicalWordsTenant tenantResult = trsTechnicalWordsTenantMapper.selectTrsTechnicalWordsById(id);
            return convertFromTenantEntity(tenantResult);
        }
    }

    @Override
    public List<TrsTechnicalWords> selectTrsTechnicalWordsList(TrsTechnicalWords query) {
        if (isPlatformAdmin()) {
            return trsTechnicalWordsMapper.selectTrsTechnicalWordsList(query);
        } else {
            List<TrsTechnicalWordsTenant> tenantResults = trsTechnicalWordsTenantMapper.selectTrsTechnicalWordsList(convertToTenantEntity(query));
            return tenantResults.stream()
                    .map(this::convertFromTenantEntity)
                    .collect(Collectors.toList());
        }
    }

    @Override
    public int insertTrsTechnicalWords(TrsTechnicalWords trsTechnicalWords) {
        if (isPlatformAdmin()) {
            List<TrsTechnicalWords> existingWords = trsTechnicalWordsMapper.selectTrsWordsListByErrorWord(trsTechnicalWords.getWrongWord());
            if (!existingWords.isEmpty()) {
                return 401;
            }
            return trsTechnicalWordsMapper.insertTrsTechnicalWords(trsTechnicalWords);
        } else {
            List<TrsTechnicalWordsTenant> existingWords = trsTechnicalWordsTenantMapper.selectTrsWordsListByErrorWord(trsTechnicalWords.getWrongWord());
            if (!existingWords.isEmpty()) {
                return 401;
            }
            TrsTechnicalWordsTenant tenantEntity = convertToTenantEntity(trsTechnicalWords);
            return trsTechnicalWordsTenantMapper.insertTrsTechnicalWords(tenantEntity);
        }
    }

    @Override
    public int updateTrsTechnicalWords(TrsTechnicalWords trsTechnicalWords) {
        if (isPlatformAdmin()) {
            return trsTechnicalWordsMapper.updateTrsTechnicalWords(trsTechnicalWords);
        } else {
            TrsTechnicalWordsTenant tenantEntity = convertToTenantEntity(trsTechnicalWords);
            return trsTechnicalWordsTenantMapper.updateTrsTechnicalWords(tenantEntity);
        }
    }

    @Override
    public int deleteTrsTechnicalWordsByIds(String ids) {
        if (isPlatformAdmin()) {
            return trsTechnicalWordsMapper.deleteTrsTechnicalWordsByIds(Convert.toStrArray(ids));
        } else {
            return trsTechnicalWordsTenantMapper.deleteTrsTechnicalWordsByIds(Convert.toStrArray(ids));
        }
    }

    @Override
    public int deleteTrsTechnicalWordsById(Long id) {
        if (isPlatformAdmin()) {
            return trsTechnicalWordsMapper.deleteTrsTechnicalWordsById(id);
        } else {
            return trsTechnicalWordsTenantMapper.deleteTrsTechnicalWordsById(id);
        }
    }

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

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

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

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

        List<TrsTechnicalWords> existingWords = trsTechnicalWordsMapper.selectTrsWordsListByErrorWord(word.getWrongWord());

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

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

        List<TrsTechnicalWordsTenant> existingWords = trsTechnicalWordsTenantMapper.selectTrsWordsListByErrorWord(word.getWrongWord());

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

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

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