package cn.palmte.work.model;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import javax.transaction.Transactional;
import java.util.Date;
import java.util.List;

public interface ProjectRepository extends JpaRepository<Project,Integer> {

    @Query(value = "select * from project where name = ?1", nativeQuery = true)
    Project findByProjectName(String projectName);

    @Query(value = "select * from project where project_no = ?1", nativeQuery = true)
    Project findByProjectNo(String projectNo);

    @Query(value = "select * from project where dept_id = ?1", nativeQuery = true)
    List<Project> findByDeptId(int deptId);

    @Query(value = "select * from project where creator_id = ?1 and end_date >= ?2 and start_date <= ?2", nativeQuery = true)
    List<Project> findByCreator(int id, Date date);

    @Modifying
    @Transactional(rollbackOn = Exception.class)
    @Query(value = "update project set project_no = ?1 where id = ?2", nativeQuery = true)
    int updateProjectNo(String projectNo, int id);

    @Query(value = "SELECT p.*, FORMAT(p.contract_amount,2) as contractRound, FORMAT(p.huazhi_product_amount,2) as huazhiRound, FORMAT(p.huizhi_product_amount,2) as huizhiRound, FORMAT(p.huasan_product_amount,2) as huasanRound, FORMAT(p.ziguang_other_amount,2) as ziguangRound, FORMAT(p.gross_profit,2) as grossProfitRound, FORMAT(p.gross_profit_margin,2) as grossProfitMarginRound, FORMAT(p.advance_interest_amount,2) as advanceInterestAmountRound, FORMAT(p.advance_peak_amount,2) as advancePeakAmountRound from project p where id = ?1 limit 1", nativeQuery = true)
    Project findById(int id);


    @Query(value = "select * from project where approve_id = ?", nativeQuery = true)
    List<Project> findByApproveId(int adminId);

    @Modifying
    @Transactional(rollbackOn = Exception.class)
    @Query(value = "update project set approve_id=?, approve_name=? where approve_id = ?", nativeQuery = true)
    int batchUpdateApprove(int targetAdminId, String targetAdminName, int adminId);

  /**
   * 查询预算通过的项目
   */
    @Query(value = "select * from project where (`status` > 5 or (`status` = 5 and approve_status_budget = 2)) " +
            "  and (`project_no` like concat('%', :q, '%') or `name` like concat('%', :q, '%'))",
           nativeQuery = true)
    List<Project> findBudgetPassedProjects(@Param("q") String query);

}
