package com.hzs.system.base.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hzs.common.core.constant.CacheConstants;
import com.hzs.common.core.constant.SystemFieldConstants;
import com.hzs.common.core.enums.EYesNo;
import com.hzs.common.core.service.RedisService;
import com.hzs.common.core.utils.DateUtils;
import com.hzs.common.domain.system.base.BdCountry;
import com.hzs.system.base.mapper.BdCountryMapper;
import com.hzs.system.base.service.IBdCountryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 国家服务
 */
@Service
public class BdCountryServiceImpl extends ServiceImpl<BdCountryMapper, BdCountry> implements IBdCountryService {

    @Autowired
    private RedisService redisService;

    @Override
    public BdCountry getCountry(Integer pkCountry) {
        String redisKey = CacheConstants.BD_COUNTRY + pkCountry;
        BdCountry bdCountry = redisService.getCacheObject(redisKey);
        if (null == bdCountry) {
            QueryWrapper<BdCountry> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq(SystemFieldConstants.ENABLE_STATE, EYesNo.YES.getIntValue());
            queryWrapper.le(SystemFieldConstants.EFFECTIVE_DATE, DateUtils.currentDateTime());
            queryWrapper.eq(SystemFieldConstants.PK_ID, pkCountry);
            bdCountry = baseMapper.selectOne(queryWrapper);
            if (null != bdCountry) {
                redisService.setCacheObject(redisKey, bdCountry,CacheConstants.CURRENCY_REFRESH_TIME, TimeUnit.DAYS);
            }
        }
        return bdCountry;
    }

    @Override
    public void updateCountryId(Integer pkCountry) {
        BdCountry bdCountry = baseMapper.selectById(pkCountry);
        if(bdCountry != null) {
            bdCountry.setEnableState(EYesNo.YES.getIntValue());
            baseMapper.updateById(bdCountry);
        }
    }

    @Override
    public List<BdCountry> getAllCountry() {
        QueryWrapper<BdCountry> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(SystemFieldConstants.ENABLE_STATE, EYesNo.YES.getIntValue());
        return baseMapper.selectList(queryWrapper);
    }

    @Override
    public Map<Integer, BdCountry> getAllCountryMap() {
        Map<Integer, BdCountry> resultMap = new HashMap<>();
        List<BdCountry> countryList = this.getAllCountry();
        if (CollectionUtil.isNotEmpty(countryList)) {
            for (BdCountry bdCountry : countryList) {
                resultMap.put(bdCountry.getPkId(), bdCountry);
            }
        }
        return resultMap;
    }

    @Override
    public List<BdCountry> queryListByUserId(Long userId) {
        return baseMapper.queryListByUserId(userId);
    }

}
