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

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 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.fasterxml.jackson.databind.SerializationFeature;
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.framework.web.exception.GlobalExceptionHandler;
import com.ruoyi.web.modules.farming.TechResourceTestSamples;
import com.ruoyi.web.modules.farming.domain.BizTechResource;
import com.ruoyi.web.modules.farming.service.IBizTechResourceService;
import com.ruoyi.web.modules.farming.support.TechResourceRules;
import com.ruoyi.web.modules.farming.support.TechResourceTypeValidator;

@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT)
@DisplayName("畜牧科技资源 HTTP 接口 MockMvc")
class BizTechResourceControllerApiTest
{

    private final ObjectMapper objectMapper = new ObjectMapper()
            .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);

    @Mock
    private IBizTechResourceService bizTechResourceService;

    @Mock
    private TechResourceTypeValidator techResourceTypeValidator;

    @InjectMocks
    private BizTechResourceController 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 list() throws Exception
    {
        BizTechResource row = TechResourceTestSamples.sampleExpertDraft();
        row.setId(1L);
        when(bizTechResourceService.selectBizTechResourceList(any()))
                .thenReturn(Collections.singletonList(row));
        mockMvc.perform(get("/techService/techResource/list")
                .param("resourceType", TechResourceRules.RESOURCE_TYPE_EXPERT)
                .param("resourceName", "张")
                .param("publishStatus", "0")
                .param("pageNum", "1")
                .param("pageSize", "20"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("GET /{id}")
    void getInfo() throws Exception
    {
        when(bizTechResourceService.selectBizTechResourceById(1L))
                .thenReturn(TechResourceTestSamples.sampleExpertDraft());
        mockMvc.perform(get("/techService/techResource/1"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("POST 新增专家")
    void addExpert() throws Exception
    {
        when(bizTechResourceService.insertBizTechResource(any())).thenReturn(1);
        mockMvc.perform(post("/techService/techResource")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(TechResourceTestSamples.sampleExpertDraft())))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("POST 新增技术成果")
    void addAchievement() throws Exception
    {
        when(bizTechResourceService.insertBizTechResource(any())).thenReturn(1);
        mockMvc.perform(post("/techService/techResource")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(TechResourceTestSamples.sampleAchievementDraft())))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("PUT 修改")
    void edit() throws Exception
    {
        BizTechResource row = TechResourceTestSamples.sampleExpertDraft();
        row.setId(1L);
        when(bizTechResourceService.updateBizTechResource(any())).thenReturn(1);
        mockMvc.perform(put("/techService/techResource")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(row)))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("DELETE 删除")
    void removeByIds() throws Exception
    {
        when(bizTechResourceService.deleteBizTechResourceByIds(any(), eq("tester"))).thenReturn(1);
        mockMvc.perform(delete("/techService/techResource/1"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("POST 发布")
    void publish() throws Exception
    {
        when(bizTechResourceService.publish(1L)).thenReturn(1);
        mockMvc.perform(post("/techService/techResource/publish/1"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("POST 下架")
    void offline() throws Exception
    {
        when(bizTechResourceService.offline(1L)).thenReturn(1);
        mockMvc.perform(post("/techService/techResource/offline/1"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("POST 分配账号")
    void assignAccount() throws Exception
    {
        when(bizTechResourceService.assignAccount(eq(1L), eq("tester"))).thenReturn(1);
        mockMvc.perform(post("/techService/techResource/assignAccount/1"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }
}
