package com.ruoyi.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.demo.entity.TopologicalEnterpriseWd;
import com.ruoyi.demo.entity.WdInfo;
import com.ruoyi.demo.entity.vo.TopologicalWdAceeptVo;
import com.ruoyi.demo.mapper.WdInfoDao;
import com.ruoyi.demo.service.TopologicalEnterpriseWdService;
import com.ruoyi.demo.utils.InitMapUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Circle;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.geo.Point;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Service
@Transactional
public class TopologicalEnterpriseWdServiceImpl implements TopologicalEnterpriseWdService {

    @Autowired
    WdInfoDao wdInfoDao;

    @Autowired
    InitMapUtil initMapUtil;

    @Autowired
    RedisTemplate redisTemplate;

    /**
     * 获取周边企业网点列表
     * @param topologicalWdAceeptVo
     * @return
     */
    @Override
    public HashMap<String,Object> list(TopologicalWdAceeptVo topologicalWdAceeptVo) {
        List<String> aroundWdId = new ArrayList<>();
        HashMap<String,Double> wdDistMap = new HashMap<>();

        //1.根据经纬度 找到 周边网点Id 及 距离
        getAroundWdIdList(topologicalWdAceeptVo,aroundWdId,wdDistMap);
        if (aroundWdId.isEmpty()){
            //没有周边网点
            HashMap<String,Object> result = new HashMap();
            Page<WdInfo> page = new Page<>(topologicalWdAceeptVo.getPageNum(),topologicalWdAceeptVo.getPageSize());
            result.put("page",page);
            result.put("data",new ArrayList<>());
            return result;
        }

        //2.分页获取周边企业网点信息
        QueryWrapper<WdInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("wd_type_code","5");
        queryWrapper.and(wdInfoQueryWrapper -> {
            wdInfoQueryWrapper.in("wd_id", aroundWdId);
        });
        Page<WdInfo> page = new Page<>(topologicalWdAceeptVo.getPageNum(),topologicalWdAceeptVo.getPageSize());
        Page<WdInfo> page1 = wdInfoDao.selectPage(page, queryWrapper);


        //3.组装结果集
        List<TopologicalEnterpriseWd> list = new ArrayList<>();  //返回结果集
        for (WdInfo wdInfo : page1.getRecords()) {
            TopologicalEnterpriseWd topologicalEnterpriseWd = new TopologicalEnterpriseWd(wdInfo);
            //topologicalEnterpriseWd.setAddrCodeInfo(initMapUtil.getInitAddrCodeMap(topologicalEnterpriseWd.getAddrCode()));
            BigDecimal bigDecimal = new BigDecimal(wdDistMap.get(wdInfo.getWdId()));
            topologicalEnterpriseWd.setDistance(bigDecimal.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue());
            list.add(topologicalEnterpriseWd);
        }

        //4.返回结果
        HashMap<String,Object> result = new HashMap();
        page1.setRecords(null);
        result.put("page",page1);
        result.put("data",list);
        return result;
    }

    /**
     * 获取周边物流园
     * @param topologicalWdAceeptVo
     * @return
     */
    @Override
    public HashMap<String, Object> logisticsList(TopologicalWdAceeptVo topologicalWdAceeptVo) {
        List<String> aroundWdId = new ArrayList<>();
        HashMap<String,Double> wdDistMap = new HashMap<>();

        //1.根据经纬度 找到 周边网点Id 及 距离
        getAroundWdIdList(topologicalWdAceeptVo,aroundWdId,wdDistMap);
        if (aroundWdId.isEmpty()){
            //没有周边网点
            HashMap<String,Object> result = new HashMap();
            Page<WdInfo> page = new Page<>(topologicalWdAceeptVo.getPageNum(),topologicalWdAceeptVo.getPageSize());
            result.put("page",page);
            result.put("data",new ArrayList<>());
            return result;
        }

        //2.分页获取周边企业物流园网点信息
        QueryWrapper<WdInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("wd_type_code","5");
        queryWrapper.and(wdInfoQueryWrapper -> {
            wdInfoQueryWrapper.in("wd_id", aroundWdId);
        });
        queryWrapper.and(wdInfoQueryWrapper -> {
            wdInfoQueryWrapper.like("wd_name","物流");
        });
        Page<WdInfo> page = new Page<>(topologicalWdAceeptVo.getPageNum(),topologicalWdAceeptVo.getPageSize());
        Page<WdInfo> page1 = wdInfoDao.selectPage(page, queryWrapper);


        //3.组装结果集
        List<TopologicalEnterpriseWd> list = new ArrayList<>();  //返回结果集
        for (WdInfo wdInfo : page1.getRecords()) {
            TopologicalEnterpriseWd topologicalEnterpriseWd = new TopologicalEnterpriseWd(wdInfo);
            //topologicalEnterpriseWd.setAddrCodeInfo(initMapUtil.getInitAddrCodeMap(topologicalEnterpriseWd.getAddrCode()));
            BigDecimal bigDecimal = new BigDecimal(wdDistMap.get(wdInfo.getWdId()));
            topologicalEnterpriseWd.setDistance(bigDecimal.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue());
            list.add(topologicalEnterpriseWd);
        }

        //4.返回结果
        HashMap<String,Object> result = new HashMap();
        page1.setRecords(null);
        result.put("page",page1);
        result.put("data",list);
        return result;
    }

    /**
     * 根据坐标获取周边网点Id
     * @param topologicalWdAceeptVo
     * @param aroundWdIdList
     * @param wdDistMap 存储 周边网点与中心网点直接的距离
     */
    public void getAroundWdIdList(TopologicalWdAceeptVo topologicalWdAceeptVo,List<String> aroundWdIdList,HashMap<String,Double> wdDistMap){
        //1.根据经纬度 找到 周边网点Id
        // 以经纬度为中心，获取半径不超过最大距离的所有元素
        Point point = new Point(topologicalWdAceeptVo.getLng(),topologicalWdAceeptVo.getLat());

        //半径范围
        Distance distance = new Distance(topologicalWdAceeptVo.getRadius(), RedisGeoCommands.DistanceUnit.METERS);

        //圆
        Circle circle = new Circle(point, distance);
        RedisGeoCommands.GeoRadiusCommandArgs geoRadiusCommandArgs = RedisGeoCommands.GeoRadiusCommandArgs.newGeoRadiusArgs();
        geoRadiusCommandArgs.includeDistance(); //添加参数：返回距离
        GeoResults<RedisGeoCommands.GeoLocation<Object>> radius = redisTemplate.boundGeoOps(topologicalWdAceeptVo.getAddrCode().substring(0, 4)).radius(circle,geoRadiusCommandArgs);

        //解析周边网点Id
        radius.getContent().stream().forEach(item -> {
            //记录网点坐标及距离
            aroundWdIdList.add((String) item.getContent().getName());
            if (wdDistMap != null)
                wdDistMap.put((String) item.getContent().getName(), item.getDistance().getValue());
        });
    }
}
