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.BizDrugIncompatibilityCompanion;
import com.ruoyi.web.modules.architecture.domain.BizDrugIncompatibilityStandard;
import com.ruoyi.web.modules.architecture.service.IBizDrugIncompatibilityStandardService;

@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT)
@DisplayName("药物禁配标准 Controller MockMvc")
class BizDrugIncompatibilityStandardControllerApiTest
{

    private final ObjectMapper objectMapper = new ObjectMapper();

    @Mock
    private IBizDrugIncompatibilityStandardService service;

    @InjectMocks
    private BizDrugIncompatibilityStandardController controller;

    private MockMvc mockMvc;

    @BeforeEach
    void setUp()
    {
        mockMvc = MockMvcBuilders.standaloneSetup(controller)
                .setControllerAdvice(new GlobalExceptionHandler())
                .build();
        SysUser u = new SysUser();
        u.setUserId(1L);
        u.setUserName("t");
        u.setPassword("x");
        Set<String> p = new HashSet<>();
        p.add(Constants.ALL_PERMISSION);
        LoginUser lu = new LoginUser(1L, 100L, u, p);
        SecurityContextHolder.getContext().setAuthentication(
                new UsernamePasswordAuthenticationToken(lu, "", lu.getAuthorities()));
    }

    @AfterEach
    void tearDown()
    {
        SecurityContextHolder.clearContext();
        PageHelper.clearPage();
    }

    @Test
    void list() throws Exception
    {
        when(service.selectBizDrugIncompatibilityStandardList(any())).thenReturn(Collections.singletonList(listRow(1L)));
        mockMvc.perform(get("/drugIncompatibility/standard/list").param("pageNum", "1").param("pageSize", "10"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    void add() throws Exception
    {
        when(service.insertBizDrugIncompatibilityStandard(any())).thenReturn(1);
        mockMvc.perform(post("/drugIncompatibility/standard")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(body(null))))
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    void detail() throws Exception
    {
        when(service.selectBizDrugIncompatibilityStandardById(2L)).thenReturn(body(2L));
        mockMvc.perform(get("/drugIncompatibility/standard/2"))
                .andExpect(jsonPath("$.data.mainDrugName").exists())
                .andExpect(jsonPath("$.data.companions").isArray());
    }

    @Test
    void putEdit() throws Exception
    {
        when(service.updateBizDrugIncompatibilityStandard(any())).thenReturn(1);
        mockMvc.perform(put("/drugIncompatibility/standard")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(body(8L))))
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    void deleteApi() throws Exception
    {
        when(service.deleteBizDrugIncompatibilityStandardByIds(any())).thenReturn(1);
        mockMvc.perform(delete("/drugIncompatibility/standard/7")).andExpect(jsonPath("$.code").value(200));
    }

    @Test
    void syncKb() throws Exception
    {
        when(service.syncKb(11L)).thenReturn(1);
        mockMvc.perform(post("/drugIncompatibility/standard/syncKb/11")).andExpect(jsonPath("$.code").value(200));
    }

    @Test
    void removeKb() throws Exception
    {
        when(service.removeKb(13L)).thenReturn(1);
        mockMvc.perform(post("/drugIncompatibility/standard/removeKb/13")).andExpect(jsonPath("$.code").value(200));
    }

    @Test
    void serviceError() throws Exception
    {
        when(service.insertBizDrugIncompatibilityStandard(any())).thenThrow(new ServiceException("配伍药物至少一条"));
        mockMvc.perform(post("/drugIncompatibility/standard")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(body(null))))
                .andExpect(jsonPath("$.code").value(500));
    }

    private static BizDrugIncompatibilityStandard listRow(Long id)
    {
        BizDrugIncompatibilityStandard r = new BizDrugIncompatibilityStandard();
        r.setId(id);
        r.setMainDrugName("主");
        r.setKbSyncStatus(0);
        r.setCompanionCount(1);
        return r;
    }

    private static BizDrugIncompatibilityStandard body(Long id)
    {
        BizDrugIncompatibilityStandard r = new BizDrugIncompatibilityStandard();
        r.setId(id);
        r.setMainDrugName("主药");
        BizDrugIncompatibilityCompanion c = new BizDrugIncompatibilityCompanion();
        c.setCompanionDrugName("配伍甲");
        r.setCompanions(Collections.singletonList(c));
        r.setKbSyncStatus(0);
        return r;
    }
}
