/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.youchain.businessdata.repository;

import com.youchain.businessdata.domain.Task;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;

import java.util.List;
import java.util.Set;

/**
 * @author houjianlan
 * @website https://eladmin.vip
 * @date 2023-08-16
 **/
public interface TaskRepository extends JpaRepository<Task, Long>, JpaSpecificationExecutor<Task> {
    /**
     * 根据出库单明细查询未完成的Task集合
     *
     * @param pickDetailId
     * @return
     */
    @Query("from Task t where t.pickDetail.id =:pickDetailId and t.planQty > t.moveQty")
    List<Task> findByPickNotAllTask(Long pickDetailId);

    /**
     * 根据出库单明细查询已完成的Task集合
     *
     * @param pickDetailId
     * @return
     */
    @Query("from Task t where t.pickDetail.id =:pickDetailId and t.planQty = t.moveQty")
    List<Task> findByPickAllTask(Long pickDetailId);

    @Query(value = "from Task t where t.agvTask.id =:agvTaskId")
    List<Task> findByAgvTaskId(Long agvTaskId);

    /**
     * 根据asnDetailIds查询任务
     *
     * @param asnDetailIds
     * @return
     */
    @Query(value = " FROM Task t WHERE t.asnDetail.id in :asnDetailIds ")
    List<Task> findByAsnDetailTask(Set asnDetailIds);

    /**
     * 根据pickId查询未拣货的任务
     *
     * @param pickId
     * @return
     */
    @Query(value = " FROM Task t WHERE t.pickDetail.pick.id=?1 and t.taskType='PICK' and t.planQty>t.moveQty ")
    List<Task> findByNotPickTask(Long pickId);

    @Query(value = " select count(t.id) FROM Task t WHERE t.srcStock.code=:stockCode and t.taskType='PICK' and t.taskStatus not in ('FINISH','CANCEL')   ")
    int existsByStock(String stockCode);

    @Query(value = " from Task t WHERE t.taskType='PICK' and t.taskStatus='ARRIVED' and t.srcStock.code=:srcStockCode ")
    Task findBySrcStockCode(String srcStockCode);

}
