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.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.util.Calendar;
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.epidemic.EpidemicReportTestSamples;
import com.ruoyi.web.modules.epidemic.domain.BizEpidemicReport;
import com.ruoyi.web.modules.epidemic.domain.dto.EpidemicReportRelieveRequest;
import com.ruoyi.web.modules.epidemic.service.IBizEpidemicReportService;

/**
 * YQSB-API-001～024（MockMvc + Mock Service）
 */
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT)
@DisplayName("疫情上报 HTTP 接口 MockMvc")
class BizEpidemicReportControllerApiTest
{

    private final ObjectMapper objectMapper = new ObjectMapper();

    @Mock
    private IBizEpidemicReportService bizEpidemicReportService;

    @InjectMocks
    private BizEpidemicReportController 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("YQSB-API-001 GET /list 分页")
    void api001_list() throws Exception
    {
        when(bizEpidemicReportService.selectBizEpidemicReportList(any()))
                .thenReturn(Collections.singletonList(sample(1L)));
        mockMvc.perform(get("/diseaseDetection/epidemicReport/list").param("pageNum", "1").param("pageSize", "20"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200))
                .andExpect(jsonPath("$.rows").isArray());
    }

    @Test
    @DisplayName("YQSB-API-002 GET /list 传播途径筛选")
    void api002_listRoute() throws Exception
    {
        when(bizEpidemicReportService.selectBizEpidemicReportList(any())).thenReturn(Collections.emptyList());
        mockMvc.perform(get("/diseaseDetection/epidemicReport/list").param("transmissionRoute", "2"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("YQSB-API-004 GET /list 处置状态筛选")
    void api004_listRelieveStatus() throws Exception
    {
        when(bizEpidemicReportService.selectBizEpidemicReportList(any())).thenReturn(Collections.emptyList());
        mockMvc.perform(get("/diseaseDetection/epidemicReport/list").param("relieveStatus", "0"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("YQSB-API-005 POST 新增成功")
    void api005_add() throws Exception
    {
        when(bizEpidemicReportService.insertBizEpidemicReport(any())).thenReturn(1);
        mockMvc.perform(post("/diseaseDetection/epidemicReport")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(EpidemicReportTestSamples.sampleOpen())))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("YQSB-API-006 POST 非法枚举")
    void api006_addBadEnum() throws Exception
    {
        when(bizEpidemicReportService.insertBizEpidemicReport(any()))
                .thenThrow(new ServiceException("传播途径须为1～4"));
        BizEpidemicReport body = EpidemicReportTestSamples.sampleOpen();
        body.setTransmissionRoute(9);
        mockMvc.perform(post("/diseaseDetection/epidemicReport")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(body)))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(500));
    }

    @Test
    @DisplayName("YQSB-API-010 GET /{id} 详情")
    void api010_getDetail() throws Exception
    {
        when(bizEpidemicReportService.selectBizEpidemicReportById(2L)).thenReturn(sample(2L));
        mockMvc.perform(get("/diseaseDetection/epidemicReport/2"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.data.epidemicName").exists())
                .andExpect(jsonPath("$.data.relieveStatus").exists());
    }

    @Test
    @DisplayName("YQSB-API-012 PUT 未解除修改")
    void api012_put() throws Exception
    {
        when(bizEpidemicReportService.updateBizEpidemicReport(any())).thenReturn(1);
        BizEpidemicReport body = EpidemicReportTestSamples.sampleOpen();
        body.setId(8L);
        mockMvc.perform(put("/diseaseDetection/epidemicReport")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(body)))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("YQSB-API-013 PUT 已解除禁止修改")
    void api013_putRelieved() throws Exception
    {
        when(bizEpidemicReportService.updateBizEpidemicReport(any()))
                .thenThrow(new ServiceException("已解除的疫情上报不可修改"));
        BizEpidemicReport body = EpidemicReportTestSamples.sampleOpen();
        body.setId(8L);
        mockMvc.perform(put("/diseaseDetection/epidemicReport")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(body)))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(500))
                .andExpect(jsonPath("$.msg").value(containsString("解除")));
    }

    @Test
    @DisplayName("YQSB-API-015 PUT relieve 成功")
    void api015_relieve() throws Exception
    {
        when(bizEpidemicReportService.relieve(any(), eq("tester"))).thenReturn(1);
        EpidemicReportRelieveRequest req = new EpidemicReportRelieveRequest();
        req.setId(1L);
        req.setReleaseDate(EpidemicReportTestSamples.date(2026, Calendar.MAY, 20));
        mockMvc.perform(put("/diseaseDetection/epidemicReport/relieve")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(req)))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("YQSB-API-016 relieve 早于上报日")
    void api016_relieveEarly() throws Exception
    {
        when(bizEpidemicReportService.relieve(any(), any()))
                .thenThrow(new ServiceException("解除日期不能早于上报日期"));
        EpidemicReportRelieveRequest req = new EpidemicReportRelieveRequest();
        req.setId(1L);
        req.setReleaseDate(EpidemicReportTestSamples.date(2026, Calendar.MAY, 9));
        mockMvc.perform(put("/diseaseDetection/epidemicReport/relieve")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(req)))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(500));
    }

    @Test
    @DisplayName("YQSB-API-017 重复解除")
    void api017_relieveAgain() throws Exception
    {
        when(bizEpidemicReportService.relieve(any(), any()))
                .thenThrow(new ServiceException("仅未解除的疫情上报可执行解除"));
        EpidemicReportRelieveRequest req = new EpidemicReportRelieveRequest();
        req.setId(2L);
        req.setReleaseDate(EpidemicReportTestSamples.date(2026, Calendar.JUNE, 2));
        mockMvc.perform(put("/diseaseDetection/epidemicReport/relieve")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(req)))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(500));
    }

    @Test
    @DisplayName("YQSB-API-018 DELETE 未解除")
    void api018_delete() throws Exception
    {
        when(bizEpidemicReportService.deleteBizEpidemicReportByIds(any())).thenReturn(1);
        mockMvc.perform(delete("/diseaseDetection/epidemicReport/7"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("YQSB-API-024 失败可读")
    void api024_errorMsg() throws Exception
    {
        when(bizEpidemicReportService.updateBizEpidemicReport(any()))
                .thenThrow(new ServiceException("已解除的疫情上报不可修改"));
        mockMvc.perform(put("/diseaseDetection/epidemicReport")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(EpidemicReportTestSamples.sampleOpen())))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.msg").value(containsString("解除")));
    }

    private static BizEpidemicReport sample(Long id)
    {
        BizEpidemicReport r = EpidemicReportTestSamples.sampleOpen();
        r.setId(id);
        r.setRelieveStatus(0);
        return r;
    }
}
