package com.izouma.jmrh.repo;

import com.izouma.jmrh.domain.OrgInfo;
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 javax.transaction.Transactional;
import java.time.LocalDateTime;
import java.util.Map;

public interface OrgInfoRepo extends JpaRepository<OrgInfo, Long>, JpaSpecificationExecutor<OrgInfo> {
    @Modifying
    @Transactional
    @Query(value = "update org_info set state =:#{#orgInfo.state} where id=:#{#orgInfo.id}", nativeQuery = true)
    int updateStateById(OrgInfo orgInfo);

    @Query(value = "SELECT*FROM (SELECT product.id id,name,created_at createdAt, 1 as stype, url pic,description needInfo from product left join pic on product.id = product_pic where state = 1 and org_info_id =?1 GROUP BY product.id UNION all " +
            "SELECT art_product.id id,name,created_at createdAt, 2 as stype, url pic,description needInfo from art_product left join pic on art_product.id = art_product_pic where state = 1 and org_info_id =?1 GROUP BY art_product.id  UNION all " +
            "SELECT tresource.id id,name,created_at createdAt, 3 as stype,url pic,description needInfo from tresource left join pic on tresource.id = res_pic where state = 1 and org_info_id =?1 GROUP BY tresource.id  UNION all " +
            "SELECT id,name,created_at createdAt, 4 as stype ,pic,need_info needInfo from product_need where state = 1 and org_info_id =?1 UNION all " +
            "SELECT id,name,created_at createdAt, 5 as stype ,pic,need_info needInfo from artNeed where state = 1 and org_info_id =?1 UNION all " +
            "SELECT id,name,created_at createdAt, 6 as stype ,pic,need_info needInfo from  financing_needs where state = 1 and org_info_id =?1) tep", countQuery =
            "SELECT id,name,created_at createdAt from product where state = 1 and org_info_id =?1 UNION all " +
                    "SELECT id,name,created_at createdAt from art_product where state = 1 and org_info_id =?1 UNION all " +
                    "SELECT id,name,created_at createdAt from tresource where state = 1 and org_info_id =?1 UNION all " +
                    "SELECT id,name,created_at createdAt from product_need where state = 1 and org_info_id =?1 UNION all " +
                    "SELECT id,name,created_at createdAt from are_need where state = 1 and org_info_id =?1 UNION all " +
                    "SELECT id,name,created_at createdAt from  financing_needs where state = 1 and org_info_id =?1", nativeQuery = true)
    Page<Map<String, Object>> listSupplyDemand(Long id, Pageable pageable);

    long countByCreatedAtBetween(LocalDateTime start, LocalDateTime end);

}