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

import com.njcn.rdms.framework.common.pojo.PageResult;
import com.njcn.rdms.framework.mybatis.core.mapper.BaseMapperX;
import com.njcn.rdms.framework.mybatis.core.query.LambdaQueryWrapperX;
import com.njcn.rdms.module.system.controller.admin.dict.vo.type.DictTypePageReqVO;
import com.njcn.rdms.module.system.dal.dataobject.dict.DictTypeDO;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Update;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;

@Mapper
public interface DictTypeMapper extends BaseMapperX<DictTypeDO> {

    default PageResult<DictTypeDO> selectPage(DictTypePageReqVO reqVO) {
        LambdaQueryWrapperX<DictTypeDO> queryWrapper = new LambdaQueryWrapperX<>();
        String typeKeyword = reqVO.getTypeKeyword();
        boolean hasName = StringUtils.hasText(reqVO.getName());
        boolean hasType = StringUtils.hasText(typeKeyword);
        if (hasName && hasType) {
            queryWrapper.and(wrapper -> wrapper.like(DictTypeDO::getName, reqVO.getName())
                    .or()
                    .like(DictTypeDO::getType, typeKeyword));
        } else {
            queryWrapper.likeIfPresent(DictTypeDO::getName, reqVO.getName())
                    .likeIfPresent(DictTypeDO::getType, typeKeyword);
        }
        queryWrapper.eqIfPresent(DictTypeDO::getStatus, reqVO.getStatus())
                .betweenIfPresent(DictTypeDO::getCreateTime, reqVO.getCreateTime())
                .orderByDesc(DictTypeDO::getId);
        return selectPage(reqVO, queryWrapper);
    }

    default DictTypeDO selectByType(String type) {
        return selectOne(DictTypeDO::getType, type);
    }

    default DictTypeDO selectByName(String name) {
        return selectOne(DictTypeDO::getName, name);
    }

    @Update("UPDATE system_dict_type SET deleted = 1, deleted_time = #{deletedTime} WHERE id = #{id}")
    void updateToDelete(@Param("id") Long id, @Param("deletedTime") LocalDateTime deletedTime);

}
