package com.izouma.dingdong.service.user;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.izouma.dingdong.domain.merchant.Merchant;
import com.izouma.dingdong.domain.user.Address;
import com.izouma.dingdong.dto.AddressDTO;
import com.izouma.dingdong.dto.MerchantDTO;
import com.izouma.dingdong.repo.user.AddressRepo;
import com.izouma.dingdong.utils.MapUtils;
import lombok.AllArgsConstructor;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
@AllArgsConstructor
public class AddressService {

    private AddressRepo addressRepo;

    /*
    带距离的地址
     */
    public List<AddressDTO> sortAddress(Long userId, Double longitude, Double latitude) {
        List<Address> addressList = addressRepo.findAllByUserIdAndEnabledTrue(userId);
        Map<Address, Double> map = distanceSorting(new HashSet<>(addressList), latitude, longitude);
        List<AddressDTO> dtos = new ArrayList<>();
        for (Map.Entry<Address, Double> m : map.entrySet()) {
            dtos.add(this.toDTO(m.getKey(), m.getValue()));
        }
        return dtos;
    }

    /*
    地址排序
     */
    public Map<Address, Double> distanceSorting(Set<Address> addresses, Double longitude, Double latitude) {
        //所有地址要按距离排序规则
        Map<Address, Double> map = new HashMap<>();
        //算距离
        for (Address m : addresses) {
            if (ObjectUtil.isNotNull(m.getLatitude()) && ObjectUtil.isNotNull(m.getLongitude())) {
                Double distance = MapUtils.distance(m.getLongitude(), m.getLatitude(), longitude, latitude);
                map.put(m, distance);
            }
        }

        //排序
        List<Map.Entry<Address, Double>> list = new ArrayList<>(map.entrySet());
        list.sort(Comparator.comparing(Map.Entry<Address, Double>::getValue));

        Map<Address, Double> result = new HashMap<>();
        for (Map.Entry<Address, Double> m : list) {
            result.put(m.getKey(), m.getValue());
        }

        return result;
    }

    public Map<T, Double> sortMap(Map<T, Double> map) {
        //排序
        List<Map.Entry<T, Double>> list = new ArrayList<>(map.entrySet());
        list.sort(Comparator.comparing(Map.Entry<T, Double>::getValue));

        Map<T, Double> result = new HashMap<>();
        for (Map.Entry<T, Double> m : list) {
            result.put(m.getKey(), m.getValue());
        }
        return result;
    }

    /*
    转dto
     */
    public AddressDTO toDTO(Address address, Double distance) {
        AddressDTO dto = new AddressDTO();
        BeanUtil.copyProperties(address, dto);
        dto.setDistance(distance);
        return dto;
    }
}
