package com.ruoyi.web.modules.architecture.service.impl;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

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 com.ruoyi.common.constant.Constants;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.web.modules.architecture.domain.BizEquipmentWorkStandard;
import com.ruoyi.web.modules.architecture.mapper.BizEquipmentWorkStandardMapper;
import com.ruoyi.web.modules.architecture.support.EquipmentWorkStandardTypeValidator;
import com.ruoyi.web.kb.support.KbApiProperties;
import com.ruoyi.web.kb.service.KnowledgeBaseClient;

/**
 * SS-BZ-UT-013～020（Mapper Mock）
 */
@ExtendWith(MockitoExtension.class)
@DisplayName("BizEquipmentWorkStandardServiceImpl")
class BizEquipmentWorkStandardServiceImplTest
{

    @Mock
    private BizEquipmentWorkStandardMapper mapper;

    @Mock
    private EquipmentWorkStandardTypeValidator equipmentWorkStandardTypeValidator;

    @Mock
    private KnowledgeBaseClient knowledgeBaseClient;

    @Mock
    private KbApiProperties kbApiProperties;

    @InjectMocks
    private BizEquipmentWorkStandardServiceImpl service;

    @Test
    @DisplayName("SS-BZ-UT-013 修改已发布抛业务异常")
    void ut013_updatePublishedThrows()
    {
        BizEquipmentWorkStandard db = baseRow();
        db.setId(9L);
        db.setPublishStatus(1);
        db.setKbSyncStatus(1);
        when(mapper.selectBizEquipmentWorkStandardById(9L)).thenReturn(db);

        BizEquipmentWorkStandard incoming = baseRow();
        incoming.setId(9L);
        incoming.setStandardName("新的标准名称一二三");

        assertThrows(ServiceException.class, () -> service.updateBizEquipmentWorkStandard(incoming));
        verify(mapper, never()).updateBizEquipmentWorkStandard(any());
    }

    @Test
    @DisplayName("SS-BZ-UT-014 同步成功写 kb_doc_id（file_id）")
    void ut014_syncKbUpdatesState()
    {
        BizEquipmentWorkStandard db = baseRow();
        db.setId(3L);
        db.setPublishStatus(0);
        db.setKbSyncStatus(0);
        when(mapper.selectBizEquipmentWorkStandardById(3L)).thenReturn(db);
        when(kbApiProperties.getFileUrlBase()).thenReturn("");
        when(knowledgeBaseClient.uploadFileByUrl(eq("http://localhost/f"), eq("设备实施作业标准"), eq("设")))
                .thenReturn("KB-DOC-3");
        when(mapper.updateBizEquipmentWorkStandard(any())).thenReturn(1);

        assertEquals(1, service.syncKb(3L));

        verify(mapper).updateBizEquipmentWorkStandard(argThat(r ->
                r.getKbSyncStatus() == 1 && "KB-DOC-3".equals(r.getKbDocId())));
    }

    @Test
    @DisplayName("SS-BZ-UT-015 同步失败：Mapper 返回 0")
    void ut015_syncKbMapperReturnsZero()
    {
        BizEquipmentWorkStandard db = baseRow();
        db.setId(4L);
        db.setPublishStatus(0);
        db.setKbSyncStatus(0);
        when(mapper.selectBizEquipmentWorkStandardById(4L)).thenReturn(db);
        when(kbApiProperties.getFileUrlBase()).thenReturn("");
        when(knowledgeBaseClient.uploadFileByUrl(eq("http://localhost/f"), eq("设备实施作业标准"), anyString()))
                .thenReturn("KB-DOC-4");
        when(mapper.updateBizEquipmentWorkStandard(any())).thenReturn(0);

        assertEquals(0, service.syncKb(4L));
        verify(mapper).updateBizEquipmentWorkStandard(any());
    }

    @Test
    @DisplayName("SS-BZ-UT-016 已同步禁止修改")
    void ut016_updateWhenSyncedRejected()
    {
        BizEquipmentWorkStandard db = baseRow();
        db.setId(10L);
        db.setPublishStatus(0);
        db.setKbSyncStatus(1);
        db.setKbDocId("LOCAL-10");
        when(mapper.selectBizEquipmentWorkStandardById(10L)).thenReturn(db);

        BizEquipmentWorkStandard incoming = baseRow();
        incoming.setId(10L);
        incoming.setIntroduction("改简介");
        assertThrows(ServiceException.class, () -> service.updateBizEquipmentWorkStandard(incoming));
        verify(mapper, never()).updateBizEquipmentWorkStandard(any());
    }

