package com.lideeyunji.service.system.mapper;

import com.github.yulichang.base.MPJBaseMapper;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.lideeyunji.service.system.controller.vo.oauth2.client.OAuth2ClientPageReqVO;
import com.lideeyunji.service.system.entity.DictDataDO;
import com.lideeyunji.service.system.entity.OAuth2ClientDO;
import com.lideeyunji.tool.framework.common.pojo.PageResult;
import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface OAuth2ClientJoinMapper extends MPJBaseMapper<OAuth2ClientDO> {

    /**
     * 分页查询（关联字典表）
     */
    default PageResult<OAuth2ClientDO> selectPage(OAuth2ClientPageReqVO reqVO) {
        MPJLambdaWrapper<OAuth2ClientDO> wrapper = buildQueryWrapper(reqVO);

        com.baomidou.mybatisplus.extension.plugins.pagination.Page<OAuth2ClientDO> page =
                new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(
                        reqVO.getPageNo(),
                        reqVO.getPageSize()
                );

        com.baomidou.mybatisplus.extension.plugins.pagination.Page<OAuth2ClientDO> resultPage =
                selectJoinPage(page, OAuth2ClientDO.class, wrapper);

        return new PageResult<>(resultPage.getRecords(), resultPage.getTotal());
    }


    default MPJLambdaWrapper<OAuth2ClientDO> buildQueryWrapper(OAuth2ClientPageReqVO reqVO) {
        MPJLambdaWrapper<OAuth2ClientDO> wrapper = new MPJLambdaWrapper<OAuth2ClientDO>()
                .selectAll(OAuth2ClientDO.class)
                .leftJoin(DictDataDO.class, on -> on
                        .eq(DictDataDO::getValue, OAuth2ClientDO::getCategory)
                        .eq(DictDataDO::getDictType, "app_category"));

        applyQueryConditions(wrapper, reqVO);

        wrapper.orderByAsc(DictDataDO::getSort)
                .orderByDesc(OAuth2ClientDO::getId);

        return wrapper;
    }

    default void applyQueryConditions(MPJLambdaWrapper<OAuth2ClientDO> wrapper, OAuth2ClientPageReqVO reqVO) {
        if (reqVO.getName() != null && !reqVO.getName().isEmpty()) {
            wrapper.like(OAuth2ClientDO::getName, reqVO.getName());
        }
        if (reqVO.getStatus() != null) {
            wrapper.eq(OAuth2ClientDO::getStatus, reqVO.getStatus());
        }
        if (reqVO.getIds() != null && !reqVO.getIds().isEmpty()) {
            wrapper.in(OAuth2ClientDO::getId, reqVO.getIds());
        }
    }
}
