package com.ruoyi.web.modules.epidemic.controller;

import static org.hamcrest.Matchers.containsString;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import java.math.BigDecimal;
import java.util.HashSet;
import java.util.Set;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.framework.web.exception.GlobalExceptionHandler;
import com.ruoyi.web.modules.epidemic.RiskFactorWeightTestSamples;
import com.ruoyi.web.modules.epidemic.domain.vo.RiskFactorWeightVo;
import com.ruoyi.web.modules.epidemic.service.IBizRiskFactorWeightService;

/**
 * FXYZ-API-001～015（MockMvc + Mock Service）
 */
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT)
@DisplayName("风险因子权重 HTTP 接口 MockMvc")
class BizRiskFactorWeightControllerApiTest
{

    private final ObjectMapper objectMapper = new ObjectMapper();

    @Mock
    private IBizRiskFactorWeightService bizRiskFactorWeightService;

    @InjectMocks
    private BizRiskFactorWeightController controller;

    private MockMvc mockMvc;

    @BeforeEach
    void setUp()
    {
        mockMvc = MockMvcBuilders.standaloneSetup(controller)
                .setControllerAdvice(new GlobalExceptionHandler())
                .build();
        loginAsAllPermissions();
    }

    @AfterEach
    void tearDown()
    {
        SecurityContextHolder.clearContext();
        PageHelper.clearPage();
    }

    private static void loginAsAllPermissions()
    {
        SysUser u = new SysUser();
        u.setUserId(1L);
        u.setUserName("tester");
        u.setPassword("x");
        Set<String> perms = new HashSet<>();
        perms.add(Constants.ALL_PERMISSION);
        LoginUser lu = new LoginUser(1L, 100L, u, perms);
        UsernamePasswordAuthenticationToken auth =
                new UsernamePasswordAuthenticationToken(lu, "", lu.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(auth);
    }

    @Test
    @DisplayName("FXYZ-API-001 GET 获取当前权重")
    void api001_get() throws Exception
    {
        RiskFactorWeightVo vo = sampleVo();
        when(bizRiskFactorWeightService.getCurrentConfig()).thenReturn(vo);
        mockMvc.perform(get("/diseaseDetection/riskFactorWeight"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200))
                .andExpect(jsonPath("$.data.breedingDensityWeight").value(0.2))
                .andExpect(jsonPath("$.data.weightSum").value(1.0));
    }

    @Test
    @DisplayName("FXYZ-API-002 GET 无配置")
    void api002_getNull() throws Exception
    {
        when(bizRiskFactorWeightService.getCurrentConfig()).thenReturn(null);
        mockMvc.perform(get("/diseaseDetection/riskFactorWeight"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("FXYZ-API-003 PUT 合法五项各 0.2")
    void api003_putUniform() throws Exception
    {
        when(bizRiskFactorWeightService.saveConfig(any(), eq("tester"))).thenReturn(1);
        mockMvc.perform(put("/diseaseDetection/riskFactorWeight")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(RiskFactorWeightTestSamples.uniformRequest())))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("FXYZ-API-004 PUT 合法非均分")
    void api004_putUneven() throws Exception
    {
        when(bizRiskFactorWeightService.saveConfig(any(), eq("tester"))).thenReturn(1);
        mockMvc.perform(put("/diseaseDetection/riskFactorWeight")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(RiskFactorWeightTestSamples.request(
                        new BigDecimal("0.3"),
                        new BigDecimal("0.25"),
                        new BigDecimal("0.2"),
                        new BigDecimal("0.15"),
                        new BigDecimal("0.1")))))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("FXYZ-API-005 PUT 合计不为 1")
    void api005_putSumInvalid() throws Exception
    {
        when(bizRiskFactorWeightService.saveConfig(any(), any()))
                .thenThrow(new ServiceException("五项权重之和须等于 1，当前合计为 1.5000"));
        mockMvc.perform(put("/diseaseDetection/riskFactorWeight")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(RiskFactorWeightTestSamples.request(
                        new BigDecimal("0.3"),
                        new BigDecimal("0.3"),
                        new BigDecimal("0.3"),
                        new BigDecimal("0.3"),
                        new BigDecimal("0.3")))))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(500))
                .andExpect(jsonPath("$.msg").value(containsString("之和须等于 1")));
    }

    @Test
    @DisplayName("FXYZ-API-006 PUT 某项为 0")
    void api006_putZeroWeight() throws Exception
    {
        when(bizRiskFactorWeightService.saveConfig(any(), any()))
                .thenThrow(new ServiceException("【养殖密度】权重须为正数"));
        com.ruoyi.web.modules.epidemic.domain.dto.RiskFactorWeightSaveRequest req =
                RiskFactorWeightTestSamples.uniformRequest();
        req.setBreedingDensityWeight(BigDecimal.ZERO);
        mockMvc.perform(put("/diseaseDetection/riskFactorWeight")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(req)))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(500))
                .andExpect(jsonPath("$.msg").value(containsString("正数")));
    }

