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.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.screen.domain.vo.LivestockResourceDashboardVo;
import com.ruoyi.web.modules.screen.domain.vo.LivestockResourceOverviewVo;
import com.ruoyi.web.modules.screen.domain.vo.LivestockResourceProductOutputListItemVo;
import com.ruoyi.web.modules.screen.domain.vo.LivestockResourceThreeAssetsProblemListItemVo;
import com.ruoyi.web.modules.screen.domain.vo.LivestockResourceVaccinationListItemVo;
import com.ruoyi.web.modules.screen.domain.vo.LivestockResourceVetCountListItemVo;
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();
        PageHelper.clearPage();
    }

    @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.operatingFixedAssets").value(100.5))
                .andExpect(jsonPath("$.data.overview.immunityRate").value(90.0))
                .andExpect(jsonPath("$.data.overview.vetCount").value(15));
    }

    @Test
    @DisplayName("DP-XM-API-025 GET threeAssetsProblemReports 明细分页")
    void api025_threeAssetsProblemReports() throws Exception
    {
        LivestockResourceThreeAssetsProblemListItemVo item = new LivestockResourceThreeAssetsProblemListItemVo();
        item.setTownName("巴青镇");
        item.setVillageName("某村");
        item.setProblemLevel("general");
        item.setProblemLevelName("一般");
        item.setProblemDetail("描述");
        item.setHandleResult("处理中");
        when(livestockResourceScreenService.listThreeAssetsProblemReports(eq(2026), eq(101L), eq(201L)))
                .thenReturn(Collections.singletonList(item));
        mockMvc.perform(get("/bigScreen/livestockResource/threeAssetsProblemReports")
                        .param("statYear", "2026")
                        .param("townDeptId", "101")
                        .param("villageDeptId", "201")
                        .param("pageNum", "1")
                        .param("pageSize", "10"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200))
                .andExpect(jsonPath("$.rows[0].townName").value("巴青镇"))
                .andExpect(jsonPath("$.rows[0].problemLevelName").value("一般"))
                .andExpect(jsonPath("$.rows[0].problemDetail").value("描述"));
    }

    @Test
    @DisplayName("DP-XM-API-026 GET productOutputs 明细分页")
    void api026_productOutputs() throws Exception
    {
        LivestockResourceProductOutputListItemVo item = new LivestockResourceProductOutputListItemVo();
        item.setStatYear(2026);
        item.setStatMonth(7);
        item.setTownName("巴青镇");
        item.setVillageName("某村");
        item.setMeatOutput(new BigDecimal("1.2000"));
        item.setMilkOutput(new BigDecimal("3.4000"));
        when(livestockResourceScreenService.listProductOutputs(eq(2026), eq(7), eq(101L), eq(201L)))
                .thenReturn(Collections.singletonList(item));
        mockMvc.perform(get("/bigScreen/livestockResource/productOutputs")
                        .param("statYear", "2026")
                        .param("statMonth", "7")
                        .param("townDeptId", "101")
                        .param("villageDeptId", "201")
                        .param("pageNum", "1")
                        .param("pageSize", "10"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200))
                .andExpect(jsonPath("$.rows[0].statYear").value(2026))
                .andExpect(jsonPath("$.rows[0].statMonth").value(7))
                .andExpect(jsonPath("$.rows[0].townName").value("巴青镇"))
                .andExpect(jsonPath("$.rows[0].meatOutput").value(1.2))
                .andExpect(jsonPath("$.rows[0].milkOutput").value(3.4));
    }

    @Test
    @DisplayName("DP-XM-API-027 GET vaccinationData 明细分页")
    void api027_vaccinationData() throws Exception
    {
        LivestockResourceVaccinationListItemVo item = new LivestockResourceVaccinationListItemVo();
        item.setStatYear(2026);
        item.setStatMonth(7);
        item.setTownName("巴青镇");
        item.setVillageName("某村");
        item.setShouldVaccinateCount(100);
        item.setActualVaccinateCount(80);
        item.setImmunityRate(new BigDecimal("80.00"));
        when(livestockResourceScreenService.listVaccinationData(eq(2026), eq(7), eq(101L), eq(201L)))
                .thenReturn(Collections.singletonList(item));
        mockMvc.perform(get("/bigScreen/livestockResource/vaccinationData")
                        .param("statYear", "2026")
                        .param("statMonth", "7")
                        .param("townDeptId", "101")
                        .param("villageDeptId", "201")
                        .param("pageNum", "1")
                        .param("pageSize", "10"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200))
                .andExpect(jsonPath("$.rows[0].statYear").value(2026))
                .andExpect(jsonPath("$.rows[0].statMonth").value(7))
                .andExpect(jsonPath("$.rows[0].townName").value("巴青镇"))
                .andExpect(jsonPath("$.rows[0].shouldVaccinateCount").value(100))
                .andExpect(jsonPath("$.rows[0].actualVaccinateCount").value(80))
                .andExpect(jsonPath("$.rows[0].immunityRate").value(80.0));
    }

    @Test
    @DisplayName("DP-XM-API-028 GET vetCounts 按乡镇汇总")
    void api028_vetCounts() throws Exception
    {
        LivestockResourceVetCountListItemVo item = new LivestockResourceVetCountListItemVo();
        item.setTownName("巴青镇");
        item.setVetCount(15L);
        when(livestockResourceScreenService.listVetCounts(eq(101L)))
                .thenReturn(Collections.singletonList(item));
        mockMvc.perform(get("/bigScreen/livestockResource/vetCounts")
                        .param("townDeptId", "101")
                        .param("pageNum", "1")
                        .param("pageSize", "10"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200))
                .andExpect(jsonPath("$.rows[0].townName").value("巴青镇"))
                .andExpect(jsonPath("$.rows[0].vetCount").value(15));
    }

    @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.setOperatingFixedAssets(new BigDecimal("100.50"));
        overview.setNonOperatingFixedAssets(new BigDecimal("200.25"));
        overview.setMeatOutput(new BigDecimal("1.2000"));
        overview.setMilkOutput(new BigDecimal("3.4000"));
        overview.setImmunityRate(new BigDecimal("90.00"));
        overview.setVetCount(15);
        overview.setTechEnvoyCount(30);
        overview.setAgriUnitCount(40);
        vo.setOverview(overview);
        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);
    }
}
