package com.ai.da.mapper.primary;

import com.ai.da.common.config.mybatis.plus.CommonMapper;
import com.ai.da.mapper.primary.entity.CollectionSort;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;

public interface CollectionSortMapper extends CommonMapper<CollectionSort> {
    /*@Update("UPDATE collection_sort SET sort = sort + 1 " +
            "WHERE parent_id = #{parentId} " +
            "AND relation_type != 'Design' " +
            "AND sort > #{originalSort}")
    void increaseGenerateSortAbove(
            @Param("parentId") Long parentId,
            @Param("relationType") String relationType,
            @Param("originalSort") int originalSort
    );*/
    @Update("UPDATE collection_sort SET sort = sort + 1 " +
            "WHERE parent_id = #{parentId} " +
            "AND relation_type != 'Design' " +
            "AND sort > #{originalSort} " +
            "ORDER BY sort DESC")  // 关键：按排序号倒序更新
    void increaseGenerateSortAbove(
            @Param("parentId") Long parentId,
            @Param("originalSort") int originalSort
    );

    @Select("SELECT * FROM collection_sort WHERE parent_id IN (SELECT id FROM collection_sort WHERE relation_id = #{relationId})")
    List<CollectionSort> queryCollectionSortsIsNotDesignByUserLikeRelationId(@Param("relationId") Long relationId);

    @Update({
            "<script>",
            "UPDATE collection_sort",
            "SET sort = sort - 1",
            "WHERE project_id = #{projectId}",
            "AND sort > #{deletedSort}",
            "<if test='parentId != null'>",
            "AND parent_id = #{parentId}",
            "</if>",
            "<if test='parentId == null'>",
            "AND parent_id IS NULL",
            "</if>",
            "</script>"
    })
    void decrementSortAfterDelete(@Param("projectId") Long projectId,
                                  @Param("parentId") Long parentId,
                                  @Param("deletedSort") int deletedSort);

}
