package com.td.boss.game.complayerland.repository;

import com.td.boss.common.repository.*;
import com.td.boss.game.complayerland.pojo.ComPlayerLand;
import com.td.boss.game.complayerland.vo.ComPlayerLandAndUserInfoVo;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Optional;

@Repository
public interface ComPlayerLandRepository extends CommonRepository<ComPlayerLand, Integer> {

    List<ComPlayerLand> findAllByUserId(String userId);


    @Query(value = "SELECT\n" +
            "a.user_id,\n" +
            "a.is_plant,\n" +
            "a.plant_start,\n" +
            "a.plant_mature,\n" +
            "DATE_ADD(a.plant_start,INTERVAL a.plant_mature DAY) AS mature_date,\n" +
            "b.address,\n" +
            "(CASE WHEN c.id IS NULL AND a.plant_steal = 1  THEN 1 ELSE 0 END) AS can_steal\n" +
            "FROM\n" +
            "com_player_land AS a \n" +
            "LEFT JOIN com_users AS b ON a.user_id = b.user_id\n" +
            "LEFT JOIN com_player_profit AS c ON c.user_id = :userId AND c.target_id = a.user_id AND a.config_land_id = c.land_id AND (  ( ISNULL(a.plant_flag) = 1 AND c.plant_flag = CONCAT(a.user_id,'or',a.config_land_id)) OR a.plant_flag = c.plant_flag )\n" +
            "WHERE NOT(a.user_id = :userId) AND is_lease = 1 AND is_plant = 1 AND a.plant_steal = 1 AND DATE_ADD(a.plant_start,INTERVAL a.plant_mature DAY) <= NOW()\n" +
            "AND DATE(a.lease_time) > DATE(NOW()) GROUP BY a.user_id,can_steal HAVING can_steal = 1  ", nativeQuery = true)
    List<Object> findAllIsStealComPlayerLandAndUserInfo(String userId,Pageable pageable);


    List<ComPlayerLand> findAllByUserIdAndIsLeaseAndIsPlant(String userId, Integer isLease, Integer isPlant);

    Optional<ComPlayerLand> findByUserIdAndConfigLandId(String userId, Integer landId);

    Optional<ComPlayerLand> findByConfigLandId(Integer landId);
}
