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

import static org.mockito.ArgumentMatchers.any;
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.Date;
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.core.domain.entity.SysUser;
import com.ruoyi.web.modules.industrypolicy.support.PastureRules;
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.BizPasture;
import com.ruoyi.web.modules.industryservice.domain.vo.YakAssetSyncResultVo;
import com.ruoyi.web.modules.industryservice.service.IBizPastureService;
import com.ruoyi.web.modules.industryservice.support.PastureSyncRules;

/**
 * 牧场管理 HTTP 接口 MockMvc（列表/详情/同步）
 */
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT)
@DisplayName("牧场管理 HTTP 接口 MockMvc")
class BizPastureControllerApiTest
{
    @Mock
    private IBizPastureService bizPastureService;

    @InjectMocks
    private BizPastureController controller;

    private MockMvc mockMvc;

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

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

    @Test
    @DisplayName("列表默认分页")
    void listDefault() throws Exception
    {
        when(bizPastureService.selectBizPastureList(any())).thenReturn(Collections.singletonList(sample(1L)));
        mockMvc.perform(get("/dataModel/pasture/list"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.rows[0].pastureName").value("示范牧场"));
    }

    @Test
    @DisplayName("列表关键字筛选")
    void listKeyword() throws Exception
    {
        when(bizPastureService.selectBizPastureList(any())).thenReturn(Collections.emptyList());
        mockMvc.perform(get("/dataModel/pasture/list").param("keyword", "示范"))
                .andExpect(status().isOk());
    }

    @Test
    @DisplayName("列表类型筛选")
    void listFarmType() throws Exception
    {
        when(bizPastureService.selectBizPastureList(any())).thenReturn(Collections.emptyList());
        mockMvc.perform(get("/dataModel/pasture/list").param("farmType", "1"))
                .andExpect(status().isOk());
    }

    @Test
    @DisplayName("详情")
    void getInfo() throws Exception
    {
        when(bizPastureService.selectBizPastureById(2L)).thenReturn(sample(2L));
        mockMvc.perform(get("/dataModel/pasture/2"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.data.pastureName").exists())
                .andExpect(jsonPath("$.data.introduction").exists());
    }

    @Test
    @DisplayName("详情不存在")
    void getInfoMissing() throws Exception
    {
        when(bizPastureService.selectBizPastureById(999999L)).thenReturn(null);
        mockMvc.perform(get("/dataModel/pasture/999999"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("同步成功")
    void syncSuccess() throws Exception
    {
        YakAssetSyncResultVo vo = new YakAssetSyncResultVo();
        vo.setInsertCount(2);
        vo.setUpdateCount(1);
        vo.setSyncTime(new Date());
        when(bizPastureService.syncFromThirdParty()).thenReturn(vo);
        mockMvc.perform(post("/dataModel/pasture/sync"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.data.insertCount").value(2))
                .andExpect(jsonPath("$.data.updateCount").value(1));
    }

    @Test
    @DisplayName("同步进行中")
    void syncInProgress() throws Exception
    {
        when(bizPastureService.syncFromThirdParty())
                .thenThrow(new ServiceException(PastureSyncRules.MSG_SYNC_IN_PROGRESS));
        mockMvc.perform(post("/dataModel/pasture/sync"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.msg").value(PastureSyncRules.MSG_SYNC_IN_PROGRESS));
    }

    private void loginAsAllPermissions()
    {
        Set<String> perms = new HashSet<>();
        perms.add("*:*:*");
        SysUser user = new SysUser();
        user.setUserId(1L);
        user.setUserName("admin");
        LoginUser loginUser = new LoginUser(1L, 1L, user, perms);
        UsernamePasswordAuthenticationToken auth =
                new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(auth);
    }

    private static BizPasture sample(Long id)
    {
        BizPasture r = new BizPasture();
        r.setId(id);
        r.setExternalId(10001L);
        r.setPastureName("示范牧场");
        r.setFarmType("1");
        r.setIntroduction("示范简介");
        r.setCounty("巴青县");
        r.setTown("拉西镇");
        r.setPersonInCharge("扎西");
        r.setContactPhone("13800138001");
        r.setCreateTime(new Date());
        r.setDelFlag(PastureRules.DEL_FLAG_NORMAL);
        return r;
    }
}
