package com.ruoyi.info.collection.controller;

import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.info.collection.domain.excel.CcdiAssetInfoExcel;
import com.ruoyi.info.collection.domain.excel.CcdiStaffFmyRelationExcel;
import com.ruoyi.info.collection.domain.vo.StaffFmyRelationImportSubmitResultVO;
import com.ruoyi.info.collection.domain.vo.StaffFmyRelationImportFailureVO;
import com.ruoyi.info.collection.service.ICcdiAssetInfoImportService;
import com.ruoyi.info.collection.service.ICcdiStaffFmyRelationImportService;
import com.ruoyi.info.collection.service.ICcdiStaffFmyRelationService;
import com.ruoyi.info.collection.utils.EasyExcelUtil;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockedStatic;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.mock.web.MockMultipartFile;

import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.List;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mockStatic;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;

@ExtendWith(MockitoExtension.class)
class CcdiStaffFmyRelationControllerTest {

    @InjectMocks
    private CcdiStaffFmyRelationController controller;

    @Mock
    private ICcdiStaffFmyRelationService relationService;

    @Mock
    private ICcdiStaffFmyRelationImportService relationImportService;

    @Mock
    private ICcdiAssetInfoImportService assetInfoImportService;

    @Test
    void importTemplate_shouldDownloadDualSheetTemplate() {
        try (MockedStatic<EasyExcelUtil> mocked = mockStatic(EasyExcelUtil.class)) {
            controller.importTemplate(null);

            mocked.verify(() -> EasyExcelUtil.importTemplateWithDictDropdown(
                    null,
                    CcdiStaffFmyRelationExcel.class,
                    "员工亲属关系信息",
                    CcdiAssetInfoExcel.class,
                    "亲属资产信息",
                    "员工亲属关系维护导入模板"
            ));
        }
    }

    @Test
    void importData_shouldErrorWhenBothSheetsAreEmpty() throws Exception {
        MockMultipartFile file = new MockMultipartFile(
                "file",
                "staff-family-empty.xlsx",
                "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                "empty".getBytes(StandardCharsets.UTF_8)
        );

        try (MockedStatic<EasyExcelUtil> mocked = mockStatic(EasyExcelUtil.class)) {
            mocked.when(() -> EasyExcelUtil.importExcel(any(InputStream.class), eq(CcdiStaffFmyRelationExcel.class), eq("员工亲属关系信息")))
                    .thenReturn(List.of());
            mocked.when(() -> EasyExcelUtil.importExcel(any(InputStream.class), eq(CcdiAssetInfoExcel.class), eq("亲属资产信息")))
                    .thenReturn(List.of());

            AjaxResult result = controller.importData(file);

            assertEquals(HttpStatus.ERROR, result.get(AjaxResult.CODE_TAG));
            assertEquals("至少需要一条数据", result.get(AjaxResult.MSG_TAG));
            verifyNoInteractions(relationService, assetInfoImportService);
        }
    }

    @Test
    void importData_shouldSubmitOnlyRelationTaskWhenOnlyRelationSheetHasRows() throws Exception {
        MockMultipartFile file = new MockMultipartFile(
                "file",
                "staff-family-relation.xlsx",
                "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                "relation".getBytes(StandardCharsets.UTF_8)
        );
        CcdiStaffFmyRelationExcel relationExcel = new CcdiStaffFmyRelationExcel();
        relationExcel.setPersonId("320101199001010011");
        StaffFmyRelationImportSubmitResultVO submitResult = new StaffFmyRelationImportSubmitResultVO();
        submitResult.setRelationTaskId("relation-task-1");
        when(relationService.importRelationWithAssets(List.of(relationExcel), List.of())).thenReturn(submitResult);

        try (MockedStatic<EasyExcelUtil> mocked = mockStatic(EasyExcelUtil.class)) {
            mocked.when(() -> EasyExcelUtil.importExcel(any(InputStream.class), eq(CcdiStaffFmyRelationExcel.class), eq("员工亲属关系信息")))
                    .thenReturn(List.of(relationExcel));
            mocked.when(() -> EasyExcelUtil.importExcel(any(InputStream.class), eq(CcdiAssetInfoExcel.class), eq("亲属资产信息")))
                    .thenReturn(List.of());

            AjaxResult result = controller.importData(file);

            assertEquals(HttpStatus.SUCCESS, result.get(AjaxResult.CODE_TAG));
            assertEquals("导入任务已提交,正在后台处理", result.get(AjaxResult.MSG_TAG));
            Object data = result.get(AjaxResult.DATA_TAG);
            assertEquals("relation-task-1", data.getClass().getMethod("getRelationTaskId").invoke(data));
            assertNull(data.getClass().getMethod("getAssetTaskId").invoke(data));
        }
    }

