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.Collections;
import java.util.HashSet;
import java.util.Set;

import com.fasterxml.jackson.databind.ObjectMapper;
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.web.modules.trading.domain.BizIsolationPen;
import com.ruoyi.web.modules.trading.domain.BizIsolationSetting;
import com.ruoyi.web.modules.trading.service.IBizIsolationPenService;
import com.ruoyi.web.modules.trading.service.IBizIsolationSettingService;
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.ruoyi.framework.web.exception.GlobalExceptionHandler;

@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT)
@DisplayName("隔离圈位管理 HTTP 接口 MockMvc")
class BizIsolationPenControllerApiTest
{
    private final ObjectMapper objectMapper = new ObjectMapper();

    @Mock
    private IBizIsolationPenService bizIsolationPenService;

    @Mock
    private IBizIsolationSettingService bizIsolationSettingService;

    @InjectMocks
    private BizIsolationPenController controller;

    private MockMvc mockMvc;

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

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

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

    @Test
    @DisplayName("GET /list")
    void list() throws Exception
    {
        when(bizIsolationPenService.selectBizIsolationPenList(any()))
                .thenReturn(Collections.singletonList(samplePen(1L)));
        mockMvc.perform(get("/tradeMarket/isolationPen/list").param("penCode", "1"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("GET /setting")
    void getSetting() throws Exception
    {
        BizIsolationSetting setting = new BizIsolationSetting();
        setting.setDefaultDays(7);
        when(bizIsolationSettingService.getCurrentSetting()).thenReturn(setting);
        mockMvc.perform(get("/tradeMarket/isolationPen/setting"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.data.defaultDays").value(7));
    }

    @Test
    @DisplayName("PUT /setting")
    void saveSetting() throws Exception
    {
        when(bizIsolationSettingService.saveSetting(any(), eq("tester"))).thenReturn(1);
        BizIsolationSetting body = new BizIsolationSetting();
        body.setDefaultDays(14);
        mockMvc.perform(put("/tradeMarket/isolationPen/setting")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(body)))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("POST 新增圈位")
    void addPen() throws Exception
    {
        when(bizIsolationPenService.insertBizIsolationPen(any())).thenReturn(1);
        BizIsolationPen body = new BizIsolationPen();
        body.setRemark("A区");
        mockMvc.perform(post("/tradeMarket/isolationPen")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(body)))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("GET /{id}")
    void getDetail() throws Exception
    {
        BizIsolationPen row = samplePen(2L);
        row.setPenCode("02");
        when(bizIsolationPenService.selectBizIsolationPenById(2L)).thenReturn(row);
        mockMvc.perform(get("/tradeMarket/isolationPen/2"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.data.penCode").value("02"));
    }

    @Test
    @DisplayName("DELETE 圈位")
    void deletePen() throws Exception
    {
        when(bizIsolationPenService.deleteBizIsolationPenByIds(any(), eq("tester"))).thenReturn(1);
        mockMvc.perform(delete("/tradeMarket/isolationPen/5"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    private static BizIsolationPen samplePen(Long id)
    {
        BizIsolationPen r = new BizIsolationPen();
        r.setId(id);
        r.setPenCode("01");
        return r;
    }
}
