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

import static org.mockito.ArgumentMatchers.any;
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.post;
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.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.industryservice.domain.dto.GrassLivestockBalanceCalculateRequest;
import com.ruoyi.web.modules.industryservice.domain.vo.GrassLivestockBalanceDefaultsVo;
import com.ruoyi.web.modules.industryservice.domain.vo.GrassLivestockBalanceResultVo;
import com.ruoyi.web.modules.industryservice.service.IGrassLivestockBalanceService;
import com.ruoyi.web.modules.industryservice.support.GrassLivestockBalanceRules;

@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT)
@DisplayName("草畜平衡计算 HTTP 接口 MockMvc")
class GrassLivestockBalanceControllerApiTest
{
    private final ObjectMapper objectMapper = new ObjectMapper();

    @Mock
    private IGrassLivestockBalanceService grassLivestockBalanceService;

    @InjectMocks
    private GrassLivestockBalanceController controller;

    private MockMvc mockMvc;

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

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

    @Test
    @DisplayName("ZCZX-CXPH-API-001 POST /calculate 成功")
    void api001_calculate() throws Exception
    {
        when(grassLivestockBalanceService.calculate(any())).thenReturn(sampleResult());
        mockMvc.perform(post("/dataModel/grassLivestockBalance/calculate")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(sampleRequest())))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200))
                .andExpect(jsonPath("$.data.availableForageKg").value(22750.00))
                .andExpect(jsonPath("$.data.balanceLevel").value(4));
    }

    @Test
    @DisplayName("ZCZX-CXPH-API-006 缺草场id")
    void api006_missingGrassland() throws Exception
    {
        when(grassLivestockBalanceService.calculate(any()))
                .thenThrow(new ServiceException("请选择草场"));
        GrassLivestockBalanceCalculateRequest body = sampleRequest();
        body.setGrasslandId(null);
        mockMvc.perform(post("/dataModel/grassLivestockBalance/calculate")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(body)))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(500));
    }

    @Test
    @DisplayName("ZCZX-CXPH-API-007 面积非法")
    void api007_invalidArea() throws Exception
    {
        when(grassLivestockBalanceService.calculate(any()))
                .thenThrow(new ServiceException("草场面积须大于0（亩）"));
        mockMvc.perform(post("/dataModel/grassLivestockBalance/calculate")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(sampleRequest())))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(500));
    }

    @Test
    @DisplayName("ZCZX-CXPH-API-012 存栏为0")
    void api012_zeroBreeding() throws Exception
    {
        GrassLivestockBalanceResultVo result = sampleResult();
        result.setActualOverloadHeads(0);
        result.setBalanceLevel(GrassLivestockBalanceRules.BALANCE_LEVEL_NOT_OVERLOAD);
        when(grassLivestockBalanceService.calculate(any())).thenReturn(result);
        mockMvc.perform(post("/dataModel/grassLivestockBalance/calculate")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(sampleRequest())))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.data.actualOverloadHeads").value(0));
    }

    @Test
    @DisplayName("ZCZX-CXPH-API-014 GET /defaults")
    void api014_defaults() throws Exception
    {
        GrassLivestockBalanceDefaultsVo defaults = new GrassLivestockBalanceDefaultsVo();
        defaults.setSheepUnitAnnualForageKg(new BigDecimal("160"));
        defaults.setSheepUnitConvertCoeff(new BigDecimal("4"));
        when(grassLivestockBalanceService.getDefaults()).thenReturn(defaults);
        mockMvc.perform(get("/dataModel/grassLivestockBalance/defaults"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200))
                .andExpect(jsonPath("$.data.sheepUnitAnnualForageKg").value(160));
    }

    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);
    }

    private static GrassLivestockBalanceCalculateRequest sampleRequest()
    {
        GrassLivestockBalanceCalculateRequest req = new GrassLivestockBalanceCalculateRequest();
        req.setGrasslandId(1L);
        req.setAreaMu(new BigDecimal("100"));
        req.setGrassYieldPerMu(new BigDecimal("350"));
        req.setUtilizationRate(new BigDecimal("0.65"));
        req.setSheepUnitAnnualForageKg(new BigDecimal("160"));
        req.setSheepUnitConvertCoeff(new BigDecimal("4"));
        req.setBreedingHeadCount(100);
        return req;
    }

    private static GrassLivestockBalanceResultVo sampleResult()
    {
        GrassLivestockBalanceResultVo vo = new GrassLivestockBalanceResultVo();
        vo.setGrasslandId(1L);
        vo.setGrasslandName("示范草场");
        vo.setAvailableForageKg(new BigDecimal("22750.00"));
        vo.setBalanceLevel(GrassLivestockBalanceRules.BALANCE_LEVEL_SEVERE);
        vo.setBalanceLevelName("严重超载");
        vo.setActualOverloadHeads(64);
        return vo;
    }
}
