package com.ruoyi.web.modules.industryservice.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.delete;
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.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.sql.Date;
import java.util.Collections;
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.industryservice.domain.BizGrassland;
import com.ruoyi.web.modules.industryservice.service.IBizGrasslandService;
import com.ruoyi.web.modules.industryservice.support.GrasslandRules;

/**
 * ZCZX-CCGL-API-001～031（MockMvc + Mock Service）
 */
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT)
@DisplayName("草场管理 HTTP 接口 MockMvc")
class BizGrasslandControllerApiTest
{
    private final ObjectMapper objectMapper = new ObjectMapper();

    @Mock
    private IBizGrasslandService bizGrasslandService;

    @InjectMocks
    private BizGrasslandController 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("ZCZX-CCGL-API-001 GET /list 分页")
    void api001_list() throws Exception
    {
        when(bizGrasslandService.selectBizGrasslandList(any())).thenReturn(Collections.singletonList(sample(1L)));
        mockMvc.perform(get("/dataModel/grassland/list").param("pageNum", "1").param("pageSize", "10"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200))
                .andExpect(jsonPath("$.rows").isArray())
                .andExpect(jsonPath("$.rows.length()").value(1));
    }

    @Test
    @DisplayName("ZCZX-CCGL-API-002 GET /list 关键字")
    void api002_listKeyword() throws Exception
    {
        when(bizGrasslandService.selectBizGrasslandList(any())).thenReturn(Collections.emptyList());
        mockMvc.perform(get("/dataModel/grassland/list").param("keyword", "示范"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("ZCZX-CCGL-API-003 利用类型筛选")
    void api003_listUtilizationType() throws Exception
    {
        when(bizGrasslandService.selectBizGrasslandList(any())).thenReturn(Collections.emptyList());
        mockMvc.perform(get("/dataModel/grassland/list").param("utilizationType", "2"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("ZCZX-CCGL-API-004 退化等级筛选")
    void api004_listDegradationLevel() throws Exception
    {
        when(bizGrasslandService.selectBizGrasslandList(any())).thenReturn(Collections.emptyList());
        mockMvc.perform(get("/dataModel/grassland/list").param("degradationLevel", "3"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("ZCZX-CCGL-API-005 组合查询")
    void api005_listCombo() throws Exception
    {
        when(bizGrasslandService.selectBizGrasslandList(any())).thenReturn(Collections.emptyList());
        mockMvc.perform(get("/dataModel/grassland/list")
                .param("keyword", "草")
                .param("utilizationType", "1")
                .param("degradationLevel", "2"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("ZCZX-CCGL-API-008 POST 新增成功")
    void api008_add() throws Exception
    {
        when(bizGrasslandService.insertBizGrassland(any())).thenReturn(1);
        mockMvc.perform(post("/dataModel/grassland")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(sample(null))))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("ZCZX-CCGL-API-009 POST 最小必填无备注")
    void api009_addMinimal() throws Exception
    {
        when(bizGrasslandService.insertBizGrassland(any())).thenReturn(1);
        BizGrassland body = sample(null);
        body.setRemark(null);
        mockMvc.perform(post("/dataModel/grassland")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(body)))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("ZCZX-CCGL-API-010 POST 禁牧类型")
    void api010_addBanType() throws Exception
    {
        when(bizGrasslandService.insertBizGrassland(any())).thenReturn(1);
        BizGrassland body = sample(null);
        body.setUtilizationType(GrasslandRules.UTILIZATION_BAN);
        mockMvc.perform(post("/dataModel/grassland")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(body)))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("ZCZX-CCGL-API-013 POST 名称非法")
    void api013_addBadName() throws Exception
    {
        when(bizGrasslandService.insertBizGrassland(any()))
                .thenThrow(new ServiceException("草场名称须为1～10个字符"));
        BizGrassland body = sample(null);
        body.setGrasslandName("");
        mockMvc.perform(post("/dataModel/grassland")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(body)))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(500))
                .andExpect(jsonPath("$.msg").value(containsString("草场名称")));
    }

    @Test
    @DisplayName("ZCZX-CCGL-API-014 POST 枚举非法")
    void api014_addBadEnum() throws Exception
    {
        when(bizGrasslandService.insertBizGrassland(any()))
                .thenThrow(new ServiceException("退化等级须为1～5（1未退化5极重度）"));
        mockMvc.perform(post("/dataModel/grassland")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(sample(null))))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(500));
    }

    @Test
    @DisplayName("ZCZX-CCGL-API-015 POST 面积非法")
    void api015_addBadArea() throws Exception
    {
        when(bizGrasslandService.insertBizGrassland(any()))
                .thenThrow(new ServiceException("面积须为大于0的数字（亩）"));
        mockMvc.perform(post("/dataModel/grassland")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(sample(null))))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(500));
    }

    @Test
    @DisplayName("ZCZX-CCGL-API-016 POST 利用率越界")
    void api016_addBadRate() throws Exception
    {
        when(bizGrasslandService.insertBizGrassland(any()))
                .thenThrow(new ServiceException("利用率须在0～1之间"));
        mockMvc.perform(post("/dataModel/grassland")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(sample(null))))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(500))
                .andExpect(jsonPath("$.msg").value(containsString("利用率")));
    }

    @Test
    @DisplayName("ZCZX-CCGL-API-017 POST 禁牧日期颠倒")
    void api017_addBadDates() throws Exception
    {
        when(bizGrasslandService.insertBizGrassland(any()))
                .thenThrow(new ServiceException("禁牧开始日期不能晚于结束日期"));
        mockMvc.perform(post("/dataModel/grassland")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(sample(null))))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(500));
    }

    @Test
    @DisplayName("ZCZX-CCGL-API-019 GET /{id} 详情")
    void api019_getDetail() throws Exception
    {
        when(bizGrasslandService.selectBizGrasslandById(2L)).thenReturn(sample(2L));
        mockMvc.perform(get("/dataModel/grassland/2"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200))
                .andExpect(jsonPath("$.data.grasslandName").exists())
                .andExpect(jsonPath("$.data.areaMu").exists())
                .andExpect(jsonPath("$.data.utilizationType").exists());
    }

    @Test
    @DisplayName("ZCZX-CCGL-API-020 GET /{id} 不存在")
    void api020_getMissing() throws Exception
    {
        when(bizGrasslandService.selectBizGrasslandById(999999L)).thenReturn(null);
        mockMvc.perform(get("/dataModel/grassland/999999"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("ZCZX-CCGL-API-022 PUT 修改成功")
    void api022_put() throws Exception
    {
        when(bizGrasslandService.updateBizGrassland(any())).thenReturn(1);
        BizGrassland body = sample(8L);
        body.setGrasslandName("更新草场");
        body.setAreaMu(new BigDecimal("150"));
        mockMvc.perform(put("/dataModel/grassland")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(body)))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("ZCZX-CCGL-API-023 PUT 利用类型变更")
    void api023_putUtilizationType() throws Exception
    {
        when(bizGrasslandService.updateBizGrassland(any())).thenReturn(1);
        BizGrassland body = sample(8L);
        body.setUtilizationType(GrasslandRules.UTILIZATION_YEAR_ROUND);
        mockMvc.perform(put("/dataModel/grassland")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(body)))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("ZCZX-CCGL-API-025 PUT 校验失败")
    void api025_putBadRate() throws Exception
    {
        when(bizGrasslandService.updateBizGrassland(any()))
                .thenThrow(new ServiceException("利用率须在0～1之间"));
        mockMvc.perform(put("/dataModel/grassland")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(sample(8L))))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(500));
    }

    @Test
    @DisplayName("ZCZX-CCGL-API-026 DELETE 单条")
    void api026_delete() throws Exception
    {
        when(bizGrasslandService.deleteBizGrasslandByIds(any(), eq("tester"))).thenReturn(1);
        mockMvc.perform(delete("/dataModel/grassland/7"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("ZCZX-CCGL-API-027 DELETE 批量")
    void api027_deleteBatch() throws Exception
    {
        when(bizGrasslandService.deleteBizGrasslandByIds(any(), eq("tester"))).thenReturn(2);
        mockMvc.perform(delete("/dataModel/grassland/7,8"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("ZCZX-CCGL-API-031 失败可读")
    void api031_errorMessage() throws Exception
    {
        when(bizGrasslandService.insertBizGrassland(any()))
                .thenThrow(new ServiceException("草场名称须为1～10个字符"));
        mockMvc.perform(post("/dataModel/grassland")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(sample(null))))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").exists())
                .andExpect(jsonPath("$.msg").exists());
    }

    private static BizGrassland sample(Long id)
    {
        BizGrassland r = new BizGrassland();
        r.setId(id);
        r.setGrasslandName("示范草场");
        r.setAreaMu(new BigDecimal("100.5"));
        r.setDegradationLevel(GrasslandRules.DEGRADATION_NONE);
        r.setUtilizationType(GrasslandRules.UTILIZATION_ROTATION);
        r.setGrassYieldPerMu(new BigDecimal("350"));
        r.setUtilizationRate(new BigDecimal("0.65"));
        r.setGrazingBanStartDate(Date.valueOf("2025-01-01"));
        r.setGrazingBanEndDate(Date.valueOf("2025-03-31"));
        r.setRotationPlotCount(4);
        r.setRotationGrazingDays(7);
        r.setRotationCycleDays(28);
        return r;
    }
}
