package com.wgb.system.service.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tool.data.external.client.LbsAmapClient;
import com.tool.data.external.domain.request.Lbs.DistrictRequest;
import com.tool.data.external.domain.response.lbs.DistrictResponse;
import com.wgb.system.service.domain.mapper.SysMapMapper;
import com.wgb.system.service.domain.model.SysMap;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class LBSService {

    @Value("${redis.map.layer.val}")
    private String regionLayer;

    private final LbsAmapClient lbsAmapClient;
    private final SysMapMapper sysMapMapper;
    private final RedisTemplate<String,Object> redisTemplate;

    public LBSService(LbsAmapClient lbsAmapClient,SysMapMapper sysMapMapper,RedisTemplate<String,Object> redisTemplate) {
        this.lbsAmapClient = lbsAmapClient;
        this.sysMapMapper=sysMapMapper;
        this.redisTemplate=redisTemplate;
    }

    public List<SysMap> getRegionList(Integer parentCode){
        QueryWrapper<SysMap> queryWrapper=new QueryWrapper<>();
        queryWrapper.lambda().eq(SysMap::getParentCode,parentCode);
        return sysMapMapper.selectList(queryWrapper);
    }

    public SysMap getRegionById(Integer id){
        SysMap region= (SysMap) redisTemplate.opsForValue().get(regionLayer+id);
        if (region!=null){
            return region;
        }
        QueryWrapper<SysMap> queryWrapper=new QueryWrapper<>();
        queryWrapper.lambda().eq(SysMap::getId,id);
        return sysMapMapper.selectOne(queryWrapper);
    }

    public DistrictResponse getDistrict(DistrictRequest request){
        DistrictResponse districtResponse= lbsAmapClient.getDistrict(request);
        districtResponse.getDistricts().stream().forEach(i->{           //国家
            sysMapMapper.insert(new SysMap("",i.getAdcode(),i.getName(),"0",i.getCenter(),i.getLevel()));
            i.getDistricts().parallelStream().forEach(j->{              //省
                sysMapMapper.insert(new SysMap("",j.getAdcode(),j.getName(),"1",j.getCenter(),j.getLevel()));
                j.getDistricts().parallelStream().forEach(k->{          //市
                    sysMapMapper.insert(new SysMap(k.getCitycode().toString(),k.getAdcode(),k.getName(),j.getAdcode(),k.getCenter(),k.getLevel()));
                    k.getDistricts().parallelStream().forEach(l->{      //区县
                        sysMapMapper.insert(new SysMap(l.getCitycode().toString(),l.getAdcode(),l.getName(),k.getAdcode(),l.getCenter(),l.getLevel()));
                    });
                });
            });
        });
        return districtResponse;
    }
}
