package com.ruoyi.web.controller.basic;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.ruoyi.RestResponse;
import com.ruoyi.basic.domain.YjHealthy;
import com.ruoyi.basic.service.impl.YjHealthyServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
import java.util.Map;

/**
 * 健康饮食
 */
@Api(tags = "036-健康饮食", description = "提供健康饮食相关的API")
@RestController
@RequestMapping("/api/healthy")
public class HealthyController {
    @Resource
    private YjHealthyServiceImpl service;

    /**
     * 健康饮食 列表
     * @param visitStore
     * @return
     */
    @ApiOperation(value = "获取健康饮食列表")
    @PostMapping("/getList")
    public RestResponse getList(@RequestBody Map map){
        Long visitStore=Long.parseLong(map.get("visitStore").toString());
        List<YjHealthy> list= service.list(new QueryWrapper<YjHealthy>()
                .select("id,title,image,read_num,start_time,modify_time")
                .eq("dept_id",visitStore)
                .eq("status",true)
                .orderByDesc("modify_time"));
        return new RestResponse().setSuccess(true).setMessage("成功").setData(list);
    }

    /**
     * 健康饮食详情
     * @param healthy
     * @return
     */
    @ApiOperation(value = "健康饮食详情")
    @PostMapping("/getOne")
    public RestResponse getOne(@RequestBody YjHealthy healthy){
        service.update(new UpdateWrapper<YjHealthy>()
                .setSql("read_num=read_num+1")
                .eq("id",healthy.getId()));//阅读量
        YjHealthy i=service.getById(healthy.getId());
        return new RestResponse().setSuccess(true).setMessage("成功").setData(i);
    }

    @ApiOperation(value = "计算BIM")
    @PostMapping("/calculateBim")
    public RestResponse calculateBim(@RequestBody Map map){
        try {
            map.get("gender");//male男性 female女性
            map.get("age");
            BigDecimal height= checkAndFormatNum(map.get("height"));
            BigDecimal weight= checkAndFormatNum(map.get("weight"));
            // 公式：BMI = 体重 ÷ (身高 × 身高)
            height=height.divide(new BigDecimal(100));
            BigDecimal heightSquare = height.multiply(height); // 身高平方
            BigDecimal bim=weight.divide(heightSquare,2,RoundingMode.HALF_UP);

            BigDecimal num185 = new BigDecimal("18.5");
            BigDecimal num239 = new BigDecimal("23.9");
            BigDecimal num279 = new BigDecimal("27.9");
            if (bim.compareTo(num185) < 0) {

                return new RestResponse()
                        .setSuccess(true)
                        .setMessage("您的体重过轻，请联系馆主或教练领取A方案")
                        .setData(bim);
            }
           else if (bim.compareTo(num185) > 0 && bim.compareTo(num239) < 0) {

                return new RestResponse()
                        .setSuccess(true)
                        .setMessage("太棒了，您的体重非常健康，请联系馆主或教练领取B方案保持")
                        .setData(bim);
            }
            else if (bim.compareTo(num239) > 0 && bim.compareTo(num279) < 0) {

                return new RestResponse()
                        .setSuccess(true)
                        .setMessage("您的体重超重，请联系馆主或教练领取C方案")
                        .setData(bim);
            }else {
                return new RestResponse()
                        .setSuccess(true)
                        .setMessage("您的体重肥胖，请联系馆主或教练领取D方案")
                        .setData(bim);
            }

        }catch (IllegalArgumentException e){
            return RestResponse.failure(e.getMessage());
        }

    }

    /**
     * 校验并格式化 height
     * @return 格式化后的 height（保留1位小数）
     * @throws IllegalArgumentException 校验不通过时抛出异常
     */
    public static BigDecimal checkAndFormatNum(Object obj) {
        // 1. 非空校验
        if (obj == null || obj.toString().trim().isEmpty()) {
            throw new IllegalArgumentException("身高/体重不能为空");
        }

        String heightStr = obj.toString().trim();
        BigDecimal heightNum;

        try {
            // 2. 校验是否为有效数字（整数/小数都支持）
            heightNum = new BigDecimal(heightStr);
        } catch (NumberFormatException e) {
            throw new IllegalArgumentException("身高/体重必须是有效数字，当前值：" + heightStr);
        }

        // 3. 保留1位小数（四舍五入，银行家舍入法，最常用）
        BigDecimal formattedHeight = heightNum.setScale(1, RoundingMode.HALF_UP);

        // 4. 返回字符串格式结果（也可返回 BigDecimal 类型）
        return formattedHeight;
    }

}
