package com.mobvista.apptag.mapper;

import com.mobvista.apptag.entity.User;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.*;

import java.util.List;

/**
 * @author wangjf
 */

public interface UserDao {

    @Insert("REPLACE INTO user(user_id,user_name,password,state,role,update_time,count) VALUES(#{userId},#{userName},#{password},#{state},#{role},#{updateTime},${count})")
    boolean save(User user);

    @Update("UPDATE user SET role = #{role}, update_time = #{updateTime}, count = #{count} WHERE user_id = #{userId}")
    void update(User user);

    @Select("SELECT * FROM user WHERE user_id = #{userId}")
    @Results({@Result(property = "userId", column = "user_id"),
            @Result(property = "userName", column = "user_name"),
            @Result(property = "count", column = "count"),
            @Result(property = "updateTime", column = "update_time"),
            @Result(property = "role", column = "role")})
    User find(String userId);

    /*
    @Select("SELECT * FROM user")
    @Results({@Result(property = "userId", column = "user_id"),
            @Result(property = "userName", column = "user_name"),
            @Result(property = "count", column = "count"),
            @Result(property = "updateTime", column = "update_time"),
            @Result(property = "role", column = "role")})
    List<User> list(String search);
     */

    @SelectProvider(type = ListMapperProvider.class, method = "list")
    @Results({@Result(property = "userId", column = "user_id"),
            @Result(property = "userName", column = "user_name"),
            @Result(property = "count", column = "count"),
            @Result(property = "updateTime", column = "update_time"),
            @Result(property = "role", column = "role")})
    List<User> list(String search);

    class ListMapperProvider {
        public String list(String search) {
            String sql = "SELECT * FROM user";
            if (StringUtils.isNotBlank(search)) {
                sql += " WHERE LOWER(user_name) LIKE '%" + search + "%'";
            }
            return sql;
        }
    }

    /*
    @Select("SELECT COUNT(1) FROM user")
    int count();
     */

    @SelectProvider(type = CountMapperProvider.class, method = "count")
    int count(String search);

    class CountMapperProvider {
        public String count(String search) {
            String sql = "SELECT count(1) FROM user ";
            if (StringUtils.isNotBlank(search)) {
                sql += " WHERE LOWER(user_name) LIKE '%" + search + "%'";
            }
            return sql;
        }
    }
}