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.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.LivestockResourceActivityTrendVo;
import com.ruoyi.web.modules.screen.domain.vo.LivestockResourceCategoryShareVo;
import com.ruoyi.web.modules.screen.domain.vo.LivestockResourceDailyPointVo;
import com.ruoyi.web.modules.screen.domain.vo.LivestockResourceDashboardVo;
import com.ruoyi.web.modules.screen.domain.vo.LivestockResourceHourlyHeatVo;
import com.ruoyi.web.modules.screen.domain.vo.LivestockResourceHourlyPointVo;
import com.ruoyi.web.modules.screen.domain.vo.LivestockResourceOverviewVo;
import com.ruoyi.web.modules.screen.domain.vo.LivestockResourceUserStructureVo;
import com.ruoyi.web.modules.screen.service.ILivestockResourceScreenService;

/**
 * DP-XM-API-001～024
 */
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT)
@DisplayName("大屏畜牧资源 HTTP 接口 MockMvc")
class LivestockResourceScreenControllerApiTest
{
    @Mock
    private ILivestockResourceScreenService livestockResourceScreenService;

    @InjectMocks
    private LivestockResourceScreenController controller;

    private MockMvc mockMvc;

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

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

    @Test
    @DisplayName("DP-XM-API-001 GET dashboard 有数据")
    void api001_dashboard() throws Exception
    {
        when(livestockResourceScreenService.loadDashboard("2026")).thenReturn(sampleDashboard());
        mockMvc.perform(get("/bigScreen/livestockResource/dashboard").param("statYear", "2026"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200))
                .andExpect(jsonPath("$.data.statYear").value(2026))
                .andExpect(jsonPath("$.data.overview.totalUsers").value(120))
                .andExpect(jsonPath("$.data.activityTrend.dailySeries.length()").value(7))
                .andExpect(jsonPath("$.data.hourlyHeat.hourlySeries.length()").value(24));
    }

    @Test
    @DisplayName("DP-XM-API-024 statYear 回显")
    void api024_statYearEcho() throws Exception
    {
        LivestockResourceDashboardVo vo = sampleDashboard();
        vo.setStatYear(2025);
        when(livestockResourceScreenService.loadDashboard("2025")).thenReturn(vo);
        mockMvc.perform(get("/bigScreen/livestockResource/dashboard").param("statYear", "2025"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.data.statYear").value(2025));
    }

    private static LivestockResourceDashboardVo sampleDashboard()
    {
        LivestockResourceDashboardVo vo = new LivestockResourceDashboardVo();
        vo.setStatYear(2026);
        vo.setStatDate("2026-05-20");
        vo.setStatDateTime("2026-05-20 15:30:00");
        vo.setAvailableYears(Arrays.asList(2026, 2025));

        LivestockResourceOverviewVo overview = new LivestockResourceOverviewVo();
        overview.setTotalUsers(120);
        overview.setTodayActiveUsers(8);
        overview.setTodayNewUsers(2);
        overview.setTotalSessions(350);
        overview.setTodaySessions(5);
        overview.setTotalQuestionCount(980);
        overview.setTodayQuestionCount(12);
        overview.setAvgResponseSeconds(new BigDecimal("3.2"));
        vo.setOverview(overview);

        LivestockResourceDailyPointVo day = new LivestockResourceDailyPointVo();
        day.setDate("2026-05-20");
        day.setSessionCount(3);
        day.setQuestionCount(10);
        LivestockResourceActivityTrendVo trend = new LivestockResourceActivityTrendVo();
        trend.setDailySeries(Collections.nCopies(7, day));
        vo.setActivityTrend(trend);

        LivestockResourceUserStructureVo user = new LivestockResourceUserStructureVo();
        user.setNewUserCount(3);
        user.setOldUserCount(2);
        vo.setUserStructure(user);

        LivestockResourceCategoryShareVo share = new LivestockResourceCategoryShareVo();
        share.setTotalAskerMessages(100);
        share.setItems(Collections.emptyList());
        vo.setCategoryShare(share);
        vo.setModelCallAnalysis(Collections.emptyList());
        vo.setHotTopics(Collections.emptyList());
        vo.setTopKeywords(Collections.emptyList());
        vo.setSessionReplyDistribution(Collections.emptyList());

        LivestockResourceHourlyPointVo hour = new LivestockResourceHourlyPointVo();
        hour.setBucketStart("14:00");
        hour.setSessionCount(1);
        hour.setQuestionCount(2);
        LivestockResourceHourlyHeatVo heat = new LivestockResourceHourlyHeatVo();
        heat.setWindowEnd("2026-05-20 15:30:00");
        heat.setHourlySeries(Collections.nCopies(24, hour));
        vo.setHourlyHeat(heat);
        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);
    }
}