    @Test
    void importData_shouldSubmitTwoTasksWhenBothSheetsHaveRows() throws Exception {
        MockMultipartFile file = new MockMultipartFile(
                "file",
                "staff-family-both.xlsx",
                "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                "both".getBytes(StandardCharsets.UTF_8)
        );
        CcdiStaffFmyRelationExcel relationExcel = new CcdiStaffFmyRelationExcel();
        relationExcel.setPersonId("320101199001010012");
        CcdiAssetInfoExcel assetExcel = new CcdiAssetInfoExcel();
        assetExcel.setPersonId("320101199001010099");
        StaffFmyRelationImportSubmitResultVO submitResult = new StaffFmyRelationImportSubmitResultVO();
        submitResult.setRelationTaskId("relation-task-2");
        submitResult.setAssetTaskId("asset-task-2");
        when(relationService.importRelationWithAssets(List.of(relationExcel), List.of(assetExcel))).thenReturn(submitResult);

        try (MockedStatic<EasyExcelUtil> mocked = mockStatic(EasyExcelUtil.class)) {
            mocked.when(() -> EasyExcelUtil.importExcel(any(InputStream.class), eq(CcdiStaffFmyRelationExcel.class), eq("员工亲属关系信息")))
                    .thenReturn(List.of(relationExcel));
            mocked.when(() -> EasyExcelUtil.importExcel(any(InputStream.class), eq(CcdiAssetInfoExcel.class), eq("亲属资产信息")))
                    .thenReturn(List.of(assetExcel));

            AjaxResult result = controller.importData(file);

            assertEquals(HttpStatus.SUCCESS, result.get(AjaxResult.CODE_TAG));
            Object data = result.get(AjaxResult.DATA_TAG);
            assertEquals("relation-task-2", data.getClass().getMethod("getRelationTaskId").invoke(data));
            assertEquals("asset-task-2", data.getClass().getMethod("getAssetTaskId").invoke(data));
        }
    }

    @Test
    void getImportFailures_shouldReturnPagedRowsWithSheetAndRowInfo() {
        StaffFmyRelationImportFailureVO failure1 = new StaffFmyRelationImportFailureVO();
        failure1.setSheetName("员工亲属关系信息");
        failure1.setRowNum(2);
        failure1.setPersonId("A1");

        StaffFmyRelationImportFailureVO failure2 = new StaffFmyRelationImportFailureVO();
        failure2.setSheetName("员工亲属关系信息");
        failure2.setRowNum(3);
        failure2.setPersonId("A2");

        when(relationImportService.getImportFailures("task-1")).thenReturn(List.of(failure1, failure2));

        TableDataInfo result = controller.getImportFailures("task-1", 2, 1);

        assertEquals(2, result.getTotal());
        assertEquals(1, result.getRows().size());
        StaffFmyRelationImportFailureVO row = (StaffFmyRelationImportFailureVO) result.getRows().get(0);
        assertEquals("员工亲属关系信息", row.getSheetName());
        assertEquals(3, row.getRowNum());
        assertEquals("A2", row.getPersonId());
    }
}
