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.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.TradeOrderTestSamples;
import com.ruoyi.web.modules.trading.domain.BizTradeOrder;
import com.ruoyi.web.modules.trading.service.IBizTradeOrderService;
import com.ruoyi.web.modules.trading.support.TradeOrderRules;

@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT)
@DisplayName("交易订单 HTTP MockMvc")
class BizTradeOrderControllerApiTest
{
    private final ObjectMapper objectMapper = new ObjectMapper()
            .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);

    @Mock
    private IBizTradeOrderService bizTradeOrderService;

    @InjectMocks
    private BizTradeOrderController 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-JYDDGL-API-001 GET /list")
    void api001_list() throws Exception
    {
        when(bizTradeOrderService.selectBizTradeOrderList(any()))
                .thenReturn(Collections.singletonList(TradeOrderTestSamples.pendingRow()));
        mockMvc.perform(get("/tradeMarket/tradeOrder/list").param("orderNo", "0520"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("ZCZX-JYDDGL-API-020 GET /{id}")
    void api020_detail() throws Exception
    {
        when(bizTradeOrderService.selectBizTradeOrderById(TradeOrderTestSamples.ORDER_ID))
                .thenReturn(TradeOrderTestSamples.pendingRow());
        mockMvc.perform(get("/tradeMarket/tradeOrder/" + TradeOrderTestSamples.ORDER_ID))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.data.orderNo").value(TradeOrderTestSamples.ORDER_NO));
    }

    @Test
    @DisplayName("ZCZX-JYDDGL-API-011 POST 新增")
    void api011_add() throws Exception
    {
        when(bizTradeOrderService.insertBizTradeOrder(any())).thenReturn(1);
        mockMvc.perform(post("/tradeMarket/tradeOrder")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(TradeOrderTestSamples.normalSaveRow())))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("ZCZX-JYDDGL-API-022 PUT 修改")
    void api022_edit() throws Exception
    {
        BizTradeOrder row = TradeOrderTestSamples.pendingRow();
        when(bizTradeOrderService.updateBizTradeOrder(any())).thenReturn(1);
        mockMvc.perform(put("/tradeMarket/tradeOrder")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(row)))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("ZCZX-JYDDGL-API-025 DELETE")
    void api025_remove() throws Exception
    {
        when(bizTradeOrderService.deleteBizTradeOrderByIds(any(), eq("tester"))).thenReturn(1);
        mockMvc.perform(delete("/tradeMarket/tradeOrder/" + TradeOrderTestSamples.ORDER_ID))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("ZCZX-JYDDGL-API-007 supplierEarTags")
    void api007_supplierEarTags() throws Exception
    {
        when(bizTradeOrderService.selectSupplierEarTags(1L))
                .thenReturn(Arrays.asList("E101", "E104"));
        mockMvc.perform(get("/tradeMarket/tradeOrder/supplierEarTags")
                .param("supplierId", "1"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.data.length()").value(2));
    }

    @Test
    @DisplayName("ZCZX-JYDDGL-API-028 completePay")
    void api028_completePay() throws Exception
    {
        BizTradeOrder done = TradeOrderTestSamples.pendingRow();
        done.setOrderStatus(TradeOrderRules.ORDER_STATUS_COMPLETED);
        done.setSettlementNo("JSD20260520001");
        when(bizTradeOrderService.completePay(any(), eq("tester"))).thenReturn(done);
        mockMvc.perform(put("/tradeMarket/tradeOrder/completePay")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(TradeOrderTestSamples.payRequest())))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.data.settlementNo").value("JSD20260520001"));
    }

    @Test
    @DisplayName("ZCZX-JYDDGL-API-031 收费未配置")
    void api031_feeFail() throws Exception
    {
        when(bizTradeOrderService.completePay(any(), any()))
                .thenThrow(new ServiceException(TradeOrderRules.MSG_FEE_NOT_CONFIGURED));
        mockMvc.perform(put("/tradeMarket/tradeOrder/completePay")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(TradeOrderTestSamples.payRequest())))
                .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()));
    }
}
