package com.hys.app.framework.elasticsearch;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 初始es索引
 * @author Administrator
 */
@Component
public class EsIndexInit {

//    @Autowired
    protected ElasticsearchTemplate elasticsearchTemplate;

    @Autowired
    protected EsConfig esConfig;


    private final Logger logger = LoggerFactory.getLogger(getClass());


    public void initEs(){

        //拼装索引名称
        String goodsIndices = esConfig.getIndexName() + "_" + EsSettings.GOODS_INDEX_NAME;
        String ptIndices = esConfig.getIndexName() + "_" + EsSettings.PINTUAN_INDEX_NAME;

        //检测商品索引是否存在
        if (!elasticsearchTemplate.indexExists(goodsIndices)) {
            logger.debug("系统检测到索引{}不存在，创建索引和Mapping",goodsIndices);
            elasticsearchTemplate.createIndex(goodsIndices);
            Map goodsMapping = EsMappingUtil.createGoodsMapping();
            elasticsearchTemplate.putMapping(goodsIndices, EsSettings.GOODS_TYPE_NAME, goodsMapping);
        }else {
            logger.debug("系统检测到索引{}已经存在",goodsIndices);
        }

        //检测拼团索引是否存在
        if (!elasticsearchTemplate.indexExists(ptIndices)) {
            logger.debug("系统检测到索引{}不存在，创建索引和Mapping",ptIndices);
            elasticsearchTemplate.createIndex(ptIndices);
            Map pingTuanMapping = EsMappingUtil.createPingTuanMapping();
            elasticsearchTemplate.putMapping(ptIndices, EsSettings.PINTUAN_TYPE_NAME, pingTuanMapping);
        }else {
            logger.debug("系统检测到索引{}已经存在",ptIndices);
        }

    }

}
