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.BizGrasslandUsageRecord;
import com.ruoyi.web.modules.industryservice.service.IBizGrasslandUsageRecordService;
import com.ruoyi.web.modules.industryservice.support.GrasslandUsageRules;

/**
 * ZCZX-CCSYJL-API-001～029（MockMvc + Mock Service）
 */
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT)
@DisplayName("草场使用记录 HTTP 接口 MockMvc")
class BizGrasslandUsageRecordControllerApiTest
{
    private final ObjectMapper objectMapper = new ObjectMapper();

    @Mock
    private IBizGrasslandUsageRecordService bizGrasslandUsageRecordService;

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

    @Test
    @DisplayName("ZCZX-CCSYJL-API-002 关键字-草场名称")
    void api002_listKeyword() throws Exception
    {
        when(bizGrasslandUsageRecordService.selectBizGrasslandUsageRecordList(any()))
                .thenReturn(Collections.emptyList());
        mockMvc.perform(get("/dataModel/grasslandUsage/list").param("keyword", "示范"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("ZCZX-CCSYJL-API-003 预约日期区间")
    void api003_listCreateDateRange() throws Exception
    {
        when(bizGrasslandUsageRecordService.selectBizGrasslandUsageRecordList(any()))
                .thenReturn(Collections.emptyList());
        mockMvc.perform(get("/dataModel/grasslandUsage/list")
                .param("startDate", "2025-01-01")
                .param("endDate", "2025-06-30"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("ZCZX-CCSYJL-API-005 创建日期区间非法")
    void api005_listBadDateRange() throws Exception
    {
        when(bizGrasslandUsageRecordService.selectBizGrasslandUsageRecordList(any()))
                .thenThrow(new ServiceException("预约开始日期不能晚于结束日期"));
        mockMvc.perform(get("/dataModel/grasslandUsage/list")
                .param("startDate", "2025-12-01")
                .param("endDate", "2025-01-01"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(500));
    }

    @Test
    @DisplayName("ZCZX-CCSYJL-API-007 POST 新增成功")
    void api007_add() throws Exception
    {
        when(bizGrasslandUsageRecordService.insertBizGrasslandUsageRecord(any())).thenReturn(1);
        mockMvc.perform(post("/dataModel/grasslandUsage")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(sample(null))))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("ZCZX-CCSYJL-API-008 同日使用")
    void api008_sameDay() throws Exception
    {
        when(bizGrasslandUsageRecordService.insertBizGrasslandUsageRecord(any())).thenReturn(1);
        BizGrasslandUsageRecord body = sample(null);
        body.setUseStartDate(Date.valueOf("2025-06-01"));
        body.setUseEndDate(Date.valueOf("2025-06-01"));
        mockMvc.perform(post("/dataModel/grasslandUsage")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(body)))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("ZCZX-CCSYJL-API-011 使用面积超限")
    void api011_areaExceed() throws Exception
    {
        when(bizGrasslandUsageRecordService.insertBizGrasslandUsageRecord(any()))
                .thenThrow(new ServiceException("使用面积不能大于草场总面积"));
        mockMvc.perform(post("/dataModel/grasslandUsage")
                .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-CCSYJL-API-012 使用日期颠倒")
    void api012_badUseDates() throws Exception
    {
        when(bizGrasslandUsageRecordService.insertBizGrasslandUsageRecord(any()))
                .thenThrow(new ServiceException("开始使用日期不能晚于结束日期"));
        mockMvc.perform(post("/dataModel/grasslandUsage")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(sample(null))))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(500));
    }

    @Test
    @DisplayName("ZCZX-CCSYJL-API-013 主数据无效")
    void api013_invalidMaster() throws Exception
    {
        when(bizGrasslandUsageRecordService.insertBizGrasslandUsageRecord(any()))
                .thenThrow(new ServiceException("草场不存在或已失效"));
        mockMvc.perform(post("/dataModel/grasslandUsage")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(sample(null))))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(500));
    }

    @Test
    @DisplayName("ZCZX-CCSYJL-API-017 GET /{id} 详情")
    void api017_getDetail() throws Exception
    {
        BizGrasslandUsageRecord row = sample(2L);
        row.setGrasslandName("示范草场");
        row.setPastureName("示范牧场");
        when(bizGrasslandUsageRecordService.selectBizGrasslandUsageRecordById(2L)).thenReturn(row);
        mockMvc.perform(get("/dataModel/grasslandUsage/2"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200))
                .andExpect(jsonPath("$.data.grasslandName").value("示范草场"))
                .andExpect(jsonPath("$.data.actualUseDays").value(3));
    }

    @Test
    @DisplayName("ZCZX-CCSYJL-API-018 GET /{id} 不存在")
    void api018_getMissing() throws Exception
    {
        when(bizGrasslandUsageRecordService.selectBizGrasslandUsageRecordById(999L)).thenReturn(null);
        mockMvc.perform(get("/dataModel/grasslandUsage/999"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("ZCZX-CCSYJL-API-019 PUT 修改成功")
    void api019_put() throws Exception
    {
        when(bizGrasslandUsageRecordService.updateBizGrasslandUsageRecord(any())).thenReturn(1);
        BizGrasslandUsageRecord body = sample(8L);
        body.setUsageAreaMu(new BigDecimal("60"));
        mockMvc.perform(put("/dataModel/grasslandUsage")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(body)))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("ZCZX-CCSYJL-API-021 PUT 校验失败")
    void api021_putBad() throws Exception
    {
        when(bizGrasslandUsageRecordService.updateBizGrasslandUsageRecord(any()))
                .thenThrow(new ServiceException("放牧数量须为大于等于1的整数（头）"));
        mockMvc.perform(put("/dataModel/grasslandUsage")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(sample(8L))))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(500));
    }

    @Test
    @DisplayName("ZCZX-CCSYJL-API-022 DELETE 单条")
    void api022_delete() throws Exception
    {
        when(bizGrasslandUsageRecordService.deleteBizGrasslandUsageRecordByIds(any(), eq("tester"))).thenReturn(1);
        mockMvc.perform(delete("/dataModel/grasslandUsage/7"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("ZCZX-CCSYJL-API-023 DELETE 批量")
    void api023_deleteBatch() throws Exception
    {
        when(bizGrasslandUsageRecordService.deleteBizGrasslandUsageRecordByIds(any(), eq("tester"))).thenReturn(2);
        mockMvc.perform(delete("/dataModel/grasslandUsage/7,8"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("ZCZX-CCSYJL-API-029 失败可读")
    void api029_errorMessage() throws Exception
    {
        when(bizGrasslandUsageRecordService.insertBizGrasslandUsageRecord(any()))
                .thenThrow(new ServiceException("使用面积不能大于草场总面积"));
        mockMvc.perform(post("/dataModel/grasslandUsage")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(sample(null))))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").exists())
                .andExpect(jsonPath("$.msg").exists());
    }

    private static BizGrasslandUsageRecord sample(Long id)
    {
        BizGrasslandUsageRecord r = new BizGrasslandUsageRecord();
        r.setId(id);
        r.setGrasslandId(1L);
        r.setPastureId(2L);
        r.setUsageAreaMu(new BigDecimal("50"));
        r.setUseStartDate(Date.valueOf("2025-06-01"));
        r.setUseEndDate(Date.valueOf("2025-06-03"));
        r.setActualUseDays(3);
        r.setGrazingHeadCount(100);
        r.setGrazingMethod(GrasslandUsageRules.GRAZING_ROTATION);
        return r;
    }
}
