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

import static org.hamcrest.Matchers.containsString;
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.common.exception.ServiceException;
import com.ruoyi.framework.web.exception.GlobalExceptionHandler;
import com.ruoyi.web.modules.circulation.domain.BizTradeMarket;
import com.ruoyi.web.modules.circulation.service.IBizTradeMarketService;
import com.ruoyi.web.modules.circulation.support.TradeMarketRules;
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;

@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT)
@DisplayName("交易市场管理 HTTP 接口 MockMvc")
class BizTradeMarketControllerApiTest
{
    private static final String VALID_PHONE = "13800138000";

    private final ObjectMapper objectMapper = new ObjectMapper();

    @Mock
    private IBizTradeMarketService bizTradeMarketService;

    @InjectMocks
    private BizTradeMarketController 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(bizTradeMarketService.selectBizTradeMarketList(any()))
                .thenReturn(Collections.singletonList(sample(1L)));
        mockMvc.perform(get("/livestock/tradeMarket/list").param("pageNum", "1").param("pageSize", "10"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200))
                .andExpect(jsonPath("$.rows").isArray());
    }

    @Test
    @DisplayName("GET /list 名称模糊")
    void listMarketName() throws Exception
    {
        when(bizTradeMarketService.selectBizTradeMarketList(any())).thenReturn(Collections.emptyList());
        mockMvc.perform(get("/livestock/tradeMarket/list").param("marketName", "交易"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("GET /list 运营状态")
    void listOperateStatus() throws Exception
    {
        when(bizTradeMarketService.selectBizTradeMarketList(any())).thenReturn(Collections.emptyList());
        mockMvc.perform(get("/livestock/tradeMarket/list").param("operateStatus", "2"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("POST 新增")
    void add() throws Exception
    {
        when(bizTradeMarketService.insertBizTradeMarket(any())).thenReturn(1);
        mockMvc.perform(post("/livestock/tradeMarket")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(sample(null))))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("POST 无照片")
    void addNoPhoto() throws Exception
    {
        when(bizTradeMarketService.insertBizTradeMarket(any())).thenReturn(1);
        BizTradeMarket body = sample(null);
        body.setPhotoFileUrl(null);
        body.setPhotoFilePath(null);
        mockMvc.perform(post("/livestock/tradeMarket")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(body)))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("POST 名称重复")
    void addDuplicateName() throws Exception
    {
        when(bizTradeMarketService.insertBizTradeMarket(any()))
                .thenThrow(new ServiceException("市场名称已存在"));
        mockMvc.perform(post("/livestock/tradeMarket")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(sample(null))))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(500))
                .andExpect(jsonPath("$.msg").value(containsString("已存在")));
    }

    @Test
    @DisplayName("POST 手机号非法")
    void addBadPhone() throws Exception
    {
        when(bizTradeMarketService.insertBizTradeMarket(any()))
                .thenThrow(new ServiceException("请输入正确的手机号码"));
        mockMvc.perform(post("/livestock/tradeMarket")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(sample(null))))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(500));
    }

    @Test
    @DisplayName("GET /{id} 详情")
    void getDetail() throws Exception
    {
        BizTradeMarket row = sample(2L);
        row.setOperateStatusName("正常");
        when(bizTradeMarketService.selectBizTradeMarketById(2L)).thenReturn(row);
        mockMvc.perform(get("/livestock/tradeMarket/2"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200))
                .andExpect(jsonPath("$.data.marketName").exists());
    }

    @Test
    @DisplayName("PUT 修改")
    void putUpdate() throws Exception
    {
        when(bizTradeMarketService.updateBizTradeMarket(any())).thenReturn(1);
        BizTradeMarket body = sample(8L);
        body.setDetailAddress("新交易路99号");
        mockMvc.perform(put("/livestock/tradeMarket")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(body)))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("DELETE 单条")
    void deleteSingle() throws Exception
    {
        when(bizTradeMarketService.deleteBizTradeMarketByIds(any(), eq("tester"))).thenReturn(1);
        mockMvc.perform(delete("/livestock/tradeMarket/7"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("DELETE 有关联拒绝")
    void deleteBlocked() throws Exception
    {
        when(bizTradeMarketService.deleteBizTradeMarketByIds(any(), eq("tester")))
                .thenThrow(new ServiceException("存在关联业务，无法删除"));
        mockMvc.perform(delete("/livestock/tradeMarket/7"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(500))
                .andExpect(jsonPath("$.msg").value(containsString("关联业务")));
    }

    private static BizTradeMarket sample(Long id)
    {
        BizTradeMarket r = new BizTradeMarket();
        r.setId(id);
        r.setMarketName("巴青交易市场");
        r.setDetailAddress("西藏那曲市巴青县交易路1号");
        r.setPersonInCharge("王五");
        r.setContactPhone(VALID_PHONE);
        r.setOperateStatus(TradeMarketRules.OPERATE_STATUS_NORMAL);
        r.setPhotoFileUrl("http://localhost/profile/upload/m.jpg");
        r.setPhotoFilePath(Constants.RESOURCE_PREFIX + "/upload/m.jpg");
        return r;
    }
}
