package com.ruoyi.project.business.service.impl;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.enums.DelFlag;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.annotation.DataUpdateCheck;
import com.ruoyi.project.business.domain.TcLead;
import com.ruoyi.project.business.domain.dto.TbCountryDto;
import com.ruoyi.project.business.domain.vo.country.CountryLanguageVo;
import com.ruoyi.project.business.mapper.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import com.ruoyi.project.business.domain.TbCountry;
import com.ruoyi.project.business.service.ITbCountryService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

import static com.ruoyi.common.constant.CacheConstants.AREA_KEY;
import static com.ruoyi.common.constant.CacheConstants.COUNTRY_KEY;

/**
 * 国家Service业务层处理
 *
 * @author ruoyi
 * @date 2024-04-15
 */
@CacheConfig(cacheManager = "concurrentMapCacheManager")
@Service
public class TbCountryServiceImpl extends ServiceImpl<TbCountryMapper, TbCountry> implements ITbCountryService {
    @Autowired
    private TbCountryMapper tbCountryMapper;

    @Resource
    private TbCountryAreaMapper tbCountryAreaMapper;

    @Resource
    private TcAccountMapper tcAccountMapper;

    @Resource
    private TbAgentMapper tbAgentMapper;

    @Resource
    private TcLeadMapper tcLeadMapper;

    /**
     * 查询国家
     *
     * @param countryId 国家主键
     * @return 国家
     */
    @Override
    @Cacheable(value = COUNTRY_KEY, key = "#countryId")
    public TbCountry selectTbCountryByCountryId(Long countryId) {
        // 校验数据是否已被删除
        TbCountry tbCountry = tbCountryMapper.selectTbCountryByCountryId(countryId);
        if (DelFlag.YES.getCode().equals(tbCountry.getDelFlag())) {
            throw new ServiceException(MessageUtils.message("business.data.deleted"));
        }
        return tbCountry;
    }

    /***根据ids批量查找国家缩写
     *
     * @param ids
     * @return
     */
    public Map<Long,String> selectCountryAbbr(List<Long> ids){
        List<TbCountryDto> tbCountryDtoList = tbCountryMapper.selectTbCountryByCountryIds(ids);
        Map<Long,String> tbCountryMap = new HashMap<>();
        tbCountryMap = tbCountryDtoList.stream().collect(Collectors.toMap(item->item.getCountryId(),item->item.getCountryAbbr()));
        return tbCountryMap;
    }

    /**
     * 查询国家列表
     *
     * @param tbCountry 国家
     * @return 国家
     */
    @Override
    public List<TbCountry> selectTbCountryList(TbCountry tbCountry) {
        if (StringUtils.isNotEmpty(tbCountry.getCountryName())) {
            tbCountry.setCountryName(tbCountry.getCountryName().replaceAll("%", "/%").replaceAll("_", "/_"));
        }
        if (StringUtils.isNotEmpty(tbCountry.getCountryNameUS())) {
            tbCountry.setCountryNameUS(tbCountry.getCountryNameUS().replaceAll("%", "/%").replaceAll("_", "/_"));
        }
        if (StringUtils.isNotEmpty(tbCountry.getCountryNameRU())) {
            tbCountry.setCountryNameRU(tbCountry.getCountryNameRU().replaceAll("%", "/%").replaceAll("_", "/_"));
        }
        if (StringUtils.isNotEmpty(tbCountry.getCountryNameES())) {
            tbCountry.setCountryNameES(tbCountry.getCountryNameES().replaceAll("%", "/%").replaceAll("_", "/_"));
        }
        return tbCountryMapper.selectTbCountryList(tbCountry);
    }

