package com.ruoyi.api.controller.info;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Comparator;
import java.util.List;

import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.utils.MapTools;
import com.ruoyi.info.hospital.domain.bo.HospitalBo;
import com.ruoyi.info.hospital.domain.vo.HospitalVo;
import com.ruoyi.info.hospital.service.IHospitalService;

import cn.hutool.core.util.StrUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;

/**
 * @author fucheng.bai
 * @date 2025/9/22
 */
@Validated
@Api(value = "API 医院管理控制器", tags = {"医院管理"})
@RequiredArgsConstructor
@RestController
@RequestMapping("/api/info/hospital")
public class ApiHospitalController {

    private final IHospitalService iHospitalService;

    /**
     * 获取所有医院列表
     */
    @ApiOperation("查询医院信息列表")
    @GetMapping("/list")
    public R<List<HospitalVo>> list(@ApiParam("经纬度，以逗号隔开") @RequestParam(required = false) String coordinates) {
        List<HospitalVo> hospitalVoList = iHospitalService.queryList(new HospitalBo());
        if (!StrUtil.isEmpty(coordinates)) {
            // 如果坐标不为空，则计算相对距离
            for (HospitalVo hospitalVo : hospitalVoList) {
                if (StrUtil.isEmpty(hospitalVo.getCoordinates())) {
                    continue;
                }
                double distance = MapTools.calculate(coordinates.split(",")[0], coordinates.split(",")[1],
                    hospitalVo.getCoordinates().split(",")[0], hospitalVo.getCoordinates().split(",")[1]);

                // 转化为km，保留一位小数
                BigDecimal relativeDistance = BigDecimal.valueOf(distance).abs().divide(BigDecimal.valueOf(1000),  1, RoundingMode.HALF_UP);
                hospitalVo.setRelativeDistance(relativeDistance);
            }
            // 根据相对距离排序，从小到大
            hospitalVoList.sort(Comparator.comparing(HospitalVo::getRelativeDistance));
        }

        return R.ok(hospitalVoList);
    }
}
