package com.mobvista.apptag.mapper;

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

import java.util.List;

/**
 * @author wangjf
 */

public interface ECStorageDao {

    @Insert("REPLACE INTO ec_storage(url_md5,preview_url,tag,update_time,user_id) VALUES(#{urlMd5}, #{previewUrl}, #{tag}, #{updateTime}, #{userId})")
    boolean save(ECStorage ecStorage);

    @Select("SELECT * FROM ec_storage WHERE url_md5 = #{urlMd5}")
    @Results({@Result(property = "urlMd5", column = "url_md5"),
            @Result(property = "previewUrl", column = "preview_url"),
            @Result(property = "tag", column = "tag"),
            @Result(property = "updateTime", column = "update_time")})
    ECStorage find(String urlMd5);

    @SelectProvider(type = MapperProvider.class, method = "list")
    @Results({@Result(property = "urlMd5", column = "url_md5"),
            @Result(property = "previewUrl", column = "preview_url"),
            @Result(property = "tag", column = "tag"),
            @Result(property = "updateTime", column = "update_time")})
    List<ECStorage> list(String search);

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

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

        public String count(String search) {
            String sql = "SELECT COUNT(1) FROM ec_storage";
            if (StringUtils.isNotBlank(search)) {
                sql += " WHERE LOWER(preview_url) LIKE '%" + search + "%'";
            }
            return sql;
        }
    }
}