package com.mobvista.apptag.mapper;

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

import java.text.MessageFormat;
import java.util.List;
import java.util.Map;

/**
 * @author wangjf
 */

public interface TreeTagDao {

    @InsertProvider(type = Provider.class, method = "batchInsert")
    boolean batchInsert(List<TreeTag> results);

    class Provider {
        /**
         * 批量插入
         */
        public String batchInsert(Map map) {
            List<TreeTag> results = (List<TreeTag>) map.get("list");
            StringBuilder sb = new StringBuilder();
            sb.append("REPLACE INTO tree_tag_list (package_name, platform, first_tag, second_tag, third_tag, update_time) VALUES ");
            MessageFormat mf = new MessageFormat(
                    "(#'{'list[{0}].packageName}, #'{'list[{0}].platform}, #'{'list[{0}].firstTag}, #'{'list[{0}].secondTag}, #'{'list[{0}].thirdTag}, #'{'list[{0}].updateTime})"
            );

            for (int i = 0; i < results.size(); i++) {
                sb.append(mf.format(new Object[]{i}));
                if (i < results.size() - 1) {
                    sb.append(",");
                }
            }
            return sb.toString();
        }
    }

    @Delete("DELETE FROM tree_tag_list")
    void delete();

    @SelectProvider(type = ListMapperProvider.class, method = "list")
    @Results({@Result(property = "packageName", column = "package_name"),
            @Result(property = "platform", column = "platform"),
            @Result(property = "firstTag", column = "first_tag"),
            @Result(property = "secondTag", column = "second_tag"),
            @Result(property = "thirdTag", column = "third_tag"),
            @Result(property = "updateTime", column = "update_time")})
    List<TreeTag> list(String search);

    class ListMapperProvider {
        public String list(String search) {
            String sql = "SELECT * FROM tree_tag_list";

            if (StringUtils.isNotBlank(search)) {
                sql += " WHERE LOWER(package_name) LIKE '%" + search.toLowerCase() + "%'";
            }
            return sql;
        }
    }

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

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