    @Test
    @DisplayName("SS-BZ-UT-017 下架成功")
    void ut017_offline()
    {
        BizEquipmentWorkStandard db = baseRow();
        db.setId(20L);
        db.setPublishStatus(1);
        db.setKbSyncStatus(1);
        db.setKbDocId("REAL-KB-DOC");
        when(mapper.selectBizEquipmentWorkStandardById(20L)).thenReturn(db);
        when(mapper.updateBizEquipmentWorkStandard(any())).thenReturn(1);

        assertEquals(1, service.offline(20L));

        verify(mapper).updateBizEquipmentWorkStandard(argThat(r ->
                r.getPublishStatus() == 0
                        && r.getKbSyncStatus() == 1
                        && "REAL-KB-DOC".equals(r.getKbDocId())
                        && r.getOfflineTime() != null));
    }

    @Test
    @DisplayName("SS-BZ-UT-018 移出成功")
    void ut018_removeKb()
    {
        BizEquipmentWorkStandard db = baseRow();
        db.setId(13L);
        db.setPublishStatus(0);
        db.setKbSyncStatus(1);
        db.setKbDocId("DOC-13");
        when(mapper.selectBizEquipmentWorkStandardById(13L)).thenReturn(db);
        when(mapper.updateBizEquipmentWorkStandard(any())).thenReturn(1);

        assertEquals(1, service.removeKb(13L));
        verify(knowledgeBaseClient).deleteFile("DOC-13");
        verify(mapper).updateBizEquipmentWorkStandard(argThat(r ->
                r.getKbSyncStatus() == 0 && r.getKbDocId() == null));
    }

    @Test
    @DisplayName("SS-BZ-UT-019 发布成功")
    void ut019_publish()
    {
        BizEquipmentWorkStandard db = baseRow();
        db.setId(14L);
        db.setPublishStatus(0);
        db.setKbSyncStatus(1);
        when(mapper.selectBizEquipmentWorkStandardById(14L)).thenReturn(db);
        when(mapper.updateBizEquipmentWorkStandard(any())).thenReturn(1);

        assertEquals(1, service.publish(14L));
        verify(mapper).updateBizEquipmentWorkStandard(argThat(r ->
                r.getPublishStatus() == 1 && r.getPublishTime() != null));
    }

    @Test
    @DisplayName("SS-BZ-UT-020 未同步保存仅本地")
    void ut020_updateUnsynced()
    {
        BizEquipmentWorkStandard db = baseRow();
        db.setId(11L);
        db.setPublishStatus(0);
        db.setKbSyncStatus(0);
        when(mapper.selectBizEquipmentWorkStandardById(11L)).thenReturn(db);
        when(mapper.updateBizEquipmentWorkStandard(any())).thenReturn(1);

        BizEquipmentWorkStandard incoming = baseRow();
        incoming.setId(11L);
        incoming.setIntroduction("仅本地");
        assertEquals(1, service.updateBizEquipmentWorkStandard(incoming));
        verify(mapper).updateBizEquipmentWorkStandard(argThat(r -> r.getKbSyncStatus() == 0));
    }

    @Test
    @DisplayName("非法状态同步应抛异常")
    void syncKbWhenAlreadySyncedThrows()
    {
        BizEquipmentWorkStandard db = baseRow();
        db.setId(5L);
        db.setPublishStatus(0);
        db.setKbSyncStatus(1);
        when(mapper.selectBizEquipmentWorkStandardById(5L)).thenReturn(db);

        assertThrows(ServiceException.class, () -> service.syncKb(5L));
        verify(mapper, never()).updateBizEquipmentWorkStandard(any());
    }

    @Test
    @DisplayName("删除：非未发布状态拒绝")
    void deleteRejectsNonDraftPublishStatus()
    {
        BizEquipmentWorkStandard db = baseRow();
        db.setId(30L);
        db.setPublishStatus(2);
        db.setKbSyncStatus(0);
        when(mapper.selectBizEquipmentWorkStandardById(30L)).thenReturn(db);

        assertThrows(ServiceException.class, () -> service.deleteBizEquipmentWorkStandardByIds(new Long[] { 30L }));
        verify(mapper, never()).deleteBizEquipmentWorkStandardById(anyLong());
    }

    private static BizEquipmentWorkStandard baseRow()
    {
        BizEquipmentWorkStandard r = new BizEquipmentWorkStandard();
        r.setStandardName("设");
        r.setStandardType("001007");
        r.setIntroduction("");
        r.setContentFileUrl("http://localhost/f");
        r.setContentFilePath(Constants.RESOURCE_PREFIX + "/upload/2026/a.pdf");
        r.setContentFileName("a.pdf");
        return r;
    }
}
