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.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.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.MarketEntryTestSamples;
import com.ruoyi.web.modules.trading.domain.BizMarketEntry;
import com.ruoyi.web.modules.trading.domain.vo.MarketStallOptionVo;
import com.ruoyi.web.modules.trading.service.IBizMarketEntryService;
import com.ruoyi.web.modules.trading.support.MarketEntryRules;

@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT)
@DisplayName("市场进栏登记 HTTP MockMvc")
class BizMarketEntryControllerApiTest
{
    private final ObjectMapper objectMapper = new ObjectMapper()
            .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);

    @Mock
    private IBizMarketEntryService bizMarketEntryService;

    @InjectMocks
    private BizMarketEntryController 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-SCJLDJ-API-001 GET /list")
    void api001_list() throws Exception
    {
        when(bizMarketEntryService.selectBizMarketEntryList(any()))
                .thenReturn(Collections.singletonList(MarketEntryTestSamples.persistedRow()));
        mockMvc.perform(get("/tradeMarket/marketEntry/list")
                .param("entryDateStart", "2026-05-01")
                .param("entryDateEnd", "2026-05-31"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("ZCZX-SCJLDJ-API-007 列表日期区间非法")
    void api007_listDateInvalid() throws Exception
    {
        when(bizMarketEntryService.selectBizMarketEntryList(any()))
                .thenThrow(new ServiceException(MarketEntryRules.MSG_DATE_RANGE_INVALID));
        mockMvc.perform(get("/tradeMarket/marketEntry/list")
                .param("entryDateStart", "2026-05-31")
                .param("entryDateEnd", "2026-05-01"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(500));
    }

    @Test
    @DisplayName("ZCZX-SCJLDJ-API-019 GET /{id}")
    void api019_detail() throws Exception
    {
        when(bizMarketEntryService.selectBizMarketEntryById(MarketEntryTestSamples.ENTRY_ID))
                .thenReturn(MarketEntryTestSamples.persistedRow());
        mockMvc.perform(get("/tradeMarket/marketEntry/" + MarketEntryTestSamples.ENTRY_ID))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.data.stallCode").value("01"))
                .andExpect(jsonPath("$.data.supplierName").value("扎西合作社"));
    }

    @Test
    @DisplayName("ZCZX-SCJLDJ-API-009 POST 新增")
    void api009_add() throws Exception
    {
        when(bizMarketEntryService.insertBizMarketEntry(any())).thenReturn(1);
        mockMvc.perform(post("/tradeMarket/marketEntry")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(MarketEntryTestSamples.normalSaveRow())))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("ZCZX-SCJLDJ-API-015 M1 校验失败")
    void api015_m1Fail() throws Exception
    {
        when(bizMarketEntryService.insertBizMarketEntry(any()))
                .thenThrow(new ServiceException(MarketEntryRules.MSG_M1_MISMATCH));
        BizMarketEntry row = MarketEntryTestSamples.twoTagSaveRow();
        row.setQuantity(1);
        mockMvc.perform(post("/tradeMarket/marketEntry")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(row)))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(500));
    }

    @Test
    @DisplayName("ZCZX-SCJLDJ-API-021 PUT 修改")
    void api021_edit() throws Exception
    {
        BizMarketEntry row = MarketEntryTestSamples.persistedRow();
        when(bizMarketEntryService.updateBizMarketEntry(any())).thenReturn(1);
        mockMvc.perform(put("/tradeMarket/marketEntry")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(row)))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("ZCZX-SCJLDJ-API-024 DELETE")
    void api024_remove() throws Exception
    {
        when(bizMarketEntryService.deleteBizMarketEntryByIds(any(), eq("tester"))).thenReturn(1);
        mockMvc.perform(delete("/tradeMarket/marketEntry/" + MarketEntryTestSamples.ENTRY_ID))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("ZCZX-SCJLDJ-API-026 stallOptions")
    void api026_stallOptions() throws Exception
    {
        MarketStallOptionVo opt = new MarketStallOptionVo();
        opt.setStallId(1L);
        opt.setStallCode("01");
        when(bizMarketEntryService.selectStallOptions()).thenReturn(Collections.singletonList(opt));
        mockMvc.perform(get("/tradeMarket/marketEntry/stallOptions"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.data[0].stallCode").value("01"));
    }

    @Test
    @DisplayName("ZCZX-SCJLDJ-API-027 supplierEarTags")
    void api027_supplierEarTags() throws Exception
    {
        when(bizMarketEntryService.selectSupplierEarTags(1L))
                .thenReturn(Arrays.asList("E101", "E103"));
        mockMvc.perform(get("/tradeMarket/marketEntry/supplierEarTags").param("supplierId", "1"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.data.length()").value(2));
    }

    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()));
    }
}
