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

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.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.architecture.domain.BizWithdrawalPeriodStandard;
import com.ruoyi.web.modules.architecture.service.IBizWithdrawalPeriodStandardService;

/**
 * 休药期标准 HTTP 接口 MockMvc（Mock Service）。
 */
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT)
@DisplayName("休药期标准 HTTP 接口 MockMvc")
class BizWithdrawalPeriodStandardControllerApiTest
{

    private final ObjectMapper objectMapper = new ObjectMapper();

    @Mock
    private IBizWithdrawalPeriodStandardService bizWithdrawalPeriodStandardService;

    @InjectMocks
    private BizWithdrawalPeriodStandardController 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("GET /list")
    void api001_list() throws Exception
    {
        when(bizWithdrawalPeriodStandardService.selectBizWithdrawalPeriodStandardList(any()))
                .thenReturn(Collections.singletonList(sample(1L)));
        mockMvc.perform(get("/withdrawalPeriod/standard/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("GET /list keyword + drugType")
    void api002_listQuery() throws Exception
    {
        when(bizWithdrawalPeriodStandardService.selectBizWithdrawalPeriodStandardList(any())).thenReturn(Collections.emptyList());
        mockMvc.perform(get("/withdrawalPeriod/standard/list").param("keyword", "阿").param("drugType", "1"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("POST 新增成功")
    void api003_add() throws Exception
    {
        when(bizWithdrawalPeriodStandardService.insertBizWithdrawalPeriodStandard(any())).thenReturn(1);
        mockMvc.perform(post("/withdrawalPeriod/standard")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(sample(null))))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("POST 新增业务校验失败")
    void api004_addServiceError() throws Exception
    {
        when(bizWithdrawalPeriodStandardService.insertBizWithdrawalPeriodStandard(any()))
                .thenThrow(new ServiceException("药物名称须为1～20个字符"));
        BizWithdrawalPeriodStandard body = sample(null);
        body.setDrugName("");
        mockMvc.perform(post("/withdrawalPeriod/standard")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(body)))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(500));
    }

    @Test
    @DisplayName("GET /{id} 详情")
    void api005_getDetail() throws Exception
    {
        when(bizWithdrawalPeriodStandardService.selectBizWithdrawalPeriodStandardById(2L)).thenReturn(sample(2L));
        mockMvc.perform(get("/withdrawalPeriod/standard/2"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200))
                .andExpect(jsonPath("$.data.drugName").exists())
                .andExpect(jsonPath("$.data.kbSyncStatus").exists());
    }

    @Test
    @DisplayName("PUT 修改成功")
    void api006_put() throws Exception
    {
        when(bizWithdrawalPeriodStandardService.updateBizWithdrawalPeriodStandard(any())).thenReturn(1);
        mockMvc.perform(put("/withdrawalPeriod/standard")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(sample(8L))))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("PUT 已同步拒绝")
    void api007_putSynced() throws Exception
    {
        when(bizWithdrawalPeriodStandardService.updateBizWithdrawalPeriodStandard(any()))
                .thenThrow(new ServiceException("仅「未同步」状态允许编辑"));
        mockMvc.perform(put("/withdrawalPeriod/standard")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(sample(8L))))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(500));
    }

    @Test
    @DisplayName("DELETE 未同步")
    void api008_delete() throws Exception
    {
        when(bizWithdrawalPeriodStandardService.deleteBizWithdrawalPeriodStandardByIds(any())).thenReturn(1);
        mockMvc.perform(delete("/withdrawalPeriod/standard/7"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("DELETE 已同步禁止")
    void api009_deleteSynced() throws Exception
    {
        when(bizWithdrawalPeriodStandardService.deleteBizWithdrawalPeriodStandardByIds(any()))
                .thenThrow(new ServiceException("已同步的数据不可删除，请先移出知识库"));
        mockMvc.perform(delete("/withdrawalPeriod/standard/7"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(500));
    }

    @Test
    @DisplayName("POST syncKb")
    void api010_syncKb() throws Exception
    {
        when(bizWithdrawalPeriodStandardService.syncKb(11L)).thenReturn(1);
        mockMvc.perform(post("/withdrawalPeriod/standard/syncKb/11"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("POST syncKb 非法状态")
    void api011_syncKbFail() throws Exception
    {
        when(bizWithdrawalPeriodStandardService.syncKb(12L))
                .thenThrow(new ServiceException("仅「未同步」可操作同步知识库（未对接知识库服务）"));
        mockMvc.perform(post("/withdrawalPeriod/standard/syncKb/12"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(500));
    }

    @Test
    @DisplayName("POST removeKb")
    void api012_removeKb() throws Exception
    {
        when(bizWithdrawalPeriodStandardService.removeKb(13L)).thenReturn(1);
        mockMvc.perform(post("/withdrawalPeriod/standard/removeKb/13"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    private static BizWithdrawalPeriodStandard sample(Long id)
    {
        BizWithdrawalPeriodStandard r = new BizWithdrawalPeriodStandard();
        r.setId(id);
        r.setDrugName("药");
        r.setDrugType(1);
        r.setWithdrawalDays(5);
        r.setUsageGuide("使用说明");
        r.setDrugEffect("药物作用描述");
        r.setKbSyncStatus(0);
        return r;
    }
}
