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

import static org.hamcrest.Matchers.containsString;
import static org.mockito.ArgumentMatchers.any;
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 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.common.exception.ServiceException;
import com.ruoyi.framework.web.exception.GlobalExceptionHandler;
import com.ruoyi.web.modules.industrypolicy.domain.BizSubsidyMatter;
import com.ruoyi.web.modules.industrypolicy.service.IBizSubsidyMatterService;
import com.ruoyi.web.modules.industrypolicy.support.SubsidyMatterRules;

/**
 * ZCZX-BTSX-API-001～033
 */
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT)
@DisplayName("项目与补贴-补贴 HTTP 接口 MockMvc")
class BizSubsidyMatterControllerApiTest
{
    private final ObjectMapper objectMapper = new ObjectMapper();

    @Mock
    private IBizSubsidyMatterService bizSubsidyMatterService;

    @InjectMocks
    private BizSubsidyMatterController 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("ZCZX-BTSX-API-001 GET /list 分页")
    void api001_list() throws Exception
    {
        when(bizSubsidyMatterService.selectBizSubsidyMatterList(any()))
                .thenReturn(Collections.singletonList(sample(1L)));
        mockMvc.perform(get("/industryPolicy/subsidyMatter/list").param("pageNum", "1").param("pageSize", "10"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200))
                .andExpect(jsonPath("$.rows").isArray());
    }

    @Test
    @DisplayName("ZCZX-BTSX-API-002 GET /list keyword")
    void api002_listKeyword() throws Exception
    {
        when(bizSubsidyMatterService.selectBizSubsidyMatterList(any())).thenReturn(Collections.emptyList());
        mockMvc.perform(get("/industryPolicy/subsidyMatter/list").param("keyword", "农业"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("ZCZX-BTSX-API-004 发放状态-申请中")
    void api004_listGrantApplying() throws Exception
    {
        when(bizSubsidyMatterService.selectBizSubsidyMatterList(any())).thenReturn(Collections.emptyList());
        mockMvc.perform(get("/industryPolicy/subsidyMatter/list").param("grantStatus", "1"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("ZCZX-BTSX-API-006 组合查询")
    void api006_listCombo() throws Exception
    {
        when(bizSubsidyMatterService.selectBizSubsidyMatterList(any())).thenReturn(Collections.emptyList());
        mockMvc.perform(get("/industryPolicy/subsidyMatter/list")
                .param("keyword", "补")
                .param("grantStatus", "2"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("ZCZX-BTSX-API-007 POST 新增成功")
    void api007_add() throws Exception
    {
        when(bizSubsidyMatterService.insertBizSubsidyMatter(any())).thenReturn(1);
        mockMvc.perform(post("/industryPolicy/subsidyMatter")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(sample(null))))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("ZCZX-BTSX-API-011 POST 名称非法")
    void api011_addBadName() throws Exception
    {
        when(bizSubsidyMatterService.insertBizSubsidyMatter(any()))
                .thenThrow(new ServiceException("补贴名称须为1～20个字符"));
        mockMvc.perform(post("/industryPolicy/subsidyMatter")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(sample(null))))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(500));
    }

    @Test
    @DisplayName("ZCZX-BTSX-API-014 POST 缺明细")
    void api014_addNoDetail() throws Exception
    {
        when(bizSubsidyMatterService.insertBizSubsidyMatter(any()))
                .thenThrow(new ServiceException("补贴明细附件 url、path、name 均必填"));
        BizSubsidyMatter body = sample(null);
        body.setDetailFileUrl(null);
        mockMvc.perform(post("/industryPolicy/subsidyMatter")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(body)))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(500));
    }

    @Test
    @DisplayName("ZCZX-BTSX-API-016 GET /{id} 详情")
    void api016_getDetail() throws Exception
    {
        when(bizSubsidyMatterService.selectBizSubsidyMatterById(2L)).thenReturn(sample(2L));
        mockMvc.perform(get("/industryPolicy/subsidyMatter/2"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200))
                .andExpect(jsonPath("$.data.subsidyName").exists())
                .andExpect(jsonPath("$.data.detailFileName").exists());
    }

    @Test
    @DisplayName("ZCZX-BTSX-API-018 PUT 修改成功")
    void api018_put() throws Exception
    {
        when(bizSubsidyMatterService.updateBizSubsidyMatter(any())).thenReturn(1);
        mockMvc.perform(put("/industryPolicy/subsidyMatter")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(sample(8L))))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("ZCZX-BTSX-API-019 状态变更")
    void api019_putGrantStatus() throws Exception
    {
        when(bizSubsidyMatterService.updateBizSubsidyMatter(any())).thenReturn(1);
        BizSubsidyMatter body = sample(8L);
        body.setGrantStatus(SubsidyMatterRules.GRANT_GRANTED);
        mockMvc.perform(put("/industryPolicy/subsidyMatter")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(body)))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("ZCZX-BTSX-API-021 PUT 清空明细拒绝")
    void api021_putClearDetail() throws Exception
    {
        when(bizSubsidyMatterService.updateBizSubsidyMatter(any()))
                .thenThrow(new ServiceException("补贴明细附件 url、path、name 均必填"));
        mockMvc.perform(put("/industryPolicy/subsidyMatter")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(sample(8L))))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(500));
    }

    @Test
    @DisplayName("ZCZX-BTSX-API-024 DELETE 单条")
    void api024_delete() throws Exception
    {
        when(bizSubsidyMatterService.deleteBizSubsidyMatterByIds(any())).thenReturn(1);
        mockMvc.perform(delete("/industryPolicy/subsidyMatter/7"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("ZCZX-BTSX-API-031 POST publish")
    void api031_publish() throws Exception
    {
        when(bizSubsidyMatterService.publish(3L)).thenReturn(1);
        mockMvc.perform(post("/industryPolicy/subsidyMatter/publish/3"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("ZCZX-BTSX-API-032 PUT 已发布拒绝")
    void api032_putPublished() throws Exception
    {
        when(bizSubsidyMatterService.updateBizSubsidyMatter(any()))
                .thenThrow(new ServiceException("已发布补贴请先下架后再编辑"));
        mockMvc.perform(put("/industryPolicy/subsidyMatter")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(sample(8L))))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(500))
                .andExpect(jsonPath("$.msg").value(containsString("下架")));
    }

    @Test
    @DisplayName("ZCZX-BTSX-API-033 POST offline")
    void api033_offline() throws Exception
    {
        when(bizSubsidyMatterService.offline(4L)).thenReturn(1);
        mockMvc.perform(post("/industryPolicy/subsidyMatter/offline/4"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    private static BizSubsidyMatter sample(Long id)
    {
        BizSubsidyMatter r = new BizSubsidyMatter();
        r.setId(id);
        r.setSubsidyName("农业补贴");
        r.setGrantStatus(SubsidyMatterRules.GRANT_APPLYING);
        r.setDetailFileUrl("http://localhost/a.pdf");
        r.setDetailFilePath("/profile/upload/a.pdf");
        r.setDetailFileName("a.pdf");
        r.setPublishStatus(0);
        return r;
    }
}
