package com.ruoyi.web.modules.trading.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.delete;
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.request.MockMvcRequestBuilders.put;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import java.text.ParseException;
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.http.MediaType;
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.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
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.trading.IsolationPatrolTestSamples;
import com.ruoyi.web.modules.trading.domain.BizIsolationPatrol;
import com.ruoyi.web.modules.trading.domain.vo.IsolationPenOptionVo;
import com.ruoyi.web.modules.trading.service.IBizIsolationPatrolService;
import com.ruoyi.web.modules.trading.support.IsolationPatrolRules;

@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT)
@DisplayName("隔离巡查登记 HTTP MockMvc")
class BizIsolationPatrolControllerApiTest
{
    private final ObjectMapper objectMapper = new ObjectMapper()
            .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);

    @Mock
    private IBizIsolationPatrolService bizIsolationPatrolService;

    @InjectMocks
    private BizIsolationPatrolController controller;

    private MockMvc mockMvc;

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

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

    @Test
    @DisplayName("ZCZX-GLXCDJ-API-001 GET /list")
    void api001_list() throws Exception
    {
        when(bizIsolationPatrolService.selectBizIsolationPatrolList(any()))
                .thenReturn(Collections.singletonList(IsolationPatrolTestSamples.persistedRow()));
        mockMvc.perform(get("/tradeMarket/isolationPatrol/list")
                .param("patrolDateStart", "2026-05-01")
                .param("patrolDateEnd", "2026-05-31"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("ZCZX-GLXCDJ-API-011 GET /{id}")
    void api011_detail() throws Exception
    {
        when(bizIsolationPatrolService.selectBizIsolationPatrolById(IsolationPatrolTestSamples.PATROL_ID))
                .thenReturn(IsolationPatrolTestSamples.persistedRow());
        mockMvc.perform(get("/tradeMarket/isolationPatrol/" + IsolationPatrolTestSamples.PATROL_ID))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.data.penCode").value("01"));
    }

    @Test
    @DisplayName("ZCZX-GLXCDJ-API-013 POST 新增")
    void api013_add() throws Exception
    {
        when(bizIsolationPatrolService.insertBizIsolationPatrol(any())).thenReturn(1);
        mockMvc.perform(post("/tradeMarket/isolationPatrol")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(IsolationPatrolTestSamples.normalSaveRow())))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("ZCZX-GLXCDJ-API-015 PUT 修改")
    void api015_edit() throws Exception
    {
        BizIsolationPatrol row = IsolationPatrolTestSamples.persistedRow();
        when(bizIsolationPatrolService.updateBizIsolationPatrol(any())).thenReturn(1);
        mockMvc.perform(put("/tradeMarket/isolationPatrol")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(row)))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("ZCZX-GLXCDJ-API-017 DELETE")
    void api017_remove() throws Exception
    {
        when(bizIsolationPatrolService.deleteBizIsolationPatrolByIds(any(), eq("tester"))).thenReturn(1);
        mockMvc.perform(delete("/tradeMarket/isolationPatrol/" + IsolationPatrolTestSamples.PATROL_ID))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("ZCZX-GLXCDJ-API-021 penOptions")
    void api021_penOptions() throws Exception
    {
        IsolationPenOptionVo opt = new IsolationPenOptionVo();
        opt.setPenId(1L);
        opt.setPenCode("01");
        when(bizIsolationPatrolService.selectInStockPenOptions()).thenReturn(Collections.singletonList(opt));
        mockMvc.perform(get("/tradeMarket/isolationPatrol/penOptions"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.data[0].penCode").value("01"));
    }

    @Test
    @DisplayName("ZCZX-GLXCDJ-API-022 penEarTags")
    void api022_penEarTags() throws Exception
    {
        when(bizIsolationPatrolService.selectPenEarTags(1L)).thenReturn(IsolationPatrolTestSamples.inStockTags());
        mockMvc.perform(get("/tradeMarket/isolationPatrol/penEarTags").param("penId", "1"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.data[0]").value("E001"));
    }

    @Test
    @DisplayName("ZCZX-GLXCDJ-API-014 P2 校验失败")
    void api014_p2Fail() throws Exception
    {
        when(bizIsolationPatrolService.insertBizIsolationPatrol(any()))
                .thenThrow(new ServiceException(IsolationPatrolRules.MSG_QTY_TAG_MISMATCH));
        BizIsolationPatrol row = IsolationPatrolTestSamples.abnormalSaveRow();
        row.setEarTagList(Collections.singletonList("E001"));
        mockMvc.perform(post("/tradeMarket/isolationPatrol")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(row)))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(500));
    }

    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);
        SecurityContextHolder.getContext().setAuthentication(
                new UsernamePasswordAuthenticationToken(lu, "", lu.getAuthorities()));
    }
}