    @Test
    @DisplayName("FXYZ-API-007 PUT 某项为负数")
    void api007_putNegative() throws Exception
    {
        when(bizRiskFactorWeightService.saveConfig(any(), any()))
                .thenThrow(new ServiceException("【交通流动性】权重须为正数"));
        com.ruoyi.web.modules.epidemic.domain.dto.RiskFactorWeightSaveRequest req =
                RiskFactorWeightTestSamples.uniformRequest();
        req.setTrafficMobilityWeight(new BigDecimal("-0.1"));
        mockMvc.perform(put("/diseaseDetection/riskFactorWeight")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(req)))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(500))
                .andExpect(jsonPath("$.msg").value(containsString("交通流动性")));
    }

    @Test
    @DisplayName("FXYZ-API-008 PUT 必填缺失")
    void api008_putMissingField() throws Exception
    {
        when(bizRiskFactorWeightService.saveConfig(any(), any()))
                .thenThrow(new ServiceException("请填写【既往发病水平】权重"));
        com.ruoyi.web.modules.epidemic.domain.dto.RiskFactorWeightSaveRequest req =
                RiskFactorWeightTestSamples.uniformRequest();
        req.setPastDiseaseLevelWeight(null);
        mockMvc.perform(put("/diseaseDetection/riskFactorWeight")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(req)))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(500))
                .andExpect(jsonPath("$.msg").value(containsString("既往发病水平")));
    }

    @Test
    @DisplayName("FXYZ-API-015 失败可读提示")
    void api015_errorReadable() throws Exception
    {
        when(bizRiskFactorWeightService.saveConfig(any(), any()))
                .thenThrow(new ServiceException("请填写【检疫强度】权重"));
        com.ruoyi.web.modules.epidemic.domain.dto.RiskFactorWeightSaveRequest req =
                RiskFactorWeightTestSamples.uniformRequest();
        req.setQuarantineIntensityWeight(null);
        mockMvc.perform(put("/diseaseDetection/riskFactorWeight")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(req)))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(500))
                .andExpect(jsonPath("$.msg").value(containsString("检疫强度")));
    }

    private static RiskFactorWeightVo sampleVo()
    {
        RiskFactorWeightVo vo = new RiskFactorWeightVo();
        vo.setBreedingDensityWeight(new BigDecimal("0.2"));
        vo.setTrafficMobilityWeight(new BigDecimal("0.2"));
        vo.setQuarantineIntensityWeight(new BigDecimal("0.2"));
        vo.setMeteorologicalSuitabilityWeight(new BigDecimal("0.2"));
        vo.setPastDiseaseLevelWeight(new BigDecimal("0.2"));
        vo.setWeightSum(new BigDecimal("1.0"));
        vo.setUpdateBy("admin");
        return vo;
    }
}
