package com.ruoyi.web.modules.trading.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.trading.domain.BizDistributor;
import com.ruoyi.web.modules.trading.service.IBizDistributorService;
import com.ruoyi.web.modules.trading.support.DistributorRules;
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 BizDistributorControllerApiTest
{
    private static final String VALID_ID_CARD = "11010519491231002X";

    private static final String VALID_PHONE = "13800138000";

    private final ObjectMapper objectMapper = new ObjectMapper();

    @Mock
    private IBizDistributorService bizDistributorService;

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

    @Test
    @DisplayName("GET /list 编号模糊")
    void listByCodeFuzzy() throws Exception
    {
        when(bizDistributorService.selectBizDistributorList(any())).thenReturn(Collections.emptyList());
        mockMvc.perform(get("/tradeMarket/distributor/list").param("distributorCode", "1"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("GET /list 名称模糊")
    void listByNameFuzzy() throws Exception
    {
        when(bizDistributorService.selectBizDistributorList(any())).thenReturn(Collections.emptyList());
        mockMvc.perform(get("/tradeMarket/distributor/list").param("distributorName", "扎西"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

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

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

    @Test
    @DisplayName("GET /{id} 详情")
    void getDetail() throws Exception
    {
        BizDistributor row = sample(2L);
        row.setDistributorCode("02");
        when(bizDistributorService.selectBizDistributorById(2L)).thenReturn(row);
        mockMvc.perform(get("/tradeMarket/distributor/2"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.data.distributorCode").value("02"));
    }

    @Test
    @DisplayName("PUT 修改")
    void putUpdate() throws Exception
    {
        when(bizDistributorService.updateBizDistributor(any())).thenReturn(1);
        BizDistributor body = sample(8L);
        body.setSalesDestination(DistributorRules.SALES_DESTINATION_OUT_PROVINCE);
        mockMvc.perform(put("/tradeMarket/distributor")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(body)))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("POST 分配账号")
    void assignAccount() throws Exception
    {
        when(bizDistributorService.assignAccount(eq(9L), eq("tester"))).thenReturn(1);
        mockMvc.perform(post("/tradeMarket/distributor/assignAccount/9"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("DELETE 有未支付订单拒绝")
    void deleteBlocked() throws Exception
    {
        when(bizDistributorService.deleteBizDistributorByIds(any(), eq("tester")))
                .thenThrow(new ServiceException(DistributorRules.MSG_DELETE_UNPAID_ORDER));
        mockMvc.perform(delete("/tradeMarket/distributor/7"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(500));
    }

    private static BizDistributor sample(Long id)
    {
        BizDistributor r = new BizDistributor();
        r.setId(id);
        r.setDistributorName("扎西承销商");
        r.setDistributorType(DistributorRules.TYPE_INDIVIDUAL);
        r.setIdentityNo(VALID_ID_CARD);
        r.setContactPhone(VALID_PHONE);
        r.setSalesDestination(DistributorRules.SALES_DESTINATION_LOCAL_CITY);
        return r;
    }
}
