package com.ruoyi.web.modules.farming.controller;

import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isNull;
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.post;
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.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.framework.web.exception.GlobalExceptionHandler;
import com.ruoyi.web.modules.diagnosis.domain.BizServiceAppointment;
import com.ruoyi.web.modules.diagnosis.domain.VetAppointmentRejectBody;
import com.ruoyi.web.modules.farming.ExpertMyAppointmentTestSamples;
import com.ruoyi.web.modules.farming.domain.BizServiceAppointmentReview;
import com.ruoyi.web.modules.farming.service.IBizExpertMyAppointmentService;

@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT)
@DisplayName("我的预约（专家）HTTP 接口 MockMvc")
class BizExpertMyAppointmentControllerApiTest
{
    private final ObjectMapper objectMapper = new ObjectMapper();

    @Mock
    private IBizExpertMyAppointmentService bizExpertMyAppointmentService;

    @InjectMocks
    private BizExpertMyAppointmentController 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(ExpertMyAppointmentTestSamples.SYS_USER_ID);
        u.setUserName("expertTester");
        u.setPassword("x");
        Set<String> perms = new HashSet<>();
        perms.add(Constants.ALL_PERMISSION);
        LoginUser lu = new LoginUser(ExpertMyAppointmentTestSamples.SYS_USER_ID, 101L, u, perms);
        UsernamePasswordAuthenticationToken auth =
                new UsernamePasswordAuthenticationToken(lu, "", lu.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(auth);
    }

    @Test
    @DisplayName("GET /list")
    void list() throws Exception
    {
        BizServiceAppointment row = ExpertMyAppointmentTestSamples.pendingAppointment();
        row.setStatusLabel("待确认");
        when(bizExpertMyAppointmentService.selectExpertAppointmentList(any(), eq(ExpertMyAppointmentTestSamples.SYS_USER_ID)))
                .thenReturn(Collections.singletonList(row));
        mockMvc.perform(get("/techService/myAppointment/expert/list")
                .param("status", "0"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("GET /{id}")
    void getInfo() throws Exception
    {
        BizServiceAppointment row = ExpertMyAppointmentTestSamples.completedAppointment();
        row.setStatusLabel("已完成");
        row.setSummary("指导专业有效");
        when(bizExpertMyAppointmentService.selectExpertAppointmentById(3004L, ExpertMyAppointmentTestSamples.SYS_USER_ID))
                .thenReturn(row);
        mockMvc.perform(get("/techService/myAppointment/expert/3004"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200))
                .andExpect(jsonPath("$.data.appointeeName").value("才让"));
    }

    @Test
    @DisplayName("POST /confirm/{id}")
    void confirm() throws Exception
    {
        when(bizExpertMyAppointmentService.confirm(eq(3000L), eq(ExpertMyAppointmentTestSamples.SYS_USER_ID), eq("expertTester")))
                .thenReturn(1);
        mockMvc.perform(post("/techService/myAppointment/expert/confirm/3000"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("POST /reject/{id}")
    void reject() throws Exception
    {
        when(bizExpertMyAppointmentService.reject(eq(3000L), eq("时段冲突"), eq(ExpertMyAppointmentTestSamples.SYS_USER_ID),
                eq("expertTester"))).thenReturn(1);
        VetAppointmentRejectBody body = new VetAppointmentRejectBody();
        body.setRejectReason("时段冲突");
        mockMvc.perform(post("/techService/myAppointment/expert/reject/3000")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(body)))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("POST /complete/{id}")
    void complete() throws Exception
    {
        when(bizExpertMyAppointmentService.complete(eq(3001L), eq(ExpertMyAppointmentTestSamples.SYS_USER_ID),
                eq("expertTester"))).thenReturn(1);
        mockMvc.perform(post("/techService/myAppointment/expert/complete/3001"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("GET /reviewList/{id}")
    void reviewList() throws Exception
    {
        when(bizExpertMyAppointmentService.selectReviewList(3004L, ExpertMyAppointmentTestSamples.SYS_USER_ID))
                .thenReturn(Collections.singletonList(ExpertMyAppointmentTestSamples.sampleReview()));
        mockMvc.perform(get("/techService/myAppointment/expert/reviewList/3004"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200))
                .andExpect(jsonPath("$.data[0].reviewerName").value("才让"));
    }

    @Test
    @DisplayName("POST /reject/{id} 无 body")
    void rejectWithoutBody() throws Exception
    {
        when(bizExpertMyAppointmentService.reject(eq(3000L), isNull(), eq(ExpertMyAppointmentTestSamples.SYS_USER_ID),
                eq("expertTester"))).thenReturn(1);
        mockMvc.perform(post("/techService/myAppointment/expert/reject/3000")
                .contentType(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk());
    }
}
