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.get;
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.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.SupplierSettlementTestSamples;
import com.ruoyi.web.modules.trading.domain.BizSupplierSettlement;
import com.ruoyi.web.modules.trading.service.IBizSupplierSettlementService;
import com.ruoyi.web.modules.trading.support.SettlementRules;

@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT)
@DisplayName("供应商结算 HTTP MockMvc")
class BizSupplierSettlementControllerApiTest
{
    private final ObjectMapper objectMapper = new ObjectMapper()
            .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);

    @Mock
    private IBizSupplierSettlementService bizSupplierSettlementService;

    @InjectMocks
    private BizSupplierSettlementController 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-GYSJSGL-API-001 GET /list")
    void api001_list() throws Exception
    {
        when(bizSupplierSettlementService.selectBizSupplierSettlementList(any()))
                .thenReturn(Collections.singletonList(SupplierSettlementTestSamples.pendingRow()));
        mockMvc.perform(get("/tradeMarket/supplierSettlement/list")
                .param("settlementNo", "JSD"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("ZCZX-GYSJSGL-API-007 GET /{id}")
    void api007_detail() throws Exception
    {
        when(bizSupplierSettlementService.selectBizSupplierSettlementById(SupplierSettlementTestSamples.SETTLEMENT_ID))
                .thenReturn(SupplierSettlementTestSamples.pendingRow());
        mockMvc.perform(get("/tradeMarket/supplierSettlement/" + SupplierSettlementTestSamples.SETTLEMENT_ID))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.data.settlementNo").value(SupplierSettlementTestSamples.SETTLEMENT_NO));
    }

    @Test
    @DisplayName("ZCZX-GYSJSGL-API-010 PUT completeSettle")
    void api010_completeSettle() throws Exception
    {
        BizSupplierSettlement done = SupplierSettlementTestSamples.completedRow();
        when(bizSupplierSettlementService.completeSettle(any(), eq("tester"))).thenReturn(done);
        mockMvc.perform(put("/tradeMarket/supplierSettlement/completeSettle")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(SupplierSettlementTestSamples.settleRequest())))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.data.settlementStatus").value(SettlementRules.SETTLEMENT_STATUS_COMPLETED));
    }

    @Test
    @DisplayName("ZCZX-GYSJSGL-API-013 已完成拒绝")
    void api013_alreadyCompleted() throws Exception
    {
        when(bizSupplierSettlementService.completeSettle(any(), any()))
                .thenThrow(new ServiceException(SettlementRules.MSG_NOT_PENDING));
        mockMvc.perform(put("/tradeMarket/supplierSettlement/completeSettle")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(SupplierSettlementTestSamples.settleRequest())))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(500));
    }

    @Test
    @DisplayName("ZCZX-GYSJSGL-API-011 缺结算凭证")
    void api011_missingVoucher() throws Exception
    {
        when(bizSupplierSettlementService.completeSettle(any(), any()))
                .thenThrow(new ServiceException(SettlementRules.MSG_SETTLE_VOUCHER_REQUIRED));
        mockMvc.perform(put("/tradeMarket/supplierSettlement/completeSettle")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(SupplierSettlementTestSamples.settleRequest())))
                .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()));
    }
}
