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

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.math.BigDecimal;
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.web.modules.prosperity.domain.vo.AchievementAnnualReportVo;
import com.ruoyi.web.modules.prosperity.support.AchievementReportAggregator;
import com.ruoyi.web.modules.screen.domain.vo.CommonProsperityProjectTypeDetailVo;
import com.ruoyi.web.modules.screen.domain.vo.CommonProsperityScreenDashboardVo;
import com.ruoyi.web.modules.screen.domain.vo.ProjectTypeStatVo;
import com.ruoyi.web.modules.screen.domain.vo.ScreenProjectListItemVo;
import com.ruoyi.web.modules.screen.service.ICommonProsperityScreenService;
import com.ruoyi.web.modules.screen.support.CommonProsperityScreenSupport;

/**
 * DP-GTFY-API-001～006、007～008、016、019
 */
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT)
@DisplayName("大屏共同富裕 HTTP 接口 MockMvc")
class CommonProsperityScreenControllerApiTest
{

    @Mock
    private ICommonProsperityScreenService commonProsperityScreenService;

    @InjectMocks
    private CommonProsperityScreenController controller;

    private MockMvc mockMvc;

    @BeforeEach
    void setUp()
    {
        mockMvc = MockMvcBuilders.standaloneSetup(controller).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("DP-GTFY-API-001 GET dashboard 有数据")
    void api001_dashboardWithData() throws Exception
    {
        when(commonProsperityScreenService.loadDashboard("2026")).thenReturn(sampleDashboard(true, true));
        mockMvc.perform(get("/bigScreen/commonProsperity/dashboard").param("statYear", "2026"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200))
                .andExpect(jsonPath("$.data.statYear").value(2026))
                .andExpect(jsonPath("$.data.achievement.hasData").value(true))
                .andExpect(jsonPath("$.data.hasProjectData").value(true))
                .andExpect(jsonPath("$.data.projectTypeStats.length()").value(3));
    }

    @Test
    @DisplayName("DP-GTFY-API-003 全年无成果")
    void api003_noAchievement() throws Exception
    {
        when(commonProsperityScreenService.loadDashboard("2026")).thenReturn(sampleDashboard(false, false));
        mockMvc.perform(get("/bigScreen/commonProsperity/dashboard").param("statYear", "2026"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.data.achievement.hasData").value(false))
                .andExpect(jsonPath("$.data.achievement.summary").doesNotExist());
    }

    @Test
    @DisplayName("DP-GTFY-API-004 仅项目无成果")
    void api004_projectsOnly() throws Exception
    {
        when(commonProsperityScreenService.loadDashboard("2026")).thenReturn(sampleDashboard(false, true));
        mockMvc.perform(get("/bigScreen/commonProsperity/dashboard").param("statYear", "2026"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.data.achievement.hasData").value(false))
                .andExpect(jsonPath("$.data.hasProjectData").value(true));
    }

    @Test
    @DisplayName("DP-GTFY-API-007 缺 statYear")
    void api007_missingStatYear() throws Exception
    {
        mockMvc.perform(get("/bigScreen/commonProsperity/dashboard"))
                .andExpect(status().isBadRequest());
    }

    @Test
    @DisplayName("DP-GTFY-API-009 statYear 回显")
    void api009_statYearEcho() throws Exception
    {
        CommonProsperityScreenDashboardVo vo = sampleDashboard(true, true);
        vo.setStatYear(2025);
        when(commonProsperityScreenService.loadDashboard("2025")).thenReturn(vo);
        mockMvc.perform(get("/bigScreen/commonProsperity/dashboard").param("statYear", "2025"))
                .andExpect(jsonPath("$.data.statYear").value(2025));
    }

    @Test
    @DisplayName("DP-GTFY-API-011 分类占比结构")
    void api011_typeStats() throws Exception
    {
        when(commonProsperityScreenService.loadDashboard("2026")).thenReturn(sampleDashboard(true, true));
        mockMvc.perform(get("/bigScreen/commonProsperity/dashboard").param("statYear", "2026"))
                .andExpect(jsonPath("$.data.projectTypeStats[0].projectTypeName").value("和美乡村建设项目"))
                .andExpect(jsonPath("$.data.projectTypeStats[0].ratio").exists());
    }

    @Test
    @DisplayName("DP-GTFY-API-016 GET projects 分页列表")
    void api016_projectsList() throws Exception
    {
        ScreenProjectListItemVo item = new ScreenProjectListItemVo();
        item.setId(1L);
        item.setProjectName("示范");
        item.setProjectType(1);
        item.setProjectTypeName("和美乡村建设项目");
        item.setImplYear(2026);
        when(commonProsperityScreenService.listPublishedProjects("2026")).thenReturn(Collections.singletonList(item));
        mockMvc.perform(get("/bigScreen/commonProsperity/projects").param("statYear", "2026"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200))
                .andExpect(jsonPath("$.rows[0].projectName").value("示范"));
    }

    @Test
    @DisplayName("DP-GTFY-API-019 无项目空列表")
    void api019_emptyProjects() throws Exception
    {
        when(commonProsperityScreenService.listPublishedProjects("2026")).thenReturn(Collections.emptyList());
        mockMvc.perform(get("/bigScreen/commonProsperity/projects").param("statYear", "2026"))
                .andExpect(jsonPath("$.rows").isEmpty());
    }

    @Test
    @DisplayName("GET projectTypeDetails 分类明细")
    void api_projectTypeDetails() throws Exception
    {
        CommonProsperityProjectTypeDetailVo row = new CommonProsperityProjectTypeDetailVo();
        row.setStatYear(2026);
        row.setTotalCount(10);
        row.setHeMeiVillageCount(4);
        row.setHabitatImproveCount(3);
        row.setOtherProjectCount(3);
        when(commonProsperityScreenService.listProjectTypeDetails(2026))
                .thenReturn(Collections.singletonList(row));
        mockMvc.perform(get("/bigScreen/commonProsperity/projectTypeDetails").param("statYear", "2026"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200))
                .andExpect(jsonPath("$.rows[0].statYear").value(2026))
                .andExpect(jsonPath("$.rows[0].totalCount").value(10))
                .andExpect(jsonPath("$.rows[0].heMeiVillageCount").value(4))
                .andExpect(jsonPath("$.rows[0].habitatImproveCount").value(3))
                .andExpect(jsonPath("$.rows[0].otherProjectCount").value(3));
    }

    @Test
    @DisplayName("GET projectTypeDetails 缺年份传 null 由服务不过滤年份")
    void api_projectTypeDetails_noYearFilter() throws Exception
    {
        when(commonProsperityScreenService.listProjectTypeDetails(null)).thenReturn(Collections.emptyList());
        mockMvc.perform(get("/bigScreen/commonProsperity/projectTypeDetails"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200))
                .andExpect(jsonPath("$.rows").isEmpty());
    }

    private static CommonProsperityScreenDashboardVo sampleDashboard(boolean hasAchievement, boolean hasProject)
    {
        AchievementAnnualReportVo achievement = hasAchievement
                ? AchievementReportAggregator.buildReport(2026, Collections.singletonList(sampleRow()))
                : AchievementReportAggregator.buildReport(2026, Collections.emptyList());
        CommonProsperityScreenDashboardVo vo = new CommonProsperityScreenDashboardVo();
        vo.setStatYear(2026);
        vo.setAchievement(achievement);
        vo.setHasProjectData(hasProject);
        vo.setProjectTypeStats(CommonProsperityScreenSupport.buildProjectTypeStats(
                hasProject ? Arrays.asList(sampleProject()) : Collections.emptyList()));
        vo.setAvailableYears(Arrays.asList(2026, 2025));
        return vo;
    }

    private static com.ruoyi.web.modules.prosperity.domain.BizCommonProsperityAchievement sampleRow()
    {
        com.ruoyi.web.modules.prosperity.domain.BizCommonProsperityAchievement r =
                new com.ruoyi.web.modules.prosperity.domain.BizCommonProsperityAchievement();
        r.setStatPeriod("2026-01");
        r.setCollectiveEconomyIncome(BigDecimal.ONE);
        r.setEmploymentDrivenCount(1);
        r.setNewJobPositions(1);
        r.setEnvProjectCount(1);
        r.setNewGreenArea(BigDecimal.ONE);
        r.setCulturalHeritageCount(1);
        r.setEthnicIntegrationProjectCount(1);
        r.setEthnicUnityActivityCount(1);
        r.setDigitalPlatformUsageRate(new BigDecimal("0.1"));
        r.setRegionalPublicBrandCount(1);
        r.setBrandPremiumRate(new BigDecimal("0.1"));
        return r;
    }

    private static com.ruoyi.web.modules.prosperity.domain.BizCommonProsperityProject sampleProject()
    {
        com.ruoyi.web.modules.prosperity.domain.BizCommonProsperityProject p =
                new com.ruoyi.web.modules.prosperity.domain.BizCommonProsperityProject();
        p.setProjectType(1);
        return p;
    }
}
