package com.ruoyi.web.modules.prosperity.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.Calendar;
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.prosperity.domain.BizCommonProsperityProject;
import com.ruoyi.web.modules.prosperity.domain.BizCommonProsperityProjectOpImage;
import com.ruoyi.web.modules.prosperity.service.IBizCommonProsperityProjectService;

/**
 * GTFY-XM-API-001～031、035（MockMvc + Mock Service）
 */
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT)
@DisplayName("共同富裕项目 HTTP 接口 MockMvc")
class BizCommonProsperityProjectControllerApiTest
{

    private final ObjectMapper objectMapper = new ObjectMapper();

    @Mock
    private IBizCommonProsperityProjectService bizCommonProsperityProjectService;

    @InjectMocks
    private BizCommonProsperityProjectController 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("GTFY-XM-API-001 GET /list 分页")
    void api001_list() throws Exception
    {
        when(bizCommonProsperityProjectService.selectBizCommonProsperityProjectList(any()))
                .thenReturn(Collections.singletonList(sample(1L)));
        mockMvc.perform(get("/commonProsperity/project/list").param("pageNum", "1").param("pageSize", "20"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200))
                .andExpect(jsonPath("$.rows").isArray())
                .andExpect(jsonPath("$.rows.length()").value(1));
    }

    @Test
    @DisplayName("GTFY-XM-API-002 GET /list projectName 模糊")
    void api002_listProjectName() throws Exception
    {
        when(bizCommonProsperityProjectService.selectBizCommonProsperityProjectList(any()))
                .thenReturn(Collections.emptyList());
        mockMvc.perform(get("/commonProsperity/project/list").param("projectName", "合作"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("GTFY-XM-API-003 GET /list projectType")
    void api003_listProjectType() throws Exception
    {
        when(bizCommonProsperityProjectService.selectBizCommonProsperityProjectList(any()))
                .thenReturn(Collections.emptyList());
        mockMvc.perform(get("/commonProsperity/project/list").param("projectType", "2"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("GTFY-XM-API-004 GET /list publishStatus")
    void api004_listPublishStatus() throws Exception
    {
        when(bizCommonProsperityProjectService.selectBizCommonProsperityProjectList(any()))
                .thenReturn(Collections.emptyList());
        mockMvc.perform(get("/commonProsperity/project/list").param("publishStatus", "0"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("GTFY-XM-API-005 GET /list 组合查询")
    void api005_listCombo() throws Exception
    {
        when(bizCommonProsperityProjectService.selectBizCommonProsperityProjectList(any()))
                .thenReturn(Collections.emptyList());
        mockMvc.perform(get("/commonProsperity/project/list")
                .param("projectName", "共富")
                .param("projectType", "1")
                .param("publishStatus", "1"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("GTFY-XM-API-006 GET /list App 仅已发布")
    void api006_listPublishedOnly() throws Exception
    {
        when(bizCommonProsperityProjectService.selectBizCommonProsperityProjectList(any()))
                .thenReturn(Collections.emptyList());
        mockMvc.perform(get("/commonProsperity/project/list").param("publishStatus", "1"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("GTFY-XM-API-007 POST 新增成功")
    void api007_add() throws Exception
    {
        when(bizCommonProsperityProjectService.insertBizCommonProsperityProject(any())).thenReturn(1);
        mockMvc.perform(post("/commonProsperity/project")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(sample(null))))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("GTFY-XM-API-009 POST 名称非法")
    void api009_addBadName() throws Exception
    {
        when(bizCommonProsperityProjectService.insertBizCommonProsperityProject(any()))
                .thenThrow(new ServiceException("项目名称须为1～64个字符"));
        BizCommonProsperityProject body = sample(null);
        body.setProjectName("");
        mockMvc.perform(post("/commonProsperity/project")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(body)))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(500));
    }

    @Test
    @DisplayName("GTFY-XM-API-010 POST 类型非法")
    void api010_addBadType() throws Exception
    {
        when(bizCommonProsperityProjectService.insertBizCommonProsperityProject(any()))
                .thenThrow(new ServiceException("项目类型须为1～3"));
        BizCommonProsperityProject body = sample(null);
        body.setProjectType(9);
        mockMvc.perform(post("/commonProsperity/project")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(body)))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(500));
    }

    @Test
    @DisplayName("GTFY-XM-API-014 GET /{id} 详情")
    void api014_getDetail() throws Exception
    {
        BizCommonProsperityProject detail = sample(2L);
        detail.setOperationImages(Collections.singletonList(sampleImage(1)));
        when(bizCommonProsperityProjectService.selectBizCommonProsperityProjectById(2L)).thenReturn(detail);
        mockMvc.perform(get("/commonProsperity/project/2"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200))
                .andExpect(jsonPath("$.data.projectName").exists())
                .andExpect(jsonPath("$.data.operationImages").isArray());
    }

    @Test
    @DisplayName("GTFY-XM-API-015 GET /{id} 不存在")
    void api015_getMissing() throws Exception
    {
        when(bizCommonProsperityProjectService.selectBizCommonProsperityProjectById(999999L)).thenReturn(null);
        mockMvc.perform(get("/commonProsperity/project/999999"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("GTFY-XM-API-019 PUT 修改成功")
    void api019_put() throws Exception
    {
        when(bizCommonProsperityProjectService.updateBizCommonProsperityProject(any())).thenReturn(1);
        mockMvc.perform(put("/commonProsperity/project")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(sample(8L))))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("GTFY-XM-API-020 PUT 已发布拒绝")
    void api020_putPublished() throws Exception
    {
        when(bizCommonProsperityProjectService.updateBizCommonProsperityProject(any()))
                .thenThrow(new ServiceException("已发布项目请先下架后再编辑"));
        mockMvc.perform(put("/commonProsperity/project")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(sample(8L))))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(500))
                .andExpect(jsonPath("$.msg").value(containsString("下架")));
    }

    @Test
    @DisplayName("GTFY-XM-API-024 DELETE 未发布")
    void api024_delete() throws Exception
    {
        when(bizCommonProsperityProjectService.deleteBizCommonProsperityProjectByIds(any())).thenReturn(1);
        mockMvc.perform(delete("/commonProsperity/project/7"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("GTFY-XM-API-025 DELETE 已发布拒绝")
    void api025_deletePublished() throws Exception
    {
        when(bizCommonProsperityProjectService.deleteBizCommonProsperityProjectByIds(any()))
                .thenThrow(new ServiceException("已发布的项目不可删除，请先下架"));
        mockMvc.perform(delete("/commonProsperity/project/7"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(500));
    }

    @Test
    @DisplayName("GTFY-XM-API-027 POST publish 成功")
    void api027_publish() throws Exception
    {
        when(bizCommonProsperityProjectService.publish(3L)).thenReturn(1);
        mockMvc.perform(post("/commonProsperity/project/publish/3"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("GTFY-XM-API-028 POST publish 重复")
    void api028_publishAgain() throws Exception
    {
        when(bizCommonProsperityProjectService.publish(3L))
                .thenThrow(new ServiceException("仅「未发布」可发布"));
        mockMvc.perform(post("/commonProsperity/project/publish/3"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(500));
    }

    @Test
    @DisplayName("GTFY-XM-API-030 POST offline 成功")
    void api030_offline() throws Exception
    {
        when(bizCommonProsperityProjectService.offline(4L)).thenReturn(1);
        mockMvc.perform(post("/commonProsperity/project/offline/4"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("GTFY-XM-API-031 POST offline 未发布拒绝")
    void api031_offlineDraft() throws Exception
    {
        when(bizCommonProsperityProjectService.offline(5L))
                .thenThrow(new ServiceException("仅「已发布」可下架"));
        mockMvc.perform(post("/commonProsperity/project/offline/5"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(500));
    }

    @Test
    @DisplayName("GTFY-XM-API-035 失败可读 msg")
    void api035_errorMsg() throws Exception
    {
        when(bizCommonProsperityProjectService.insertBizCommonProsperityProject(any()))
                .thenThrow(new ServiceException("运营图片至少需要1张，最多3张"));
        BizCommonProsperityProject body = sample(null);
        body.setOperationImages(Collections.emptyList());
        mockMvc.perform(post("/commonProsperity/project")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(body)))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(500))
                .andExpect(jsonPath("$.msg").value(containsString("运营图片")));
    }

    private static BizCommonProsperityProject sample(Long id)
    {
        BizCommonProsperityProject r = new BizCommonProsperityProject();
        r.setId(id);
        r.setProjectName("共富项目");
        r.setProjectType(1);
        r.setIntroduction("简介");
        r.setProjectContent("建设规模及内容描述");
        r.setInvestmentAmount(new java.math.BigDecimal("100"));
        r.setImplYear(Calendar.getInstance().get(Calendar.YEAR));
        r.setImplStatus("实施中");
        r.setPublishStatus(0);
        r.setOperationImages(Collections.singletonList(sampleImage(1)));
        return r;
    }

    private static BizCommonProsperityProjectOpImage sampleImage(int sortOrder)
    {
        BizCommonProsperityProjectOpImage img = new BizCommonProsperityProjectOpImage();
        img.setFileUrl("http://img");
        img.setFilePath(Constants.RESOURCE_PREFIX + "/upload/img.jpg");
        img.setSortOrder(sortOrder);
        return img;
    }
}
