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

import static org.hamcrest.Matchers.containsString;
import static org.mockito.ArgumentMatchers.any;
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.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.LabDetectionTestSamples;
import com.ruoyi.web.modules.epidemic.domain.BizLabDetection;
import com.ruoyi.web.modules.epidemic.service.IBizLabDetectionService;

/**
 * SYJC-API-001～021（MockMvc + Mock Service）
 */
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT)
@DisplayName("实验室检测 HTTP 接口 MockMvc")
class BizLabDetectionControllerApiTest
{

    private final ObjectMapper objectMapper = new ObjectMapper();

    @Mock
    private IBizLabDetectionService bizLabDetectionService;

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

    @Test
    @DisplayName("SYJC-API-002 GET /list 样本来源筛选")
    void api002_listSampleSource() throws Exception
    {
        when(bizLabDetectionService.selectBizLabDetectionList(any())).thenReturn(Collections.emptyList());
        mockMvc.perform(get("/diseaseDetection/labDetection/list").param("sampleSource", "2"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("SYJC-API-022 GET /list 检疫点精确筛选")
    void api022_listQuarantineStation() throws Exception
    {
        when(bizLabDetectionService.selectBizLabDetectionList(any())).thenReturn(Collections.emptyList());
        mockMvc.perform(get("/diseaseDetection/labDetection/list").param("quarantineStationId", "2"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("SYJC-API-023 GET /quarantineStationOptions")
    void api023_quarantineStationOptions() throws Exception
    {
        com.ruoyi.web.modules.epidemic.domain.vo.QuarantineStationOptionVo opt =
                new com.ruoyi.web.modules.epidemic.domain.vo.QuarantineStationOptionVo();
        opt.setId(1L);
        opt.setStationName("测试检疫站");
        when(bizLabDetectionService.listQuarantineStationOptions())
                .thenReturn(Collections.singletonList(opt));
        mockMvc.perform(get("/diseaseDetection/labDetection/quarantineStationOptions"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200))
                .andExpect(jsonPath("$.data[0].stationName").value("测试检疫站"));
    }

    @Test
    @DisplayName("SYJC-API-003 GET /list 未选来源")
    void api003_listNoFilter() throws Exception
    {
        when(bizLabDetectionService.selectBizLabDetectionList(any()))
                .thenReturn(Collections.singletonList(sample(1L)));
        mockMvc.perform(get("/diseaseDetection/labDetection/list"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("SYJC-API-005 POST 新增成功")
    void api005_add() throws Exception
    {
        when(bizLabDetectionService.insertBizLabDetection(any())).thenReturn(1);
        mockMvc.perform(post("/diseaseDetection/labDetection")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(LabDetectionTestSamples.sample())))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("SYJC-API-006 POST 非法样本来源")
    void api006_addBadSource() throws Exception
    {
        when(bizLabDetectionService.insertBizLabDetection(any()))
                .thenThrow(new ServiceException("样本来源须为1～4（1场地抽检2疫情上报送检3调运检疫4日常检测）"));
        BizLabDetection body = LabDetectionTestSamples.sample();
        body.setSampleSource(9);
        mockMvc.perform(post("/diseaseDetection/labDetection")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(body)))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(500))
                .andExpect(jsonPath("$.msg").value(containsString("样本来源")));
    }

    @Test
    @DisplayName("SYJC-API-007 POST 必填缺失")
    void api007_addMissingDate() throws Exception
    {
        when(bizLabDetectionService.insertBizLabDetection(any()))
                .thenThrow(new ServiceException("检测日期不能为空"));
        BizLabDetection body = LabDetectionTestSamples.sample();
        body.setTestDate(null);
        mockMvc.perform(post("/diseaseDetection/labDetection")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(body)))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(500));
    }

    @Test
    @DisplayName("SYJC-API-008 POST 阳性大于检测量")
    void api008_addPositiveOverQuantity() throws Exception
    {
        when(bizLabDetectionService.insertBizLabDetection(any()))
                .thenThrow(new ServiceException("阳性检出数不能大于检测量"));
        BizLabDetection body = LabDetectionTestSamples.sample();
        body.setTestQuantity(10);
        body.setPositiveCount(11);
        mockMvc.perform(post("/diseaseDetection/labDetection")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(body)))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(500))
                .andExpect(jsonPath("$.msg").value(containsString("大于")));
    }

    @Test
    @DisplayName("SYJC-API-009 POST 零检测量阳性非零")
    void api009_addZeroQuantityPositive() throws Exception
    {
        when(bizLabDetectionService.insertBizLabDetection(any()))
                .thenThrow(new ServiceException("检测量为0时阳性检出数须为0"));
        BizLabDetection body = LabDetectionTestSamples.sample();
        body.setTestQuantity(0);
        body.setPositiveCount(1);
        mockMvc.perform(post("/diseaseDetection/labDetection")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(body)))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(500))
                .andExpect(jsonPath("$.msg").value(containsString("检测量为0")));
    }

    @Test
    @DisplayName("SYJC-API-010 POST 客户端检出率被忽略")
    void api010_addIgnoresClientRate() throws Exception
    {
        when(bizLabDetectionService.insertBizLabDetection(any())).thenReturn(1);
        BizLabDetection body = LabDetectionTestSamples.sample();
        body.setTestQuantity(10);
        body.setPositiveCount(1);
        body.setDetectionRate(new BigDecimal("0.9900"));
        mockMvc.perform(post("/diseaseDetection/labDetection")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(body)))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("SYJC-API-011 GET /{id} 详情")
    void api011_getDetail() throws Exception
    {
        BizLabDetection row = sample(2L);
        row.setDetectionRate(new BigDecimal("0.0500"));
        when(bizLabDetectionService.selectBizLabDetectionById(2L)).thenReturn(row);
        mockMvc.perform(get("/diseaseDetection/labDetection/2"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200))
                .andExpect(jsonPath("$.data.testDate").exists())
                .andExpect(jsonPath("$.data.sampleSource").exists())
                .andExpect(jsonPath("$.data.detectionRate").exists());
    }

    @Test
    @DisplayName("SYJC-API-013 PUT 修改成功")
    void api013_put() throws Exception
    {
        when(bizLabDetectionService.updateBizLabDetection(any())).thenReturn(1);
        BizLabDetection body = LabDetectionTestSamples.sample();
        body.setId(1L);
        body.setTestQuantity(50);
        body.setPositiveCount(5);
        mockMvc.perform(put("/diseaseDetection/labDetection")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(body)))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("SYJC-API-014 PUT 阳性超量")
    void api014_putPositiveOver() throws Exception
    {
        when(bizLabDetectionService.updateBizLabDetection(any()))
                .thenThrow(new ServiceException("阳性检出数不能大于检测量"));
        BizLabDetection body = LabDetectionTestSamples.sample();
        body.setId(1L);
        body.setTestQuantity(5);
        body.setPositiveCount(10);
        mockMvc.perform(put("/diseaseDetection/labDetection")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(body)))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(500));
    }

    @Test
    @DisplayName("SYJC-API-015 PUT 携带检出率被忽略")
    void api015_putIgnoresClientRate() throws Exception
    {
        when(bizLabDetectionService.updateBizLabDetection(any())).thenReturn(1);
        BizLabDetection body = LabDetectionTestSamples.sample();
        body.setId(1L);
        body.setTestQuantity(10);
        body.setPositiveCount(2);
        body.setDetectionRate(new BigDecimal("0.5000"));
        mockMvc.perform(put("/diseaseDetection/labDetection")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(body)))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("SYJC-API-016 DELETE 单条")
    void api016_delete() throws Exception
    {
        when(bizLabDetectionService.deleteBizLabDetectionByIds(any())).thenReturn(1);
        mockMvc.perform(delete("/diseaseDetection/labDetection/3"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("SYJC-API-017 DELETE 批量")
    void api017_deleteBatch() throws Exception
    {
        when(bizLabDetectionService.deleteBizLabDetectionByIds(any())).thenReturn(2);
        mockMvc.perform(delete("/diseaseDetection/labDetection/1,2"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("SYJC-API-021 失败可读提示")
    void api021_errorMessage() throws Exception
    {
        when(bizLabDetectionService.insertBizLabDetection(any()))
                .thenThrow(new ServiceException("阳性检出数不能大于检测量"));
        BizLabDetection body = LabDetectionTestSamples.sample();
        body.setTestQuantity(10);
        body.setPositiveCount(11);
        mockMvc.perform(post("/diseaseDetection/labDetection")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(body)))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(500))
                .andExpect(jsonPath("$.msg").value(containsString("阳性检出数")));
    }

    private static BizLabDetection sample(Long id)
    {
        BizLabDetection row = LabDetectionTestSamples.sample();
        row.setId(id);
        row.setDetectionRate(new BigDecimal("0.0500"));
        return row;
    }
}
