package com.ruoyi.web.modules.technology.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.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import java.util.Arrays;
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.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.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.category.domain.vo.InformationCategoryItemVo;
import com.ruoyi.web.modules.technology.OnlineTrainingCourseTestSamples;
import com.ruoyi.web.modules.technology.domain.OnlineTrainingCourseDetailVo;
import com.ruoyi.web.modules.technology.domain.OnlineTrainingCourseListVo;
import com.ruoyi.web.modules.technology.service.IBizOnlineTrainingCourseService;
import com.ruoyi.web.modules.technology.support.OnlineTrainingCourseRules;

@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT)
@DisplayName("网上培训课程 HTTP 接口 MockMvc")
class BizOnlineTrainingCourseControllerApiTest
{
    @Mock
    private IBizOnlineTrainingCourseService onlineTrainingCourseService;

    @InjectMocks
    private BizOnlineTrainingCourseController 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
    {
        OnlineTrainingCourseListVo row = new OnlineTrainingCourseListVo();
        row.setId(101L);
        row.setCourseTitle("基础养殖入门");
        row.setCourseTopic("005001");
        row.setVideoFileName("course.mp4");
        when(onlineTrainingCourseService.selectOnlineTrainingCourseList(any()))
                .thenReturn(Collections.singletonList(row));
        mockMvc.perform(get("/techService/onlineTrainingCourse/list")
                .param("courseTitle", "养殖")
                .param("courseTopic", "005001"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("GET /courseTopics")
    void courseTopics() throws Exception
    {
        when(onlineTrainingCourseService.selectCourseTopics())
                .thenReturn(Arrays.asList(
                        new InformationCategoryItemVo("005001", "基础养殖"),
                        new InformationCategoryItemVo("005002", "疫病防治")));
        mockMvc.perform(get("/techService/onlineTrainingCourse/courseTopics"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200))
                .andExpect(jsonPath("$.data[0].code").value("005001"))
                .andExpect(jsonPath("$.data[0].name").value("基础养殖"));
    }

    @Test
    @DisplayName("GET /{id}")
    void getInfo() throws Exception
    {
        when(onlineTrainingCourseService.selectOnlineTrainingCourseById(101L))
                .thenReturn(toDetailVo());
        mockMvc.perform(get("/techService/onlineTrainingCourse/101"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200))
                .andExpect(jsonPath("$.data.courseTitle").value("基础养殖入门"))
                .andExpect(jsonPath("$.data.videoFileUrl").value(OnlineTrainingCourseTestSamples.VIDEO_URL));
    }

    @Test
    @DisplayName("GET /{id} 已下线")
    void getInfoOffline() throws Exception
    {
        when(onlineTrainingCourseService.selectOnlineTrainingCourseById(eq(9L)))
                .thenThrow(new ServiceException(OnlineTrainingCourseRules.NOT_FOUND_MSG));
        mockMvc.perform(get("/techService/onlineTrainingCourse/9"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(500));
    }

    private static OnlineTrainingCourseDetailVo toDetailVo()
    {
        OnlineTrainingCourseDetailVo vo = new OnlineTrainingCourseDetailVo();
        vo.setId(101L);
        vo.setCourseTitle("基础养殖入门");
        vo.setCourseIntro("课程简介正文");
        vo.setCourseTopic("005001");
        vo.setVideoFileUrl(OnlineTrainingCourseTestSamples.VIDEO_URL);
        vo.setVideoFilePath(OnlineTrainingCourseTestSamples.VIDEO_PATH);
        vo.setVideoFileName("course.mp4");
        return vo;
    }
}
