package com.ruoyi.web.modules.industrypolicy.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.math.BigDecimal;
import java.util.Collections;
import java.util.Date;
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.industrypolicy.domain.BizSubsidyProject;
import com.ruoyi.web.modules.industrypolicy.service.IBizSubsidyProjectService;
import com.ruoyi.web.modules.industrypolicy.support.SubsidyProjectRules;

/**
 * ZCZX-BTXM-API-001～029
 */
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT)
@DisplayName("项目与补贴-项目 HTTP 接口 MockMvc")
class BizSubsidyProjectControllerApiTest
{
    private final ObjectMapper objectMapper = new ObjectMapper();

    @Mock
    private IBizSubsidyProjectService bizSubsidyProjectService;

    @InjectMocks
    private BizSubsidyProjectController 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("ZCZX-BTXM-API-001 GET /list 分页")
    void api001_list() throws Exception
    {
        when(bizSubsidyProjectService.selectBizSubsidyProjectList(any()))
                .thenReturn(Collections.singletonList(sample(1L)));
        mockMvc.perform(get("/industryPolicy/subsidyProject/list").param("pageNum", "1").param("pageSize", "10"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200))
                .andExpect(jsonPath("$.rows").isArray());
    }

    @Test
    @DisplayName("ZCZX-BTXM-API-002 GET /list keyword")
    void api002_listKeyword() throws Exception
    {
        when(bizSubsidyProjectService.selectBizSubsidyProjectList(any())).thenReturn(Collections.emptyList());
        mockMvc.perform(get("/industryPolicy/subsidyProject/list").param("keyword", "示范"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("ZCZX-BTXM-API-004 GET /list execStatus")
    void api004_listExecStatus() throws Exception
    {
        when(bizSubsidyProjectService.selectBizSubsidyProjectList(any())).thenReturn(Collections.emptyList());
        mockMvc.perform(get("/industryPolicy/subsidyProject/list").param("execStatus", "2"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("ZCZX-BTXM-API-006 日期区间非法")
    void api006_badDateRange() throws Exception
    {
        when(bizSubsidyProjectService.selectBizSubsidyProjectList(any()))
                .thenThrow(new ServiceException("项目开始日期筛选：开始不能晚于结束"));
        mockMvc.perform(get("/industryPolicy/subsidyProject/list")
                .param("startDate", "2025-12-01")
                .param("endDate", "2025-01-01"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(500))
                .andExpect(jsonPath("$.msg").value(containsString("结束")));
    }

    @Test
    @DisplayName("ZCZX-BTXM-API-008 POST 新增成功")
    void api008_add() throws Exception
    {
        when(bizSubsidyProjectService.insertBizSubsidyProject(any())).thenReturn(1);
        mockMvc.perform(post("/industryPolicy/subsidyProject")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(sample(null))))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("ZCZX-BTXM-API-013 POST 已完成缺实际日")
    void api013_addCompletedNoActual() throws Exception
    {
        when(bizSubsidyProjectService.insertBizSubsidyProject(any()))
                .thenThrow(new ServiceException("执行状态为已完成时，实际完成日期不能为空"));
        BizSubsidyProject body = sample(null);
        body.setExecStatus(SubsidyProjectRules.EXEC_COMPLETED);
        body.setActualEndDate(null);
        mockMvc.perform(post("/industryPolicy/subsidyProject")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(body)))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(500));
    }

    @Test
    @DisplayName("ZCZX-BTXM-API-014 POST 校验失败")
    void api014_addBadName() throws Exception
    {
        when(bizSubsidyProjectService.insertBizSubsidyProject(any()))
                .thenThrow(new ServiceException("项目名称须为1～20个字符"));
        mockMvc.perform(post("/industryPolicy/subsidyProject")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(sample(null))))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(500));
    }

    @Test
    @DisplayName("ZCZX-BTXM-API-015 GET /{id} 详情")
    void api015_getDetail() throws Exception
    {
        when(bizSubsidyProjectService.selectBizSubsidyProjectById(2L)).thenReturn(sample(2L));
        mockMvc.perform(get("/industryPolicy/subsidyProject/2"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200))
                .andExpect(jsonPath("$.data.projectName").exists())
                .andExpect(jsonPath("$.data.execStatus").exists());
    }

    @Test
    @DisplayName("ZCZX-BTXM-API-017 PUT 修改成功")
    void api017_put() throws Exception
    {
        when(bizSubsidyProjectService.updateBizSubsidyProject(any())).thenReturn(1);
        mockMvc.perform(put("/industryPolicy/subsidyProject")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(sample(8L))))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("ZCZX-BTXM-API-028 PUT 已发布拒绝")
    void api028_putPublished() throws Exception
    {
        when(bizSubsidyProjectService.updateBizSubsidyProject(any()))
                .thenThrow(new ServiceException("已发布项目请先下架后再编辑"));
        mockMvc.perform(put("/industryPolicy/subsidyProject")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(sample(8L))))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(500))
                .andExpect(jsonPath("$.msg").value(containsString("下架")));
    }

    @Test
    @DisplayName("ZCZX-BTXM-API-021 DELETE 单条")
    void api021_delete() throws Exception
    {
        when(bizSubsidyProjectService.deleteBizSubsidyProjectByIds(any())).thenReturn(1);
        mockMvc.perform(delete("/industryPolicy/subsidyProject/7"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("ZCZX-BTXM-API-027 POST publish")
    void api027_publish() throws Exception
    {
        when(bizSubsidyProjectService.publish(3L)).thenReturn(1);
        mockMvc.perform(post("/industryPolicy/subsidyProject/publish/3"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("ZCZX-BTXM-API-029 POST offline")
    void api029_offline() throws Exception
    {
        when(bizSubsidyProjectService.offline(4L)).thenReturn(1);
        mockMvc.perform(post("/industryPolicy/subsidyProject/offline/4"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    private static BizSubsidyProject sample(Long id)
    {
        BizSubsidyProject r = new BizSubsidyProject();
        r.setId(id);
        r.setProjectName("示范项目");
        r.setInvestmentAmount(new BigDecimal("50000"));
        r.setProjectStartDate(new Date());
        r.setPlannedEndDate(new Date());
        r.setExecStatus(SubsidyProjectRules.EXEC_IN_PROGRESS);
        r.setPublishStatus(0);
        return r;
    }
}
