package com.njcn.rdms.module.system.dal.mysql.dict;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.njcn.rdms.framework.common.pojo.PageResult;
import com.njcn.rdms.module.system.controller.admin.dict.vo.data.DictDataPageReqVO;
import com.njcn.rdms.module.system.dal.dataobject.dict.DictDataDO;
import jakarta.validation.constraints.NotBlank;
import org.apache.ibatis.builder.MapperBuilderAssistant;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;

import java.lang.reflect.Field;
import java.util.Locale;

import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;

class DictDataMapperTest {

    @BeforeAll
    static void initMyBatisPlusTableInfo() {
        TableInfoHelper.initTableInfo(new MapperBuilderAssistant(new MybatisConfiguration(), ""), DictDataDO.class);
    }

    @Test
    @SuppressWarnings({"unchecked", "rawtypes"})
    void selectPage_shouldOrderBySortAscForSingleDictType() {
        DictDataMapper mapper = mock(DictDataMapper.class, invocation -> invocation.callRealMethod());
        DictDataPageReqVO reqVO = new DictDataPageReqVO();
        reqVO.setDictType("sys_common_status");
        doReturn(PageResult.empty()).when(mapper).selectPage(eq(reqVO), any(Wrapper.class));

        mapper.selectPage(reqVO);

        ArgumentCaptor<Wrapper<DictDataDO>> wrapperCaptor = ArgumentCaptor.forClass(Wrapper.class);
        verify(mapper).selectPage(eq(reqVO), wrapperCaptor.capture());
        String sqlSegment = wrapperCaptor.getValue().getSqlSegment().toLowerCase(Locale.ROOT);
        assertTrue(sqlSegment.contains("dict_type"));
        assertTrue(sqlSegment.contains("order by sort asc,id asc"));
        assertFalse(sqlSegment.contains("dict_type desc"));
        assertFalse(sqlSegment.contains("sort desc"));
    }

    @Test
    void pageReqVO_shouldRequireDictType() throws NoSuchFieldException {
        Field dictTypeField = DictDataPageReqVO.class.getDeclaredField("dictType");

        NotBlank notBlank = dictTypeField.getAnnotation(NotBlank.class);

        assertNotNull(notBlank);
        assertEquals("字典类型不能为空", notBlank.message());
    }

}
