package com.yuchen.saas.park.service.mapper.door.config;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yuchen.saas.park.api.commons.domain.DoorAccessControlConfigEntry;
import com.yuchen.saas.park.api.commons.domain.DoorAccessControlConfigTarget;
import com.yuchen.saas.park.api.commons.enums.DoorAccessControlConfigType;
import com.yuchen.saas.park.api.entity.door.config.DoorAccessControlConfigIssueTask;
import com.yuchen.saas.park.service.mapper.domain.config.details.DoorAccessControlConfigDetailsCondition;
import com.yuchen.saas.park.service.mapper.domain.config.details.DoorAccessControlConfigDetailsRO;
import lombok.val;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;

import javax.annotation.Nullable;
import javax.validation.constraints.Positive;
import java.util.List;
import java.util.Optional;

import static java.util.Optional.ofNullable;

@Mapper
public interface DoorAccessControlConfigIssueTaskRepository extends BaseMapper<DoorAccessControlConfigIssueTask> {
    default List<DoorAccessControlConfigIssueTask> listByTarget(DoorAccessControlConfigTarget target) {
        return this.listByTargetCondition(target, null, null);
    }

    default List<DoorAccessControlConfigIssueTask> listByTargetCondition(DoorAccessControlConfigTarget target, @Nullable DoorAccessControlConfigType type, @Nullable Long configId) {
        // 创建一个lambdaQuery对象
        val query = Wrappers.<DoorAccessControlConfigIssueTask>lambdaQuery()
          .eq(DoorAccessControlConfigIssueTask::getUserId, target.getUserId())
          .eq(DoorAccessControlConfigIssueTask::getDoorAccessControlId, target.getDoorAccessControlId());
        ofNullable(type).ifPresent(o -> query.eq(DoorAccessControlConfigIssueTask::getType, o.getCode()));
        ofNullable(configId).filter(o -> o > 0).ifPresent(o -> query.eq(DoorAccessControlConfigIssueTask::getConfigId, o));
        // 返回查询结果，如果为空则返回空列表
        return ofNullable(this.selectList(query)).orElse(List.of());
    }

    default List<DoorAccessControlConfigIssueTask> listByTargetAndType(DoorAccessControlConfigTarget target, DoorAccessControlConfigType type) {
        return this.listByTargetCondition(target, type, null);
    }

    default Optional<DoorAccessControlConfigIssueTask> getByTargetAndEntry(DoorAccessControlConfigTarget target, DoorAccessControlConfigEntry entry) {
        return this.listByTargetCondition(target, entry.getType(), entry.getConfigId()).stream().findFirst();
    }

    @Nullable
    List<DoorAccessControlConfigIssueTask> listUnprocessed(@Positive int size);

    IPage<DoorAccessControlConfigDetailsRO> pageForDoorAccessControlConfigDetails(IPage<?> page, @Param("o") DoorAccessControlConfigDetailsCondition o);
}
