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.Date;
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.BizIndustryPolicyPublicity;
import com.ruoyi.web.modules.industrypolicy.service.IBizIndustryPolicyPublicityService;

/**
 * ZCZX-XC-API-001～024（MockMvc + Mock Service）
 */
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT)
@DisplayName("产业政策宣传 HTTP 接口 MockMvc")
class BizIndustryPolicyPublicityControllerApiTest
{

    private final ObjectMapper objectMapper = new ObjectMapper();

    @Mock
    private IBizIndustryPolicyPublicityService bizIndustryPolicyPublicityService;

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

    @Test
    @DisplayName("ZCZX-XC-API-002 GET /list keyword")
    void api002_listKeyword() throws Exception
    {
        when(bizIndustryPolicyPublicityService.selectBizIndustryPolicyPublicityList(any()))
                .thenReturn(Collections.emptyList());
        mockMvc.perform(get("/industryPolicy/publicity/list").param("keyword", "补贴"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("ZCZX-XC-API-004 GET /list policyLevel")
    void api004_listLevel() throws Exception
    {
        when(bizIndustryPolicyPublicityService.selectBizIndustryPolicyPublicityList(any()))
                .thenReturn(Collections.emptyList());
        mockMvc.perform(get("/industryPolicy/publicity/list").param("policyLevel", "2"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("ZCZX-XC-API-005 GET /list publishStatus")
    void api005_listStatus() throws Exception
    {
        when(bizIndustryPolicyPublicityService.selectBizIndustryPolicyPublicityList(any()))
                .thenReturn(Collections.emptyList());
        mockMvc.perform(get("/industryPolicy/publicity/list").param("publishStatus", "0"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("ZCZX-XC-API-006 GET /list 组合")
    void api006_listCombo() throws Exception
    {
        when(bizIndustryPolicyPublicityService.selectBizIndustryPolicyPublicityList(any()))
                .thenReturn(Collections.emptyList());
        mockMvc.perform(get("/industryPolicy/publicity/list")
                .param("keyword", "产业")
                .param("policyLevel", "1")
                .param("publishStatus", "1"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

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

    @Test
    @DisplayName("ZCZX-XC-API-009 POST 名称非法")
    void api009_addBadName() throws Exception
    {
        when(bizIndustryPolicyPublicityService.insertBizIndustryPolicyPublicity(any()))
                .thenThrow(new ServiceException("政策名称须为1～20个字符"));
        BizIndustryPolicyPublicity body = sample(null);
        body.setPolicyName("");
        mockMvc.perform(post("/industryPolicy/publicity")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(body)))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(500));
    }

    @Test
    @DisplayName("ZCZX-XC-API-010 POST 层级非法")
    void api010_addBadLevel() throws Exception
    {
        when(bizIndustryPolicyPublicityService.insertBizIndustryPolicyPublicity(any()))
                .thenThrow(new ServiceException("政策层级须为1～4"));
        BizIndustryPolicyPublicity body = sample(null);
        body.setPolicyLevel(99);
        mockMvc.perform(post("/industryPolicy/publicity")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(body)))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(500));
    }

    @Test
    @DisplayName("ZCZX-XC-API-014 GET /{id} 详情")
    void api014_getDetail() throws Exception
    {
        when(bizIndustryPolicyPublicityService.selectBizIndustryPolicyPublicityById(2L)).thenReturn(sample(2L));
        mockMvc.perform(get("/industryPolicy/publicity/2"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200))
                .andExpect(jsonPath("$.data.policyName").exists())
                .andExpect(jsonPath("$.data.publishStatus").exists());
    }

    @Test
    @DisplayName("ZCZX-XC-API-015 GET /{id} 不存在")
    void api015_getMissing() throws Exception
    {
        when(bizIndustryPolicyPublicityService.selectBizIndustryPolicyPublicityById(999999L)).thenReturn(null);
        mockMvc.perform(get("/industryPolicy/publicity/999999"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("ZCZX-XC-API-016 PUT 修改成功")
    void api016_put() throws Exception
    {
        when(bizIndustryPolicyPublicityService.updateBizIndustryPolicyPublicity(any())).thenReturn(1);
        mockMvc.perform(put("/industryPolicy/publicity")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(sample(8L))))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("ZCZX-XC-API-017 PUT 已发布拒绝")
    void api017_putPublished() throws Exception
    {
        when(bizIndustryPolicyPublicityService.updateBizIndustryPolicyPublicity(any()))
                .thenThrow(new ServiceException("已发布内容请先下架后再编辑"));
        mockMvc.perform(put("/industryPolicy/publicity")
                .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-XC-API-019 DELETE 未发布")
    void api019_delete() throws Exception
    {
        when(bizIndustryPolicyPublicityService.deleteBizIndustryPolicyPublicityByIds(any())).thenReturn(1);
        mockMvc.perform(delete("/industryPolicy/publicity/7"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("ZCZX-XC-API-020 DELETE 已发布拒绝")
    void api020_deletePublished() throws Exception
    {
        when(bizIndustryPolicyPublicityService.deleteBizIndustryPolicyPublicityByIds(any()))
                .thenThrow(new ServiceException("已发布的数据不可删除，请先下架"));
        mockMvc.perform(delete("/industryPolicy/publicity/7"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(500));
    }

    @Test
    @DisplayName("ZCZX-XC-API-021 POST publish 成功")
    void api021_publish() throws Exception
    {
        when(bizIndustryPolicyPublicityService.publish(3L)).thenReturn(1);
        mockMvc.perform(post("/industryPolicy/publicity/publish/3"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("ZCZX-XC-API-022 POST publish 重复")
    void api022_publishAgain() throws Exception
    {
        when(bizIndustryPolicyPublicityService.publish(3L))
                .thenThrow(new ServiceException("仅「未发布」可发布"));
        mockMvc.perform(post("/industryPolicy/publicity/publish/3"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(500));
    }

    @Test
    @DisplayName("ZCZX-XC-API-023 POST offline 成功")
    void api023_offline() throws Exception
    {
        when(bizIndustryPolicyPublicityService.offline(4L)).thenReturn(1);
        mockMvc.perform(post("/industryPolicy/publicity/offline/4"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("ZCZX-XC-API-024 POST offline 未发布拒绝")
    void api024_offlineDraft() throws Exception
    {
        when(bizIndustryPolicyPublicityService.offline(5L))
                .thenThrow(new ServiceException("仅「已发布」可下架"));
        mockMvc.perform(post("/industryPolicy/publicity/offline/5"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(500));
    }

    private static BizIndustryPolicyPublicity sample(Long id)
    {
        BizIndustryPolicyPublicity r = new BizIndustryPolicyPublicity();
        r.setId(id);
        r.setPolicyName("产业政策");
        r.setPolicyLevel(1);
        r.setIssueDate(new Date());
        r.setPolicyDesc("描述");
        r.setPublishStatus(0);
        return r;
    }
}
