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

import static org.mockito.ArgumentMatchers.any;
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.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

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.common.exception.ServiceException;
import com.ruoyi.framework.web.exception.GlobalExceptionHandler;
import com.ruoyi.web.modules.industryservice.domain.BizYakAsset;
import com.ruoyi.web.modules.industryservice.domain.vo.YakAssetDetailVo;
import com.ruoyi.web.modules.industryservice.domain.vo.LivestockFinanceSyncResultVo;
import com.ruoyi.web.modules.industryservice.domain.vo.YakAssetSyncResultVo;
import com.ruoyi.web.modules.industryservice.service.IBizYakAssetService;

@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT)
@DisplayName("牦牛资产档案 HTTP 接口 MockMvc")
class BizYakAssetControllerApiTest
{
    @Mock
    private IBizYakAssetService bizYakAssetService;

    @InjectMocks
    private BizYakAssetController 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-MYNZDA-API-001 GET /list")
    void api001_list() throws Exception
    {
        when(bizYakAssetService.selectBizYakAssetList(any())).thenReturn(Collections.singletonList(sample(1L)));
        mockMvc.perform(get("/dataModel/yakAsset/list").param("pageNum", "1").param("pageSize", "20"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200))
                .andExpect(jsonPath("$.rows.length()").value(1));
    }

    @Test
    @DisplayName("ZCZX-MYNZDA-API-002 编号模糊")
    void api002_keyword() throws Exception
    {
        when(bizYakAssetService.selectBizYakAssetList(any())).thenReturn(Collections.emptyList());
        mockMvc.perform(get("/dataModel/yakAsset/list").param("keyword", "250001"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("ZCZX-MYNZDA-API-003 资产状态")
    void api003_assetStatus() throws Exception
    {
        when(bizYakAssetService.selectBizYakAssetList(any())).thenReturn(Collections.emptyList());
        mockMvc.perform(get("/dataModel/yakAsset/list").param("assetStatus", "2"))
                .andExpect(status().isOk());
    }

    @Test
    @DisplayName("ZCZX-MYNZDA-API-005 非法状态")
    void api005_invalidStatus() throws Exception
    {
        when(bizYakAssetService.selectBizYakAssetList(any()))
                .thenThrow(new ServiceException("资产状态须为1～4"));
        mockMvc.perform(get("/dataModel/yakAsset/list").param("assetStatus", "99"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(500));
    }

    @Test
    @DisplayName("ZCZX-MYNZDA-API-009 详情")
    void api009_detail() throws Exception
    {
        YakAssetDetailVo vo = new YakAssetDetailVo();
        vo.setAsset(sample(2L));
        when(bizYakAssetService.selectDetailById(2L)).thenReturn(vo);
        mockMvc.perform(get("/dataModel/yakAsset/2"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200))
                .andExpect(jsonPath("$.data.asset.yakNo").value("YAK20250001"));
    }

    @Test
    @DisplayName("ZCZX-MYNZDA-API-011 byNo")
    void api011_byNo() throws Exception
    {
        YakAssetDetailVo vo = new YakAssetDetailVo();
        vo.setAsset(sample(3L));
        when(bizYakAssetService.selectDetailByYakNo("YAK20250001")).thenReturn(vo);
        mockMvc.perform(get("/dataModel/yakAsset/byNo/YAK20250001"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.data.asset.id").value(3));
    }

    @Test
    @DisplayName("ZCZX-MYNZDA-API-013 生理曲线")
    void api013_physioChart() throws Exception
    {
        when(bizYakAssetService.selectPhysioChart(eq(1L), any())).thenReturn(Collections.emptyList());
        mockMvc.perform(get("/dataModel/yakAsset/1/physioChart"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("ZCZX-MYNZDA-API-015 生长曲线")
    void api015_growthChart() throws Exception
    {
        when(bizYakAssetService.selectGrowthChart(1L, "weight")).thenReturn(new com.ruoyi.web.modules.industryservice.domain.vo.YakAssetGrowthChartVo());
        mockMvc.perform(get("/dataModel/yakAsset/1/growthChart").param("metric", "weight"))
                .andExpect(status().isOk());
    }

    @Test
    @DisplayName("ZCZX-MYNZDA-API-017 同步")
    void api017_sync() throws Exception
    {
        LivestockFinanceSyncResultVo result = new LivestockFinanceSyncResultVo();
        YakAssetSyncResultVo yak = new YakAssetSyncResultVo();
        yak.setInsertCount(1);
        yak.setSyncTime(new java.util.Date());
        result.setYakAsset(yak);
        result.setSyncTime(yak.getSyncTime());
        when(bizYakAssetService.syncFromThirdParty()).thenReturn(result);
        mockMvc.perform(post("/dataModel/yakAsset/sync"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200))
                .andExpect(jsonPath("$.data.insertCount").value(1));
    }

    @Test
    @DisplayName("ZCZX-MYNZDA-API-018 同步失败")
    void api018_syncFail() throws Exception
    {
        when(bizYakAssetService.syncFromThirdParty()).thenThrow(new ServiceException("第三方服务不可用"));
        mockMvc.perform(post("/dataModel/yakAsset/sync"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(500));
    }

    private static BizYakAsset sample(Long id)
    {
        BizYakAsset a = new BizYakAsset();
        a.setId(id);
        a.setYakNo("YAK20250001");
        a.setAssetStatus(2);
        return a;
    }
}
