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

import cn.hutool.core.bean.BeanUtil;
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.domain.system.base.BdArea;
import com.hzs.common.domain.system.base.ext.AreaCache;
import com.hzs.system.base.mapper.BdAreaMapper;
import com.hzs.system.base.service.IBdAreaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * 行政区划 服务实现类
 *
 * @author hzs
 * @since 2022-08-04
 */
@Service
public class BdAreaServiceImpl extends ServiceImpl<BdAreaMapper, BdArea> implements IBdAreaService {

    @Autowired
    private RedisService redisService;

    @Override
    public List<AreaCache> getAreaList(Integer pkCountry) {
        String redisKey = CacheConstants.BD_AREA + pkCountry;

        List<AreaCache> areaCacheList = redisService.getCacheList(redisKey);
        if (CollectionUtils.isEmpty(areaCacheList)) {
            QueryWrapper<BdArea> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq(SystemFieldConstants.PK_COUNTRY, pkCountry);
            queryWrapper.eq("enable_state", EYesNo.YES.getIntValue());
            // 行政区划中不存国家信息了，此处去掉排除区域
            // queryWrapper.notIn("PARENT", 0);
            queryWrapper.orderByAsc("code");
            List<BdArea> areaList = baseMapper.selectList(queryWrapper);
            if (!CollectionUtils.isEmpty(areaList)) {
                areaCacheList = BeanUtil.copyToList(areaList, AreaCache.class);
                redisService.setCacheList(redisKey, areaCacheList);
            }
        }
        return areaCacheList;
    }

}
