/*
*  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 me.zhengjie.modules.dm.information.repository;

import me.zhengjie.modules.dm.information.domain.DmInformation;
import me.zhengjie.modules.dm.information.service.dto.DmInformationDto;
import me.zhengjie.modules.dm.information.service.dto.DmInformationQueryCriteria;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import java.util.List;
import java.util.Map;

/**
* @website https://el-admin.vip
* @author xwx
* @date 2021-04-22
**/
public interface DmInformationRepository extends JpaRepository<DmInformation, Long>, JpaSpecificationExecutor<DmInformation> {

    @Modifying
    @Query(value = "update dm_information set task_id =:#{#resources.taskId} ,proc_inst_id =:#{#resources.procInstId} where id =:#{#resources.id} ",nativeQuery = true )
    void updateTask(@Param(value = "resources") DmInformation resources);

    @Query(value = "select GROUP_CONCAT(DISTINCT(approval_user)) as userIds from dm_information_approval where is_new = '1' and info_id = ?1 ",nativeQuery = true )
    Map<String,Object> selectInfoApproveUserNames(Long id);

    @Modifying
    @Query(value = "update dm_information set status = '00' ,approval_user = null,approval_remark=null where id = ?1 ",nativeQuery = true )
    void reset(Long id);

    @Query(value = "select status from dm_information where id = ?1",nativeQuery = true)
    String findSubmitBeforeStatus(Long id);

    @Query(value = "select a.*  from  dm_information a left join dm_information_approval b on a.id= b.info_id where b.is_new = 1 and  b.approval_user = ?1 and a.status = '00' group by a.id",
            countQuery = "select count(*) from (select a.* from dm_information a left join dm_information_approval b on a.id= b.info_id where b.is_new = 1 and  b.approval_user = ?1 and a.status = '00' group by a.id)",
            nativeQuery = true)
    Page<DmInformation> findAllDSP(String approval_user, Pageable pageable);
}