/*
 * Copyright (c) 2023 codvision.com All Rights Reserved.
 */

package com.codvision.webcore.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.codvision.webcore.service.IBaseService;
import com.codvision.webcore.util.PageUtil;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;

/**
 * 自定义服务实现
 *
 * @author lingee
 * @date 2023/7/21
 */
public class BaseServiceImpl<M extends BaseMapper<T>, T, V> extends ServiceImpl<M, T> implements IBaseService<T, V> {

    @Override
    public IPage<V> getBasePage(IPage<T> page, Wrapper<T> wrapper) {
        IPage<T> pageResult = this.page(page, wrapper);
        List<V> voList = BeanUtil.copyToList(pageResult.getRecords(), getVClass());
        return PageUtil.convertPage(pageResult, voList);
    }

    private Class<V> getVClass() {
        Type type = getClass().getGenericSuperclass();
        if (!(type instanceof ParameterizedType)) {
            throw new IllegalStateException("Type must be a parameterized type");
        }
        ParameterizedType parameterizedType = (ParameterizedType) type;
        // 获取泛型的具体类型  这里是单泛型
        Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
        if (null == actualTypeArguments || actualTypeArguments.length < 1) {
            throw new IllegalStateException("Number of type arguments must be 1");
        }
        return (Class<V>) actualTypeArguments[2];
    }
}