    /**
     * 新增国家
     *
     * @param tbCountry 国家
     * @return 结果
     */
    @Override
    @CacheEvict(value = COUNTRY_KEY, allEntries = true)
    @Transactional
    public int insertTbCountry(TbCountry tbCountry) {
        // 校验国家名称
        int count = tbCountryMapper.selectTbCountryByCountryName(tbCountry.getCountryName(), null);
        if (count > 0) {
            throw new ServiceException(MessageUtils.message("country.name.repeat"));
        }
        tbCountry.setCreateBy(SecurityUtils.getUserId().toString());
        tbCountry.setCreateTime(DateUtils.getNowDate());
        tbCountry.setUpdateTime(DateUtils.getNowDate());
        return tbCountryMapper.insertTbCountry(tbCountry);
    }

    /**
     * 修改国家
     *
     * @param tbCountry 国家
     * @return 结果
     */
    @Override
    @CacheEvict(value = COUNTRY_KEY, allEntries = true)
    @Transactional
    public int updateTbCountry(TbCountry tbCountry) {
        // 校验国家名称
        int count = tbCountryMapper.selectTbCountryByCountryName(tbCountry.getCountryName(), tbCountry.getCountryId());
        if (count > 0) {
            throw new ServiceException(MessageUtils.message("country.name.repeat"));
        }
        tbCountry.setUpdateBy(SecurityUtils.getUserId().toString());
        tbCountry.setUpdateTime(DateUtils.getNowDate());
        return tbCountryMapper.updateTbCountry(tbCountry);
    }

    /**
     * 批量删除国家
     *
     * @param countryIds 需要删除的国家主键
     * @return 结果
     */
    @Override
    @CacheEvict(value = COUNTRY_KEY, allEntries = true)
    @Transactional
    public int deleteTbCountryByCountryIds(Long[] countryIds) {
        // 校验是否有客户使用
        int count = tcAccountMapper.selectCountByCountryIds(countryIds);
        if (count > 0) {
            throw new ServiceException(MessageUtils.message("account.cannot.delete"));
        }
        // 校验是否有代理商使用
        int agentCount = tbAgentMapper.selectCountByCountryIds(countryIds);
        if (agentCount > 0) {
            throw new ServiceException(MessageUtils.message("agent.cannot.delete"));
        }
        int leadCount = tcLeadMapper.selectCountByCountryIds(countryIds);
        if (leadCount > 0) {
            throw new ServiceException(MessageUtils.message("lead.cannot.delete"));
        }
        // 同时删除关联区域
        tbCountryAreaMapper.deleteTbCountryAreaByCountryIds(countryIds);
        return tbCountryMapper.deleteTbCountryByCountryIds(countryIds);
    }

    /**
     * 删除国家信息
     *
     * @param countryId 国家主键
     * @return 结果
     */
    @Override
    @CacheEvict(value = COUNTRY_KEY, allEntries = true)
    public int deleteTbCountryByCountryId(Long countryId) {
        return tbCountryMapper.deleteTbCountryByCountryId(countryId);
    }

    /**
     * 查询所有国家列表
     *
     * @return 结果
     */
    @Override
    public List<TbCountry> getAllNationList() {
        return tbCountryMapper.getAllNationList();
    }

    /**
     * 查询所有国家列表(需要语言)
     *
     * @return 结果
     */
    @Override
    public List<CountryLanguageVo> getAllNationNeedLanguageList(String language) {
        return tbCountryMapper.getAllNationNeedLanguageList(language);
    }

    @Override
    public List<TbCountry> getCountryByAreaId(Long areaId) {

        return tbCountryMapper.selectCountryByAreaId(areaId);
    }

    @Override
    public List<TbCountry> getCountryByAreaIds(Long[] areaIds) {
        if (Arrays.asList(areaIds).contains(0L)) {
            areaIds = new Long[]{};
        }
        return tbCountryMapper.selectCountryByAreaIds(areaIds);
    }

    @Override
    @Cacheable(value = COUNTRY_KEY, key = "'allCountryMap'")
    public Map<Long, TbCountry> allCountryMap() {
        List<TbCountry> countries = tbCountryMapper.getAllNationList();
        
        return countries.stream().collect(Collectors.toMap(TbCountry::getCountryId, country -> country));
    }
}
