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.math.BigDecimal;
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.BizSupplier;
import com.ruoyi.web.modules.trading.service.IBizSupplierService;
import com.ruoyi.web.modules.trading.support.SupplierRules;
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 BizSupplierControllerApiTest
{
    private static final String VALID_ID_CARD = "11010519491231002X";

    private static final String VALID_PHONE = "13800138000";

    private final ObjectMapper objectMapper = new ObjectMapper();

    @Mock
    private IBizSupplierService bizSupplierService;

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

    @Test
    @DisplayName("GET /list 编号精确")
    void listByCode() throws Exception
    {
        when(bizSupplierService.selectBizSupplierList(any())).thenReturn(Collections.emptyList());
        mockMvc.perform(get("/tradeMarket/supplier/list").param("supplierCode", "01"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("POST 新增按头计费")
    void addPerHead() throws Exception
    {
        when(bizSupplierService.insertBizSupplier(any())).thenReturn(1);
        BizSupplier body = sample(null);
        body.setFeeMethod(SupplierRules.FEE_METHOD_PER_HEAD);
        body.setFeeStandard(new BigDecimal("20"));
        mockMvc.perform(post("/tradeMarket/supplier")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(body)))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("POST 名称重复")
    void addDuplicateName() throws Exception
    {
        when(bizSupplierService.insertBizSupplier(any()))
                .thenThrow(new ServiceException("供应商名称已存在"));
        mockMvc.perform(post("/tradeMarket/supplier")
                .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
    {
        BizSupplier row = sample(2L);
        row.setSupplierCode("02");
        when(bizSupplierService.selectBizSupplierById(2L)).thenReturn(row);
        mockMvc.perform(get("/tradeMarket/supplier/2"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.data.supplierCode").value("02"));
    }

    @Test
    @DisplayName("PUT 修改")
    void putUpdate() throws Exception
    {
        when(bizSupplierService.updateBizSupplier(any())).thenReturn(1);
        BizSupplier body = sample(8L);
        body.setSupplierCode("08");
        mockMvc.perform(put("/tradeMarket/supplier")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(body)))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

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

    @Test
    @DisplayName("DELETE 有未结算结算单拒绝")
    void deleteBlocked() throws Exception
    {
        when(bizSupplierService.deleteBizSupplierByIds(any(), eq("tester")))
                .thenThrow(new ServiceException(SupplierRules.MSG_DELETE_UNSETTLED_SETTLEMENT));
        mockMvc.perform(delete("/tradeMarket/supplier/7"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(500));
    }

    private static BizSupplier sample(Long id)
    {
        BizSupplier r = new BizSupplier();
        r.setId(id);
        r.setSupplierName("扎西供应商");
        r.setSupplierType(SupplierRules.TYPE_INDIVIDUAL);
        r.setIdentityNo(VALID_ID_CARD);
        r.setContactPhone(VALID_PHONE);
        r.setFeeMethod(SupplierRules.FEE_METHOD_PER_ACCOUNT);
        return r;
    }
}
