package cn.edu.whu.boot.allocation.mapper;

import cn.edu.whu.boot.allocation.entities.TaskCell;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Repository;

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

@Repository
public interface TaskCellMapper {
    @Select("SELECT * FROM task_cell WHERE task_id = #{taskId}")
    @Results(
            {
                    @Result(property = "taskId", column = "task_id")
            }
    )
    List<TaskCell> findByTaskId(@Param("taskId") int taskId);

    @Select("SELECT a.geojson FROM task_cell AS a WHERE a.geohash IN " +
            "(SELECT DISTINCT b.cell_geohash FROM task_user_cell AS b " +
            "WHERE b.task_id = #{taskId} AND b.user_id = #{userId})")
    List<String> findGeojsonByTaskIdAndUserId(@Param("taskId") int taskId, @Param("userId") int userId);

    @Select("SELECT geojson FROM task_cell WHERE task_id = #{taskId} AND geohash = #{geohash}")
    String findGeojsonByTaskIdAndGeohash(@Param("taskId") int taskId, @Param("geohash") String geohash);

    @Insert({
            "<script>",
            "INSERT INTO task_cell(task_id, geohash, geojson)",
            "VALUES" +
                    "<foreach item='item' index='item' collection='list' open='' separator=',' close=''>" +
                    "(" +
                    "#{item.taskId}, #{item.geohash}, #{item.geojson}",
            ")" +
                    "</foreach>",
            "</script>"})
    void insertForeach(@Param("list") List<TaskCell> list);

    @Insert("INSERT INTO task_cell(task_id, geohash, geojson) VALUES(#{taskId}, #{geohash}, #{geojson})")
    void insert(TaskCell taskCell);

    @Delete("DELETE FROM task_cell WHERE task_id = #{taskId}")
    void deleteByTaskId(@Param("taskId") int taskId);

    @Select("SELECT min(st_xmin(st_geomfromgeohash(substring(geohash, 1, length(geohash) - 12), 4490))) as xmin," +
            " max(st_xmax(st_geomfromgeohash(substring(geohash, 1, length(geohash) - 12), 4490))) as xmax, " +
            " min(st_ymin(st_geomfromgeohash(substring(geohash, 1, length(geohash) - 12), 4490))) as ymin, " +
            " max(st_ymax(st_geomfromgeohash(substring(geohash, 1, length(geohash) - 12), 4490))) as ymax " +
            " FROM task_cell WHERE task_id = #{taskId}")
    Map<String,Object> getCoordinateRange(@Param("taskId") Integer taskId);
}
