package com.ruoyi.web.modules.circulation.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.Collections;
import java.util.HashSet;
import java.util.Set;

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.circulation.domain.BizQuarantineStation;
import com.ruoyi.web.modules.circulation.service.IBizQuarantineStationService;
import com.ruoyi.web.modules.circulation.support.QuarantineStationRules;
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;

/**
 * ZCZX-JYZGL-API-001～027（MockMvc + Mock Service）
 */
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT)
@DisplayName("检疫站管理 HTTP 接口 MockMvc")
class BizQuarantineStationControllerApiTest
{
    private static final String VALID_PHONE = "13800138000";

    private final ObjectMapper objectMapper = new ObjectMapper();

    @Mock
    private IBizQuarantineStationService bizQuarantineStationService;

    @InjectMocks
    private BizQuarantineStationController 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-JYZGL-API-001 GET /list 分页")
    void api001_list() throws Exception
    {
        when(bizQuarantineStationService.selectBizQuarantineStationList(any()))
                .thenReturn(Collections.singletonList(sample(1L)));
        mockMvc.perform(get("/livestock/quarantineStation/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-JYZGL-API-002 GET /list 名称模糊")
    void api002_listStationName() throws Exception
    {
        when(bizQuarantineStationService.selectBizQuarantineStationList(any()))
                .thenReturn(Collections.emptyList());
        mockMvc.perform(get("/livestock/quarantineStation/list").param("stationName", "检疫"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("ZCZX-JYZGL-API-003 GET /list 运营状态")
    void api003_listOperateStatus() throws Exception
    {
        when(bizQuarantineStationService.selectBizQuarantineStationList(any()))
                .thenReturn(Collections.emptyList());
        mockMvc.perform(get("/livestock/quarantineStation/list").param("operateStatus", "2"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("ZCZX-JYZGL-API-004 GET /list 组合筛选")
    void api004_listCombo() throws Exception
    {
        when(bizQuarantineStationService.selectBizQuarantineStationList(any()))
                .thenReturn(Collections.emptyList());
        mockMvc.perform(get("/livestock/quarantineStation/list")
                .param("stationName", "测试")
                .param("operateStatus", "3"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("ZCZX-JYZGL-API-007 POST 新增含照片")
    void api007_add() throws Exception
    {
        when(bizQuarantineStationService.insertBizQuarantineStation(any())).thenReturn(1);
        mockMvc.perform(post("/livestock/quarantineStation")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(sample(null))))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("ZCZX-JYZGL-API-008 POST 无照片")
    void api008_addNoPhoto() throws Exception
    {
        when(bizQuarantineStationService.insertBizQuarantineStation(any())).thenReturn(1);
        BizQuarantineStation body = sample(null);
        body.setPhotoFileUrl(null);
        body.setPhotoFilePath(null);
        mockMvc.perform(post("/livestock/quarantineStation")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(body)))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("ZCZX-JYZGL-API-009 POST 缺必填")
    void api009_addMissing() throws Exception
    {
        when(bizQuarantineStationService.insertBizQuarantineStation(any()))
                .thenThrow(new ServiceException("检疫站名称须为1～10个字符"));
        BizQuarantineStation body = sample(null);
        body.setStationName("");
        mockMvc.perform(post("/livestock/quarantineStation")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(body)))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(500))
                .andExpect(jsonPath("$.msg").value(containsString("检疫站名称")));
    }

    @Test
    @DisplayName("ZCZX-JYZGL-API-011 POST 名称重复")
    void api011_addDuplicateName() throws Exception
    {
        when(bizQuarantineStationService.insertBizQuarantineStation(any()))
                .thenThrow(new ServiceException("检疫站名称已存在"));
        mockMvc.perform(post("/livestock/quarantineStation")
                .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-JYZGL-API-012 POST 手机号非法")
    void api012_addBadPhone() throws Exception
    {
        when(bizQuarantineStationService.insertBizQuarantineStation(any()))
                .thenThrow(new ServiceException("请输入正确的手机号码"));
        mockMvc.perform(post("/livestock/quarantineStation")
                .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-JYZGL-API-013 POST 状态非法")
    void api013_addBadStatus() throws Exception
    {
        when(bizQuarantineStationService.insertBizQuarantineStation(any()))
                .thenThrow(new ServiceException("运营状态须为1～3（1正常2停业3注销）"));
        mockMvc.perform(post("/livestock/quarantineStation")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(sample(null))))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(500));
    }

    @Test
    @DisplayName("ZCZX-JYZGL-API-014 GET /{id} 详情")
    void api014_getDetail() throws Exception
    {
        BizQuarantineStation row = sample(2L);
        row.setOperateStatusName("正常");
        when(bizQuarantineStationService.selectBizQuarantineStationById(2L)).thenReturn(row);
        mockMvc.perform(get("/livestock/quarantineStation/2"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200))
                .andExpect(jsonPath("$.data.stationName").exists())
                .andExpect(jsonPath("$.data.operateStatus").exists());
    }

    @Test
    @DisplayName("ZCZX-JYZGL-API-015 GET /{id} 不存在")
    void api015_getMissing() throws Exception
    {
        when(bizQuarantineStationService.selectBizQuarantineStationById(999999L)).thenReturn(null);
        mockMvc.perform(get("/livestock/quarantineStation/999999"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("ZCZX-JYZGL-API-016 PUT 修改")
    void api016_put() throws Exception
    {
        when(bizQuarantineStationService.updateBizQuarantineStation(any())).thenReturn(1);
        BizQuarantineStation body = sample(8L);
        body.setDetailAddress("新地址路99号");
        mockMvc.perform(put("/livestock/quarantineStation")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(body)))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("ZCZX-JYZGL-API-017 PUT 改运营状态")
    void api017_putOperateStatus() throws Exception
    {
        when(bizQuarantineStationService.updateBizQuarantineStation(any())).thenReturn(1);
        BizQuarantineStation body = sample(8L);
        body.setOperateStatus(QuarantineStationRules.OPERATE_STATUS_SUSPENDED);
        mockMvc.perform(put("/livestock/quarantineStation")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(body)))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("ZCZX-JYZGL-API-019 PUT 不存在")
    void api019_putMissing() throws Exception
    {
        when(bizQuarantineStationService.updateBizQuarantineStation(any()))
                .thenThrow(new ServiceException("记录不存在或已删除"));
        mockMvc.perform(put("/livestock/quarantineStation")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(sample(999L))))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(500));
    }

    @Test
    @DisplayName("ZCZX-JYZGL-API-020 DELETE 单条")
    void api020_delete() throws Exception
    {
        when(bizQuarantineStationService.deleteBizQuarantineStationByIds(any(), eq("tester"))).thenReturn(1);
        mockMvc.perform(delete("/livestock/quarantineStation/7"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("ZCZX-JYZGL-API-021 DELETE 有关联拒绝")
    void api021_deleteBlocked() throws Exception
    {
        when(bizQuarantineStationService.deleteBizQuarantineStationByIds(any(), eq("tester")))
                .thenThrow(new ServiceException("存在关联业务，无法删除"));
        mockMvc.perform(delete("/livestock/quarantineStation/7"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(500))
                .andExpect(jsonPath("$.msg").value(containsString("关联业务")));
    }

    @Test
    @DisplayName("ZCZX-JYZGL-API-027 失败可读")
    void api027_errorMessage() throws Exception
    {
        when(bizQuarantineStationService.insertBizQuarantineStation(any()))
                .thenThrow(new ServiceException("详细地址须为1～200个字符"));
        mockMvc.perform(post("/livestock/quarantineStation")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(sample(null))))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").exists())
                .andExpect(jsonPath("$.msg").exists());
    }

    private static BizQuarantineStation sample(Long id)
    {
        BizQuarantineStation r = new BizQuarantineStation();
        r.setId(id);
        r.setStationName("巴青东站");
        r.setDetailAddress("西藏那曲市巴青县某某路1号");
        r.setPersonInCharge("李四");
        r.setContactPhone(VALID_PHONE);
        r.setOperateStatus(QuarantineStationRules.OPERATE_STATUS_NORMAL);
        r.setPhotoFileUrl("http://localhost/profile/upload/q.jpg");
        r.setPhotoFilePath(Constants.RESOURCE_PREFIX + "/upload/q.jpg");
        return r;
    }
}
