package com.jy.system.dao;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jy.framework.model.base.BaseDao;
import com.jy.framework.model.base.BaseIdPo;
import com.jy.framework.model.constants.CommonConstant;
import com.jy.framework.satoken.LoginContext;
import com.jy.system.mapper.SysDictTypeMapper;
import com.jy.system.model.dto.SysDictTypeSelectDto;
import com.jy.system.model.entity.SysDictType;
import com.jy.system.model.table.SysDictTypeTable;
import com.jy.system.model.vo.SysDictTypeVo;
import org.springframework.stereotype.Service;

@Service
public class SysDictTypeDao extends BaseDao<SysDictTypeMapper, SysDictType> {

    /**
     * 字典类型分页
     */
    public Page<SysDictTypeVo> getPage(SysDictTypeSelectDto dto) {
        SysDictTypeTable sdt = SysDictTypeTable.sdt;

        return sql(SysDictTypeVo.class)
                .select(
                        sdt.id,
                        sdt.code,
                        sdt.name,
                        sdt.remark,
                        sdt.builtin
                )
                .from(sdt)
                .where(
                        sdt.builtin.eq(LoginContext.isSupperAdmin() ? dto.getBuiltin() : CommonConstant.NO),
                        sdt.code.like(dto.getCode()),
                        sdt.name.like(dto.getName())
                )
                .orderBy(
                        sdt.id.desc()
                )
                .page(dto.getPage());
    }

    /**
     * 字典类型明细
     */
    public SysDictTypeVo getDetail(Long id) {
        SysDictTypeTable sdt = SysDictTypeTable.sdt;

        return sql(SysDictTypeVo.class)
                .select(
                        sdt.id,
                        sdt.code,
                        sdt.name,
                        sdt.remark,
                        sdt.builtin
                )
                .from(sdt)
                .where(sdt.id.eq(id))
                .one();
    }

    /**
     * 字典编码是否存在
     */
    public boolean codeExists(String code) {
        return lambdaQuery().eq(SysDictType::getCode, code).exists();
    }

    /**
     * 字典编码是否存在（排除id）
     */
    public boolean codeExists(String code, Long exclusionId) {
        return lambdaQuery().eq(SysDictType::getCode, code).ne(BaseIdPo::getId, exclusionId).exists();
    }

}
