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

import static org.hamcrest.Matchers.containsString;
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.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.common.exception.ServiceException;
import com.ruoyi.framework.web.exception.GlobalExceptionHandler;
import com.ruoyi.web.modules.innovation.TechProjectGuideTestSamples;
import com.ruoyi.web.modules.innovation.domain.BizTechProjectGuide;
import com.ruoyi.web.modules.innovation.service.IBizTechProjectGuideService;

/**
 * KJXM-API-001～025（MockMvc + Mock Service）
 */
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT)
@DisplayName("科技项目指南 HTTP 接口 MockMvc")
class BizTechProjectGuideControllerApiTest
{

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

    @Mock
    private IBizTechProjectGuideService bizTechProjectGuideService;

    @InjectMocks
    private BizTechProjectGuideController 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("KJXM-API-001 GET /list 分页")
    void api001_list() throws Exception
    {
        when(bizTechProjectGuideService.selectBizTechProjectGuideList(any()))
                .thenReturn(Collections.singletonList(sample(1L, 0)));
        mockMvc.perform(get("/innovationPlatform/techProjectGuide/list").param("pageNum", "1").param("pageSize", "20"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200))
                .andExpect(jsonPath("$.rows").isArray());
    }

    @Test
    @DisplayName("KJXM-API-002 GET /list 项目名称模糊")
    void api002_listProjectName() throws Exception
    {
        when(bizTechProjectGuideService.selectBizTechProjectGuideList(any())).thenReturn(Collections.emptyList());
        mockMvc.perform(get("/innovationPlatform/techProjectGuide/list").param("projectName", "示范"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("KJXM-API-003 GET /list 项目类型")
    void api003_listProjectType() throws Exception
    {
        when(bizTechProjectGuideService.selectBizTechProjectGuideList(any())).thenReturn(Collections.emptyList());
        mockMvc.perform(get("/innovationPlatform/techProjectGuide/list").param("projectType", "002002"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("KJXM-API-004 GET /list 发布状态")
    void api004_listPublishStatus() throws Exception
    {
        when(bizTechProjectGuideService.selectBizTechProjectGuideList(any()))
                .thenReturn(Collections.singletonList(sample(2L, 0)));
        mockMvc.perform(get("/innovationPlatform/techProjectGuide/list").param("publishStatus", "0"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("KJXM-API-005 POST 仅保存未发布")
    void api005_add() throws Exception
    {
        when(bizTechProjectGuideService.insertBizTechProjectGuide(any())).thenReturn(1);
        mockMvc.perform(post("/innovationPlatform/techProjectGuide")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(TechProjectGuideTestSamples.sampleDraft())))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("KJXM-API-006 POST 保存并发布")
    void api006_addSaveAndPublish() throws Exception
    {
        when(bizTechProjectGuideService.insertBizTechProjectGuide(any())).thenReturn(1);
        BizTechProjectGuide body = TechProjectGuideTestSamples.sampleDraft();
        body.setSaveAndPublish(true);
        mockMvc.perform(post("/innovationPlatform/techProjectGuide")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(body)))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("KJXM-API-007 POST 必填缺失")
    void api007_addMissingName() throws Exception
    {
        when(bizTechProjectGuideService.insertBizTechProjectGuide(any()))
                .thenThrow(new ServiceException("项目名称须为1～20个字符"));
        BizTechProjectGuide body = TechProjectGuideTestSamples.sampleDraft();
        body.setProjectName("");
        mockMvc.perform(post("/innovationPlatform/techProjectGuide")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(body)))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(500));
    }

    @Test
    @DisplayName("KJXM-API-008 POST 截止早于开始")
    void api008_addBadDates() throws Exception
    {
        when(bizTechProjectGuideService.insertBizTechProjectGuide(any()))
                .thenThrow(new ServiceException("申报截止日期不能早于开始日期"));
        mockMvc.perform(post("/innovationPlatform/techProjectGuide")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(TechProjectGuideTestSamples.sampleDraft())))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(500))
                .andExpect(jsonPath("$.msg").value(containsString("截止日期")));
    }

    @Test
    @DisplayName("KJXM-API-009 POST 非法项目类型")
    void api009_addBadType() throws Exception
    {
        when(bizTechProjectGuideService.insertBizTechProjectGuide(any()))
                .thenThrow(new ServiceException("项目类型无效，请选择资讯类别中的类型"));
        BizTechProjectGuide body = TechProjectGuideTestSamples.sampleDraft();
        body.setProjectType("999999");
        mockMvc.perform(post("/innovationPlatform/techProjectGuide")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(body)))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(500));
    }

    @Test
    @DisplayName("KJXM-API-010 POST 手机号非法")
    void api010_addBadPhone() throws Exception
    {
        when(bizTechProjectGuideService.insertBizTechProjectGuide(any()))
                .thenThrow(new ServiceException("联系方式须为合法大陆手机号"));
        BizTechProjectGuide body = TechProjectGuideTestSamples.sampleDraft();
        body.setContactPhone("123");
        mockMvc.perform(post("/innovationPlatform/techProjectGuide")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(body)))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(500))
                .andExpect(jsonPath("$.msg").value(containsString("手机号")));
    }

    @Test
    @DisplayName("KJXM-API-011 GET /{id} 详情")
    void api011_getDetail() throws Exception
    {
        when(bizTechProjectGuideService.selectBizTechProjectGuideById(2L)).thenReturn(sample(2L, 1));
        mockMvc.perform(get("/innovationPlatform/techProjectGuide/2"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200))
                .andExpect(jsonPath("$.data.projectName").exists())
                .andExpect(jsonPath("$.data.publishStatus").value(1));
    }

    @Test
    @DisplayName("KJXM-API-013 PUT 未发布修改")
    void api013_put() throws Exception
    {
        when(bizTechProjectGuideService.updateBizTechProjectGuide(any())).thenReturn(1);
        BizTechProjectGuide body = TechProjectGuideTestSamples.sampleDraft();
        body.setId(1L);
        body.setProjectIntro("更新后的简介");
        mockMvc.perform(put("/innovationPlatform/techProjectGuide")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(body)))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("KJXM-API-014 PUT 已发布拒绝")
    void api014_putPublished() throws Exception
    {
        when(bizTechProjectGuideService.updateBizTechProjectGuide(any()))
                .thenThrow(new ServiceException("已发布指南请先下架后再编辑"));
        BizTechProjectGuide body = TechProjectGuideTestSamples.sampleDraft();
        body.setId(9L);
        mockMvc.perform(put("/innovationPlatform/techProjectGuide")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(body)))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(500))
                .andExpect(jsonPath("$.msg").value(containsString("下架")));
    }

    @Test
    @DisplayName("KJXM-API-015 DELETE 未发布")
    void api015_delete() throws Exception
    {
        when(bizTechProjectGuideService.deleteBizTechProjectGuideByIds(any())).thenReturn(1);
        mockMvc.perform(delete("/innovationPlatform/techProjectGuide/3"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("KJXM-API-016 DELETE 已发布拒绝")
    void api016_deletePublished() throws Exception
    {
        when(bizTechProjectGuideService.deleteBizTechProjectGuideByIds(any()))
                .thenThrow(new ServiceException("已发布的指南不可删除，请先下架"));
        mockMvc.perform(delete("/innovationPlatform/techProjectGuide/9"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(500));
    }

    @Test
    @DisplayName("KJXM-API-017 POST publish")
    void api017_publish() throws Exception
    {
        when(bizTechProjectGuideService.publish(5L)).thenReturn(1);
        mockMvc.perform(post("/innovationPlatform/techProjectGuide/publish/5"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("KJXM-API-018 POST 重复发布")
    void api018_publishAgain() throws Exception
    {
        when(bizTechProjectGuideService.publish(6L))
                .thenThrow(new ServiceException("仅「未发布」可发布"));
        mockMvc.perform(post("/innovationPlatform/techProjectGuide/publish/6"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(500));
    }

    @Test
    @DisplayName("KJXM-API-019 POST offline")
    void api019_offline() throws Exception
    {
        when(bizTechProjectGuideService.offline(7L)).thenReturn(1);
        mockMvc.perform(post("/innovationPlatform/techProjectGuide/offline/7"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("KJXM-API-020 POST 未发布拒绝下架")
    void api020_offlineDraft() throws Exception
    {
        when(bizTechProjectGuideService.offline(8L))
                .thenThrow(new ServiceException("仅「已发布」可下架"));
        mockMvc.perform(post("/innovationPlatform/techProjectGuide/offline/8"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(500));
    }

    @Test
    @DisplayName("KJXM-API-025 失败可区分")
    void api025_errorMessage() throws Exception
    {
        when(bizTechProjectGuideService.updateBizTechProjectGuide(any()))
                .thenThrow(new ServiceException("已发布指南请先下架后再编辑"));
        BizTechProjectGuide body = TechProjectGuideTestSamples.sampleDraft();
        body.setId(1L);
        mockMvc.perform(put("/innovationPlatform/techProjectGuide")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(body)))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(500))
                .andExpect(jsonPath("$.msg").value(containsString("下架")));
    }

    private static BizTechProjectGuide sample(Long id, int publishStatus)
    {
        BizTechProjectGuide row = TechProjectGuideTestSamples.sampleDraft();
        row.setId(id);
        row.setPublishStatus(publishStatus);
        return row;
    }
}
