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

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.architecture.domain.BizEpidemicTreatmentStandard;
import com.ruoyi.web.modules.architecture.service.IBizEpidemicTreatmentStandardService;

/**
 * 疫病诊疗标准 HTTP 接口 MockMvc 测试（Mock Service）。
 */
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT)
@DisplayName("疫病诊疗标准 HTTP 接口 MockMvc")
class BizEpidemicTreatmentStandardControllerApiTest
{

    private final ObjectMapper objectMapper = new ObjectMapper();

    @Mock
    private IBizEpidemicTreatmentStandardService bizEpidemicTreatmentStandardService;

    @InjectMocks
    private BizEpidemicTreatmentStandardController 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 分页与 code=200")
    void api001_list() throws Exception
    {
        when(bizEpidemicTreatmentStandardService.selectBizEpidemicTreatmentStandardList(any()))
                .thenReturn(Collections.singletonList(sample(1L)));
        mockMvc.perform(get("/epidemicTreatment/standard/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("GET /list keyword")
    void api002_listKeyword() throws Exception
    {
        when(bizEpidemicTreatmentStandardService.selectBizEpidemicTreatmentStandardList(any())).thenReturn(Collections.emptyList());
        mockMvc.perform(get("/epidemicTreatment/standard/list").param("keyword", "诊疗"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("GET /list standardType")
    void api003_listType() throws Exception
    {
        when(bizEpidemicTreatmentStandardService.selectBizEpidemicTreatmentStandardList(any())).thenReturn(Collections.emptyList());
        mockMvc.perform(get("/epidemicTreatment/standard/list").param("standardType", "001013"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("GET /list keyword + standardType")
    void api004_listCombo() throws Exception
    {
        when(bizEpidemicTreatmentStandardService.selectBizEpidemicTreatmentStandardList(any())).thenReturn(Collections.emptyList());
        mockMvc.perform(get("/epidemicTreatment/standard/list").param("keyword", "测").param("standardType", "1"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("POST 新增成功")
    void api005_add() throws Exception
    {
        when(bizEpidemicTreatmentStandardService.insertBizEpidemicTreatmentStandard(any())).thenReturn(1);
        BizEpidemicTreatmentStandard body = sample(null);
        mockMvc.perform(post("/epidemicTreatment/standard")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(body)))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("POST 新增名称非法")
    void api006_addBadName() throws Exception
    {
        when(bizEpidemicTreatmentStandardService.insertBizEpidemicTreatmentStandard(any()))
                .thenThrow(new ServiceException("标准名称须为1～20个字符"));
        BizEpidemicTreatmentStandard body = sample(null);
        body.setStandardName("");
        mockMvc.perform(post("/epidemicTreatment/standard")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(body)))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(500));
    }

    @Test
    @DisplayName("POST 新增类型非法")
    void api007_addBadType() throws Exception
    {
        when(bizEpidemicTreatmentStandardService.insertBizEpidemicTreatmentStandard(any()))
                .thenThrow(new ServiceException("标准类型无效，请选择资讯类别中的类型"));
        BizEpidemicTreatmentStandard body = sample(null);
        body.setStandardType("999999");
        mockMvc.perform(post("/epidemicTreatment/standard")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(body)))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(500));
    }

    @Test
    @DisplayName("POST 新增简介超长")
    void api008_addLongIntro() throws Exception
    {
        when(bizEpidemicTreatmentStandardService.insertBizEpidemicTreatmentStandard(any()))
                .thenThrow(new ServiceException("简介不能超过50个字符"));
        BizEpidemicTreatmentStandard body = sample(null);
        body.setIntroduction(repeat('x', 51));
        mockMvc.perform(post("/epidemicTreatment/standard")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(body)))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(500));
    }

    @Test
    @DisplayName("GET /{id} 详情字段")
    void api009_getDetail() throws Exception
    {
        when(bizEpidemicTreatmentStandardService.selectBizEpidemicTreatmentStandardById(2L)).thenReturn(sample(2L));
        mockMvc.perform(get("/epidemicTreatment/standard/2"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200))
                .andExpect(jsonPath("$.data.standardName").exists())
                .andExpect(jsonPath("$.data.contentFileName").exists())
                .andExpect(jsonPath("$.data.publishStatus").exists())
                .andExpect(jsonPath("$.data.kbSyncStatus").exists());
    }

    @Test
    @DisplayName("GET /{id} 不存在")
    void api010_getMissing() throws Exception
    {
        when(bizEpidemicTreatmentStandardService.selectBizEpidemicTreatmentStandardById(999999L)).thenReturn(null);
        mockMvc.perform(get("/epidemicTreatment/standard/999999"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("PUT 修改成功")
    void api011_put() throws Exception
    {
        when(bizEpidemicTreatmentStandardService.updateBizEpidemicTreatmentStandard(any())).thenReturn(1);
        BizEpidemicTreatmentStandard body = sample(8L);
        mockMvc.perform(put("/epidemicTreatment/standard")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(body)))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("PUT 已发布拒绝")
    void api012_putPublished() throws Exception
    {
        when(bizEpidemicTreatmentStandardService.updateBizEpidemicTreatmentStandard(any()))
                .thenThrow(new ServiceException("仅「未发布」状态允许编辑"));
        BizEpidemicTreatmentStandard body = sample(8L);
        mockMvc.perform(put("/epidemicTreatment/standard")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(body)))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(500));
    }

    @Test
    @DisplayName("DELETE 未同步可删")
    void api013_delete() throws Exception
    {
        when(bizEpidemicTreatmentStandardService.deleteBizEpidemicTreatmentStandardByIds(any())).thenReturn(1);
        mockMvc.perform(delete("/epidemicTreatment/standard/7"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("DELETE 已发布禁止")
    void api014_deletePublished() throws Exception
    {
        when(bizEpidemicTreatmentStandardService.deleteBizEpidemicTreatmentStandardByIds(any()))
                .thenThrow(new ServiceException("已发布的数据不可删除，请先下架"));
        mockMvc.perform(delete("/epidemicTreatment/standard/7"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(500));
    }

    @Test
    @DisplayName("DELETE 未发布已同步（Service 内置清 kb）")
    void api015_deleteSynced() throws Exception
    {
        when(bizEpidemicTreatmentStandardService.deleteBizEpidemicTreatmentStandardByIds(any())).thenReturn(1);
        mockMvc.perform(delete("/epidemicTreatment/standard/71"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("POST syncKb")
    void api016_syncKb() throws Exception
    {
        when(bizEpidemicTreatmentStandardService.syncKb(11L)).thenReturn(1);
        mockMvc.perform(post("/epidemicTreatment/standard/syncKb/11"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("POST syncKb 非法状态")
    void api017_syncKbFail() throws Exception
    {
        when(bizEpidemicTreatmentStandardService.syncKb(12L)).thenThrow(new ServiceException("仅「未发布且未同步」可操作同步（未对接知识库服务）"));
        mockMvc.perform(post("/epidemicTreatment/standard/syncKb/12"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(500));
    }

    @Test
    @DisplayName("POST removeKb")
    void api018_removeKb() throws Exception
    {
        when(bizEpidemicTreatmentStandardService.removeKb(13L)).thenReturn(1);
        mockMvc.perform(post("/epidemicTreatment/standard/removeKb/13"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("POST publish")
    void api019_publish() throws Exception
    {
        when(bizEpidemicTreatmentStandardService.publish(14L)).thenReturn(1);
        mockMvc.perform(post("/epidemicTreatment/standard/publish/14"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("POST publish 未同步禁止")
    void api020_publishFail() throws Exception
    {
        when(bizEpidemicTreatmentStandardService.publish(15L)).thenThrow(new ServiceException("仅「未发布且已同步」可发布"));
        mockMvc.perform(post("/epidemicTreatment/standard/publish/15"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(500));
    }

    @Test
    @DisplayName("POST offline")
    void api021_offline() throws Exception
    {
        when(bizEpidemicTreatmentStandardService.offline(16L)).thenReturn(1);
        mockMvc.perform(post("/epidemicTreatment/standard/offline/16"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("POST offline 非已发布禁止")
    void api022_offlineFail() throws Exception
    {
        when(bizEpidemicTreatmentStandardService.offline(17L)).thenThrow(new ServiceException("仅「已发布」可下架"));
        mockMvc.perform(post("/epidemicTreatment/standard/offline/17"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(500));
    }

    private static String repeat(char c, int n)
    {
        char[] a = new char[n];
        java.util.Arrays.fill(a, c);
        return new String(a);
    }

    private static BizEpidemicTreatmentStandard sample(Long id)
    {
        BizEpidemicTreatmentStandard r = new BizEpidemicTreatmentStandard();
        r.setId(id);
        r.setStandardName("疫");
        r.setStandardType("001013");
        r.setIntroduction("简介");
        r.setContentFileUrl("http://localhost/f");
        r.setContentFilePath(Constants.RESOURCE_PREFIX + "/upload/2026/a.pdf");
        r.setContentFileName("a.pdf");
        r.setPublishStatus(0);
        r.setKbSyncStatus(0);
        return r;
    }
}
