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.TopologicalHouseWd;
import com.ruoyi.demo.entity.TopologicalHouseWdStatisticsData;
import com.ruoyi.demo.entity.WdInfo;
import com.ruoyi.demo.entity.vo.TopologicalWdAceeptVo;
import com.ruoyi.demo.mapper.HouseWdDao;
import com.ruoyi.demo.mapper.WdInfoDao;
import com.ruoyi.demo.service.TopologicalHouseWdService;
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 TopologicalHouseServiceWdImpl implements TopologicalHouseWdService {


    @Autowired
    WdInfoDao wdInfoDao;

    @Autowired
    InitMapUtil initMapUtil;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    HouseWdDao houseWdDao;

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

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

        //2.分页查找网点信息
        QueryWrapper<WdInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("wd_type_code", "2");
        queryWrapper.and(wdInfoQueryWrapper -> {
            wdInfoQueryWrapper.in("ddt_wd_info.wd_id", aroundWdId);
        });
        Page<WdInfo> page = new Page<>(topologicalWdAceeptVo.getPageNum(),topologicalWdAceeptVo.getPageSize());
        Page<TopologicalHouseWd> page1 = wdInfoDao.selectTopologicalHouseList(page, queryWrapper);


        //3.组装结果集
        for (TopologicalHouseWd topologicalHouseWd : page1.getRecords()) {
            //topologicalHouseWd.setAddrCodeInfo(initMapUtil.getInitAddrCodeMap(topologicalHouseWd.getAddrCode()));
            BigDecimal bigDecimal = new BigDecimal(wdDistMap.get(topologicalHouseWd.getAroundWdId()));
            topologicalHouseWd.setDistance(bigDecimal.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
        }

        //4.返回结果
        return page1;
    }

    /**
     * 获取周边小区关键统计信息
     * @param topologicalWdAceeptVo
     * @return
     */
    @Override
    public TopologicalHouseWdStatisticsData info(TopologicalWdAceeptVo topologicalWdAceeptVo) {
        List<String> aroundWdId = new ArrayList<>();

        //1.根据经纬度 找到 周边网点Id 及 距离
        getAroundWdIdList(topologicalWdAceeptVo,aroundWdId,null);
        if (aroundWdId.isEmpty())
            return new TopologicalHouseWdStatisticsData();

        //2.得到符合的小区网点信息
        List<TopologicalHouseWdStatisticsData> houseWdStatisticsData = houseWdDao.selectAndStatistics(aroundWdId);

        //3.分装数据集
        int total = 0;
        TopologicalHouseWdStatisticsData result = new TopologicalHouseWdStatisticsData();
        for (TopologicalHouseWdStatisticsData houseWdStatisticsDatum : houseWdStatisticsData) {
            result.setTotalPeopleCount(houseWdStatisticsDatum.getTotalPeopleCount() + result.getTotalPeopleCount());
            result.setTotalHouseholds(houseWdStatisticsDatum.getTotalHouseholds() + result.getTotalHouseholds());
            result.setAverageRent(houseWdStatisticsDatum.getAverageRent() + result.getAverageRent());
            total++;
        }
        result.setHouseWdCount(total);
        double averageRent = (total == 0) ? 0 : (result.getAverageRent() / total);
        result.setAverageRent(averageRent);

        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());
        });
    }
}
