package com.gxwebsoft.shop.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gxwebsoft.common.core.utils.CacheClient;
import com.gxwebsoft.common.core.web.PageParam;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.shop.entity.Merchant;
import com.gxwebsoft.shop.mapper.MerchantMapper;
import com.gxwebsoft.shop.param.MerchantParam;
import com.gxwebsoft.shop.service.MerchantService;
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;

/**
 * 商户管理Service实现
 *
 * @author 科技小王子
 * @since 2022-11-30 15:10:54
 */
@Service
public class MerchantServiceImpl extends ServiceImpl<MerchantMapper, Merchant> implements MerchantService {
  @Resource
  private StringRedisTemplate stringRedisTemplate;
  @Resource
  private CacheClient cacheClient;

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

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

  @Override
  public Merchant getByIdRel(Integer merchantId) {
    MerchantParam param = new MerchantParam();
    param.setMerchantId(merchantId);
    return param.getOne(baseMapper.selectListRel(param));
  }

  @Override
  public String getMerchantCodeByOwner(Integer merchantOwner) {
    Merchant merchant = query().eq("merchant_owner", merchantOwner).one();
    if (merchant == null) {
      return null;
    }
    return merchant.getMerchantCode();
  }

  @Override
  public Merchant getMerchantByCode(String merchantCode) {
    return query().eq("merchant_code", merchantCode).one();
  }

  @Override
  public List<Merchant> listByGeo(MerchantParam param) {
    System.out.println("param = " + param);
    // 1. 是否按距离排序
    if (param.getLngAndLat() == null) {
      // 无定位信息
      return list();
    }
    // 2. 查询10公里内的10家店铺
    final String lngAndLat = param.getLngAndLat();
    final String[] split = lngAndLat.split(",");
    final Point point = new Point(Double.parseDouble(split[0]), Double.parseDouble(split[1]));
    RedisGeoCommands.GeoRadiusCommandArgs geoRadiusCommandArgs = RedisGeoCommands.GeoRadiusCommandArgs.newGeoRadiusArgs();
//      final Distance distance1 = new Distance(5, Metrics.KILOMETERS);
    GeoResults<RedisGeoCommands.GeoLocation<String>> results = stringRedisTemplate.opsForGeo().radius(MERCHANT_GEO_KEY, new Circle(point, 10000), geoRadiusCommandArgs.includeDistance().limit(10));

    assert results != null;
    final List<GeoResult<RedisGeoCommands.GeoLocation<String>>> list = results.getContent();
    if (list.size() == 0) {
      return null;
    }
    List<String> ids = new ArrayList<>(list.size());
    Map<String, Distance> distanceMap = new HashMap<>(list.size());
    list.forEach(d -> {
      // 获取店铺ID
      String merchantId = d.getContent().getName();
      ids.add(merchantId);
      // 获取距离
      Distance distance = d.getDistance();
//        System.out.println("distance = " + distance);
      distanceMap.put(merchantId, distance);
    });
//      System.out.println("ids = " + ids);
//      System.out.println("distanceMap = " + distanceMap);
    final List<Merchant> merchants = query().in("merchant_id", ids).last("ORDER BY FIELD(merchant_id," + StrUtil.join(",", ids) + ")").list();
    for (Merchant shop : merchants) {
      shop.setDistance(distanceMap.get(StrUtil.toString(shop.getMerchantId())).getValue());
    }
//      System.out.println("merchants = " + merchants);
    // 定时更新geo商户点位信息
//    this.saveGeoPointToRedis();
    return merchants;
  }

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