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.math.BigDecimal;
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.BizSubsidyGrantRecord;
import com.ruoyi.web.modules.industrypolicy.service.IBizSubsidyGrantRecordService;

/**
 * ZCZX-BTJL-API-001～025（MockMvc + Mock Service）
 */
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT)
@DisplayName("补贴发放记录 HTTP 接口 MockMvc")
class BizSubsidyGrantRecordControllerApiTest
{
    private final ObjectMapper objectMapper = new ObjectMapper();

    @Mock
    private IBizSubsidyGrantRecordService bizSubsidyGrantRecordService;

    @InjectMocks
    private BizSubsidyGrantRecordController 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-BTJL-API-001 GET /list 分页")
    void api001_list() throws Exception
    {
        when(bizSubsidyGrantRecordService.selectBizSubsidyGrantRecordList(any()))
                .thenReturn(Collections.singletonList(sample(1L)));
        mockMvc.perform(get("/industryPolicy/subsidyRecord/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-BTJL-API-002 GET /list 姓名模糊")
    void api002_listName() throws Exception
    {
        when(bizSubsidyGrantRecordService.selectBizSubsidyGrantRecordList(any()))
                .thenReturn(Collections.emptyList());
        mockMvc.perform(get("/industryPolicy/subsidyRecord/list").param("recipientName", "张"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("ZCZX-BTJL-API-003 类型筛选")
    void api003_listType() throws Exception
    {
        when(bizSubsidyGrantRecordService.selectBizSubsidyGrantRecordList(any()))
                .thenReturn(Collections.emptyList());
        mockMvc.perform(get("/industryPolicy/subsidyRecord/list").param("subsidyType", "1"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("ZCZX-BTJL-API-006 发放日期闭区间")
    void api006_listDateRange() throws Exception
    {
        when(bizSubsidyGrantRecordService.selectBizSubsidyGrantRecordList(any()))
                .thenReturn(Collections.emptyList());
        mockMvc.perform(get("/industryPolicy/subsidyRecord/list")
                .param("startDate", "2025-01-01")
                .param("endDate", "2025-12-31"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("ZCZX-BTJL-API-009 日期区间非法")
    void api009_listBadRange() throws Exception
    {
        when(bizSubsidyGrantRecordService.selectBizSubsidyGrantRecordList(any()))
                .thenThrow(new ServiceException("发放日期开始不能晚于结束"));
        mockMvc.perform(get("/industryPolicy/subsidyRecord/list")
                .param("startDate", "2025-12-01")
                .param("endDate", "2025-01-01"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(500))
                .andExpect(jsonPath("$.msg").value(containsString("结束")));
    }

    @Test
    @DisplayName("ZCZX-BTJL-API-010 组合查询")
    void api010_listCombo() throws Exception
    {
        when(bizSubsidyGrantRecordService.selectBizSubsidyGrantRecordList(any()))
                .thenReturn(Collections.emptyList());
        mockMvc.perform(get("/industryPolicy/subsidyRecord/list")
                .param("recipientName", "张")
                .param("subsidyType", "2")
                .param("startDate", "2025-01-01")
                .param("endDate", "2025-06-30"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("ZCZX-BTJL-API-011 POST 新增成功")
    void api011_add() throws Exception
    {
        when(bizSubsidyGrantRecordService.insertBizSubsidyGrantRecord(any())).thenReturn(1);
        mockMvc.perform(post("/industryPolicy/subsidyRecord")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(sample(null))))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("ZCZX-BTJL-API-012 POST 项目名非法")
    void api012_addBadProject() throws Exception
    {
        when(bizSubsidyGrantRecordService.insertBizSubsidyGrantRecord(any()))
                .thenThrow(new ServiceException("补贴项目名称须为1～20个字符"));
        BizSubsidyGrantRecord body = sample(null);
        body.setSubsidyProjectName("");
        mockMvc.perform(post("/industryPolicy/subsidyRecord")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(body)))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(500));
    }

    @Test
    @DisplayName("ZCZX-BTJL-API-014 POST 类型非法")
    void api014_addBadType() throws Exception
    {
        when(bizSubsidyGrantRecordService.insertBizSubsidyGrantRecord(any()))
                .thenThrow(new ServiceException("补贴类型须为1～3（1农业生产2住房基建3民生保障）"));
        BizSubsidyGrantRecord body = sample(null);
        body.setSubsidyType(99);
        mockMvc.perform(post("/industryPolicy/subsidyRecord")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(body)))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(500));
    }

    @Test
    @DisplayName("ZCZX-BTJL-API-015 POST 身份证非法")
    void api015_addBadIdCard() throws Exception
    {
        when(bizSubsidyGrantRecordService.insertBizSubsidyGrantRecord(any()))
                .thenThrow(new ServiceException("身份证号格式不正确"));
        mockMvc.perform(post("/industryPolicy/subsidyRecord")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(sample(null))))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(500));
    }

    @Test
    @DisplayName("ZCZX-BTJL-API-020 GET /{id} 详情")
    void api020_getDetail() throws Exception
    {
        when(bizSubsidyGrantRecordService.selectBizSubsidyGrantRecordById(2L)).thenReturn(sample(2L));
        mockMvc.perform(get("/industryPolicy/subsidyRecord/2"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200))
                .andExpect(jsonPath("$.data.subsidyProjectName").exists())
                .andExpect(jsonPath("$.data.grantDate").exists());
    }

    @Test
    @DisplayName("ZCZX-BTJL-API-021 GET /{id} 不存在")
    void api021_getMissing() throws Exception
    {
        when(bizSubsidyGrantRecordService.selectBizSubsidyGrantRecordById(999999L)).thenReturn(null);
        mockMvc.perform(get("/industryPolicy/subsidyRecord/999999"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("ZCZX-BTJL-API-022 PUT 修改成功")
    void api022_put() throws Exception
    {
        when(bizSubsidyGrantRecordService.updateBizSubsidyGrantRecord(any())).thenReturn(1);
        mockMvc.perform(put("/industryPolicy/subsidyRecord")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(sample(8L))))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("ZCZX-BTJL-API-023 PUT 校验失败")
    void api023_putBadPhone() throws Exception
    {
        when(bizSubsidyGrantRecordService.updateBizSubsidyGrantRecord(any()))
                .thenThrow(new ServiceException("联系电话须为合法的大陆手机号"));
        mockMvc.perform(put("/industryPolicy/subsidyRecord")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(sample(8L))))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(500));
    }

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

    @Test
    @DisplayName("ZCZX-BTJL-API-025 DELETE 批量")
    void api025_deleteBatch() throws Exception
    {
        when(bizSubsidyGrantRecordService.deleteBizSubsidyGrantRecordByIds(any())).thenReturn(2);
        mockMvc.perform(delete("/industryPolicy/subsidyRecord/7,8"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    private static BizSubsidyGrantRecord sample(Long id)
    {
        BizSubsidyGrantRecord r = new BizSubsidyGrantRecord();
        r.setId(id);
        r.setSubsidyProjectName("农业补贴");
        r.setSubsidyType(1);
        r.setRecipientName("张三");
        r.setIdCard("11010519491231002X");
        r.setContactPhone("13800138000");
        r.setBankAccount("6222021234567890");
        r.setSubsidyAmount(new BigDecimal("1500.00"));
        r.setGrantDate(new Date());
        return r;
    }
}
