package com.sptg.gateway.service.impl;

import com.sptg.common.core.util.JsonUtils;
import com.sptg.gateway.service.AreaService;
import com.sptg.permissions.api.dto.AreaDto;
import com.sptg.permissions.api.entity.Area;
import com.sptg.permissions.api.feigns.AreaFeign;
import lombok.RequiredArgsConstructor;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * @author WFT
 * @date 2020/5/29
 * description:
 */
@Service
@RequiredArgsConstructor
public class AreaServiceImpl implements AreaService {

    private final static String IMPORT_CACHE_AREA = "sptg:import:area";

    private final RedisTemplate<String,String> redisTemplate;
    private final AreaFeign areaFeign;

    @Override
    public AreaDto selectByRegionName(String province, String city, String area) {
        HashOperations<String, Object, Object> operations = this.redisTemplate.opsForHash();
        //
        String cacheKey = DigestUtils.md5Hex(province + city + area);
        //  先尝试从缓存中获取
        Object json = operations.get(IMPORT_CACHE_AREA, cacheKey);
        if (null == json){
            //  查询数据
            AreaDto dto = new AreaDto();
            dto.setRegionProvince(province);
            dto.setRegionCity(city);
            dto.setRegionArea(area);
            Map<String, Object> map = this.areaFeign.selectByNameAndLayer(dto);
            //  判断是否查询到记录
            if (null == map || map.size() < 4 || null == map.get("regionName")){
                return null;
            }
            dto.setRegionProvince(String.valueOf((map.get("regionProvince"))));
            dto.setRegionCity(String.valueOf((map.get("regionCity"))));
            dto.setRegionArea(String.valueOf((map.get("regionArea"))));
            dto.setRegionName(String.valueOf((map.get("regionName"))));
            //  将查询结果保存到缓存中
            operations.put(IMPORT_CACHE_AREA,cacheKey,JsonUtils.objectToJson(dto));
            return dto;
        }
        return JsonUtils.jsonToPojo(json.toString(),AreaDto.class);
    }

    @Override
    public List<Area> selectCityAndProvinceByName(String name) {
        return this.areaFeign.getCityAndProvinceByName(name);
    }
}
