package com.gxwebsoft.apps.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gxwebsoft.apps.mapper.HualalaShopMapper;
import com.gxwebsoft.apps.service.HualalaShopService;
import com.gxwebsoft.apps.entity.HualalaShop;
import com.gxwebsoft.apps.param.HualalaShopParam;
import com.gxwebsoft.common.core.web.PageParam;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.shop.entity.Merchant;
import org.springframework.data.geo.*;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.gxwebsoft.common.core.constants.RedisConstants.MERCHANT_GEO_KEY;
import static com.gxwebsoft.common.core.constants.RedisConstants.haulalaGeoKey;

/**
 * 哗啦啦门店管理Service实现
 *
 * @author 科技小王子
 * @since 2023-01-12 18:24:44
 */
@Service
public class HualalaShopServiceImpl extends ServiceImpl<HualalaShopMapper, HualalaShop> implements HualalaShopService {

  @Resource
  private StringRedisTemplate stringRedisTemplate;

    @Override
    public PageResult<HualalaShop> pageRel(HualalaShopParam param) {
        PageParam<HualalaShop, HualalaShopParam> page = new PageParam<>(param);
        //page.setDefaultOrder("create_time desc");
        List<HualalaShop> list = baseMapper.selectPageRel(page, param);
        return new PageResult<>(list, page.getTotal());
    }

    @Override
    public List<HualalaShop> listRel(HualalaShopParam param) {
        List<HualalaShop> list = baseMapper.selectListRel(param);
        // 排序
        PageParam<HualalaShop, HualalaShopParam> page = new PageParam<>();
        //page.setDefaultOrder("create_time desc");
        return page.sortRecords(list);
    }

    @Override
    public HualalaShop getByIdRel(Integer shopId) {
        HualalaShopParam param = new HualalaShopParam();
        param.setShopId(Long.valueOf(shopId));
        return param.getOne(baseMapper.selectListRel(param));
    }


  @Override
  public List<HualalaShop> listByGeo(HualalaShopParam param) {
    // 1. 是否按距离排序
//    if (param.getMapLongitudeValueBaiDu() == null) {
//      System.out.println("param = " + param);
//      // 无定位信息
//      return list();
//    }
//    System.out.println("param333 = " + param);
    // 2. 查询10公里内的10家店铺
    final Point point = new Point(Double.parseDouble(param.getMapLongitudeValueBaiDu()), Double.parseDouble(param.getMapLatitudeValueBaiDu()));
//    System.out.println("point = " + point);
    RedisGeoCommands.GeoRadiusCommandArgs geoRadiusCommandArgs = RedisGeoCommands.GeoRadiusCommandArgs.newGeoRadiusArgs();
//      final Distance distance1 = new Distance(5, Metrics.KILOMETERS);
    GeoResults<RedisGeoCommands.GeoLocation<String>> results = stringRedisTemplate.opsForGeo().radius(haulalaGeoKey, new Circle(point, 200000), geoRadiusCommandArgs.includeDistance().limit(30));
//    System.out.println("results = " + results);
    assert results != null;
    final List<GeoResult<RedisGeoCommands.GeoLocation<String>>> list = results.getContent();
    System.out.println("list.size() = " + list.size());
    // 如查找不到店铺点位则批量写入
    if (list.size() == 0) {
      this.saveGeoPointToRedis();
      return null;
    }
    List<String> ids = new ArrayList<>(list.size());
    Map<String, Distance> distanceMap = new HashMap<>(list.size());
    list.forEach(d -> {
      // 获取店铺ID
      String shopId = d.getContent().getName();
      ids.add(shopId);
      // 获取距离
      Distance distance = d.getDistance();
//        System.out.println("distance = " + distance);
      distanceMap.put(shopId, distance);
    });
//      System.out.println("ids = " + ids);
//      System.out.println("distanceMap = " + distanceMap);
    final List<HualalaShop> shops = query().in("shop_id", ids).last("ORDER BY FIELD(shop_id," + StrUtil.join(",", ids) + ")").list();
//    System.out.println("shops = " + shops);
    for (HualalaShop shop : shops) {
      shop.setDistance(distanceMap.get(StrUtil.toString(shop.getShopId())).getValue());
    }

    return shops;
  }


  /**
   * 更新所有商户点位信息
   */
  @Override
  public void saveGeoPointToRedis() {
    // 1.查询所有商户
    final List<HualalaShop> list = list();
    // 2.然后按品牌分组，把品牌id一致的放到一个集合
    final Map<Long, List<HualalaShop>> map = list.stream().collect(Collectors.groupingBy(HualalaShop::getShopId));
    // 3.分批完成写入Redis
    for (Map.Entry<Long, List<HualalaShop>> entry : map.entrySet()) {
      // 3.1 获取商户的集合
      List<HualalaShop> value = entry.getValue();
      List<RedisGeoCommands.GeoLocation<String>> locatioins = new ArrayList<>(value.size());
      // 3.2 写入redis GEOADD key 经度 维度 member
      for (HualalaShop shop : value) {
        locatioins.add(new RedisGeoCommands.GeoLocation<>(shop.getShopId().toString(), new Point(shop.getMapLongitudeValueBaiDu(), shop.getMapLatitudeValueBaiDu())));
      }
//        System.out.println("locatioins = " + locatioins);
      stringRedisTemplate.opsForGeo().add(haulalaGeoKey, locatioins);
    }
  }

}
