package cn.iselab.mooctest.user.mapper;

import cn.iselab.mooctest.user.model.User;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;

/**
 * @author sean
 * @date 2018-03-04.
 */
public interface UserMapper {

    @Select("SELECT * FROM user WHERE id = #{id}")
    User findById(@Param("id")Long id);

    @Select("SELECT * FROM user WHERE email = #{email}")
    User findByEmail(String email);

    @Select("SELECT * FROM user WHERE mobile = #{mobile}")
    User findByMobile(String mobile);

    @Insert("INSERT INTO user(name, password, email, mobile, school ) VALUES(#{name}, #{password}, #{email}, #{mobile}, #{school})")
    void insert(User user);

    @Update("UPDATE user SET name=#{name} WHERE id=#{id}")
    void updateName(User user);

    @Update("UPDATE user SET school=#{school}, province=#{province}, city=#{city} WHERE id=#{id}")
    void updateAddress(User user);

    @Update("UPDATE user SET email=#{email} WHERE id=#{id}")
    void updateEmail(User user);

    @Update("UPDATE user SET mobile=#{mobile} WHERE id=#{id}")
    void updateMobile(User user);

    @Update("UPDATE user SET photo_url=#{photoUrl} WHERE id=#{id}")
    void updatePhotoUrl(User user);

    @Update("UPDATE user SET password=#{password} WHERE id=#{id}")
    void updatePassword(User user);

    @Update("UPDATE user SET availability=#{availability} WHERE id=#{id}")
    void updateAvailability(User user);

    @Select("SELECT * FROM user WHERE name LIKE concat('%',#{username},'%') or email LIKE concat('%',#{username},'%')" +
            "or school LIKE concat('%',#{username},'%') or province LIKE concat('%',#{username},'%') or city LIKE concat('%',#{username},'%')" +
            "or mobile LIKE concat('%',#{username},'%')")
    List<User> findByFuzzyName(String name);

    @Select("SELECT * FROM user WHERE email LIKE concat('%',#{username},'%')")
    List<User> findByFuzzyEmail(String email);

    @Select("SELECT * FROM user WHERE name LIKE concat('%',#{keyword},'%') OR email LIKE CONCAT('%',#{keyword},'%')")
    List<User> findByFuzzyNameOrEmail(String keyword);

    @Select("SELECT * FROM user WHERE id in (${userIds})")
    List<User> findAll(@Param("userIds") String userIds);

    @Select({
            "<script>",
            "select",
            "*",
            "from user",
            "where id in",
            "<foreach collection='userIds' item='id' open='(' separator=',' close=')'>",
            "#{id}",
            "</foreach>",
            "</script>"
    })
    List<User> findAllUsers(@Param("userIds") List<Long> userIds);
}
