package com.kym.service.miniapp.impl;

import cn.hutool.core.util.ClassUtil;
import cn.hutool.core.util.ReflectUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kym.common.IQuery;
import com.kym.common.utils.CommUtil;
import com.kym.entity.common.PageBean;
import com.kym.entity.miniapp.DataDict;
import com.kym.mapper.miniapp.DataDictMapper;
import com.kym.service.miniapp.DataDictService;
import org.springframework.stereotype.Service;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.List;


/**
 * <p>
 * 数据字典 服务实现类
 * </p>
 *
 * @author zuy
 * @since 2023-08-13
 */
@Service
@DS("db-miniapp")
public class DataDictServiceImpl extends ServiceImpl<DataDictMapper, DataDict> implements DataDictService {


    @Override
    public Object list(IQuery<DataDict> query) {
//        PageHelper.startPage(query.pageNum, query.pageSize);
        List<DataDict> list = list();
        return new PageBean<>(list);
    }


    @Override
    public Object listV2(IQuery<DataDict> query) {
        QueryChainWrapper<DataDict> wrapper = getWrapper(query.query, DataDict.class);
        Long count = wrapper.count();
        List<DataDict> list = wrapper.list();
        return IQuery.newPageBean(count, list);
    }


    public <T> QueryChainWrapper<T> getWrapper(Object query, Class<T> clz) {
        QueryChainWrapper<T> wrapper = new QueryChainWrapper<>(clz);
        if (null == query) {
            return wrapper;
        }


        Field[] fields = ClassUtil.getDeclaredFields(query.getClass());
        if (!CommUtil.isEmptyOrNull(fields)) {
            for (Field field : fields) {
                int modifiers = field.getModifiers();
                if (Modifier.isFinal(modifiers) || Modifier.isStatic(modifiers)) {
                    continue;
                }
                Object fieldValue = ReflectUtil.getFieldValue(query, field);
                if (!CommUtil.isEmptyOrNull(fieldValue)) {
                    wrapper.eq(CommUtil.toDbColumn(field.getName()), fieldValue);
                }
            }
        }

        return wrapper;
    }
}
