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

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.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
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.screen.domain.vo.HomeScreenAgriClassroomVo;
import com.ruoyi.web.modules.screen.domain.vo.HomeScreenAppointmentVo;
import com.ruoyi.web.modules.screen.domain.vo.HomeScreenDashboardVo;
import com.ruoyi.web.modules.screen.domain.vo.HomeScreenIndustryOverviewVo;
import com.ruoyi.web.modules.screen.domain.vo.HomeScreenInventoryChangeVo;
import com.ruoyi.web.modules.screen.domain.vo.HomeScreenInventoryMonthVo;
import com.ruoyi.web.modules.screen.domain.vo.HomeScreenSubsidyVo;
import com.ruoyi.web.modules.screen.domain.vo.HomeScreenTrainingTrendVo;
import com.ruoyi.web.modules.screen.service.IHomeScreenService;

/**
 * DP-SY-API-001～020
 */
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT)
@DisplayName("大屏首页 HTTP 接口 MockMvc")
class HomeScreenControllerApiTest
{

    @Mock
    private IHomeScreenService homeScreenService;

    @InjectMocks
    private HomeScreenController controller;

    private MockMvc mockMvc;

    @BeforeEach
    void setUp()
    {
        mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
        loginAsAllPermissions();
    }

    @AfterEach
    void tearDown()
    {
        SecurityContextHolder.clearContext();
        PageHelper.clearPage();
    }

    @Test
    @DisplayName("DP-SY-API-001 GET dashboard 有数据")
    void api001_dashboard() throws Exception
    {
        when(homeScreenService.loadDashboard("2026")).thenReturn(sampleDashboard());
        mockMvc.perform(get("/bigScreen/home/dashboard").param("statYear", "2026"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200))
                .andExpect(jsonPath("$.data.statYear").value(2026))
                .andExpect(jsonPath("$.data.industryOverview.inventoryTotal").value(10))
                .andExpect(jsonPath("$.data.inventoryChange.monthlyTrend.length()").value(12));
    }

    @Test
    @DisplayName("DP-SY-API-019 statYear 回显")
    void api019_statYearEcho() throws Exception
    {
        HomeScreenDashboardVo vo = sampleDashboard();
        vo.setStatYear(2025);
        when(homeScreenService.loadDashboard("2025")).thenReturn(vo);
        mockMvc.perform(get("/bigScreen/home/dashboard").param("statYear", "2025"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.data.statYear").value(2025));
    }

    @Test
    @DisplayName("DP-SY-API-023 GET standards 分页")
    void api023_standards() throws Exception
    {
        when(homeScreenService.listStandards(eq("2026"), eq("BREEDING_MGMT")))
                .thenReturn(Collections.emptyList());
        mockMvc.perform(get("/bigScreen/home/standards")
                        .param("statYear", "2026")
                        .param("category", "BREEDING_MGMT")
                        .param("pageNum", "1")
                        .param("pageSize", "10"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("DP-SY-API-038 GET townMapMarkers 地图标注")
    void api024_townMapMarkers() throws Exception
    {
        when(homeScreenService.loadTownMapMarkers()).thenReturn(sampleTownMap());
        mockMvc.perform(get("/bigScreen/home/townMapMarkers"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200))
                .andExpect(jsonPath("$.data.herdStatYear").value(2025))
                .andExpect(jsonPath("$.data.outboundStatYear").value(2026))
                .andExpect(jsonPath("$.data.markers[0].townDeptId").value(101))
                .andExpect(jsonPath("$.data.markers[0].townName").value("巴青乡"))
                .andExpect(jsonPath("$.data.markers[0].yakInventoryCount").value(21587))
                .andExpect(jsonPath("$.data.markers[0].yakOutboundCount").value(1523));
    }

    private static com.ruoyi.web.modules.screen.domain.vo.HomeScreenTownMapVo sampleTownMap()
    {
        com.ruoyi.web.modules.screen.domain.vo.HomeScreenTownMapMarkerVo marker =
                new com.ruoyi.web.modules.screen.domain.vo.HomeScreenTownMapMarkerVo();
        marker.setTownDeptId(101L);
        marker.setTownName("巴青乡");
        marker.setYakInventoryCount(21587);
        marker.setYakOutboundCount(1523);
        com.ruoyi.web.modules.screen.domain.vo.HomeScreenTownMapVo vo =
                new com.ruoyi.web.modules.screen.domain.vo.HomeScreenTownMapVo();
        vo.setHerdStatYear(2025);
        vo.setOutboundStatYear(2026);
        vo.setMarkers(Collections.singletonList(marker));
        return vo;
    }

    private static HomeScreenDashboardVo sampleDashboard()
    {
        HomeScreenDashboardVo vo = new HomeScreenDashboardVo();
        vo.setStatYear(2026);
        vo.setStatDate("2026-05-20");
        vo.setAvailableYears(Arrays.asList(2026, 2025));

        HomeScreenIndustryOverviewVo overview = new HomeScreenIndustryOverviewVo();
        overview.setInventoryTotal(10);
        overview.setAnnualOutbound(2);
        overview.setPastureCount(1);
        overview.setGrasslandCount(5);
        overview.setGrasslandAreaMu(new BigDecimal("100.00"));
        overview.setSupplierCount(1);
        overview.setDistributorCount(1);
        overview.setTradeMarketCount(1);
        vo.setIndustryOverview(overview);

        HomeScreenInventoryChangeVo inv = new HomeScreenInventoryChangeVo();
        inv.setBullCount(4);
        inv.setCowCount(5);
        inv.setUnknownGenderCount(1);
        List<HomeScreenInventoryMonthVo> trend = new ArrayList<>();
        for (int m = 1; m <= 12; m++)
        {
            HomeScreenInventoryMonthVo p = new HomeScreenInventoryMonthVo();
            p.setMonth(m);
            p.setBullCount(1);
            p.setCowCount(1);
            trend.add(p);
        }
        inv.setMonthlyTrend(trend);
        vo.setInventoryChange(inv);

        vo.setAgeStructure(new ArrayList<>());
        vo.setOutboundMonthly(new ArrayList<>());
        vo.setGrassland(null);
        vo.setAppointment(new HomeScreenAppointmentVo());
        HomeScreenSubsidyVo subsidy = new HomeScreenSubsidyVo();
        subsidy.setHasSubsidyData(false);
        vo.setSubsidy(subsidy);
        HomeScreenAgriClassroomVo agri = new HomeScreenAgriClassroomVo();
        agri.setHasAgriData(true);
        vo.setAgriClassroom(agri);
        HomeScreenTrainingTrendVo training = new HomeScreenTrainingTrendVo();
        training.setHasTrainingData(true);
        vo.setTrainingTrend(training);
        return vo;
    }

    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);
    }
}
