package com.yihu.jw.es.es;

import com.alibaba.fastjson.JSONObject;
import io.searchbox.client.JestClient;
import io.searchbox.core.Bulk;
import io.searchbox.core.BulkResult;
import io.searchbox.core.Index;
import io.searchbox.core.Update;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

;

/**
 * Created by chenweida on 2017/6/2.
 */
@Component
@Scope("prototype")
public class ElastricSearchSave {

    private Logger logger = LoggerFactory.getLogger(ElastricSearchSave.class);
    @Autowired
    private ElasticFactory elasticFactory;

    public Boolean save(List sms, String esIndex, String esType) {

        JestClient jestClient = null;
        try {
            //得到链接
            jestClient = elasticFactory.getJestClient();

            Bulk.Builder bulk = new Bulk.Builder().defaultIndex(esIndex).defaultType(esType);
            for (Object obj : sms) {
                Index index = new Index.Builder(obj).build();
                bulk.addAction(index);
            }
            BulkResult br = jestClient.execute(bulk.build());
            logger.info("save data count:" + sms.size());
            logger.info("save flag:" + br.isSucceeded());
            return br.isSucceeded();
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(" save error ：" + e.getMessage());
        } finally {
            if (jestClient != null) {
                jestClient.shutdownClient();
            }
        }
        return null;
    }

    public Boolean save(Object obj, String esIndex, String esType) {

        JestClient jestClient = null;
        try {
            //得到链接
            jestClient = elasticFactory.getJestClient();

            Bulk.Builder bulk = new Bulk.Builder().defaultIndex(esIndex).defaultType(esType);
            Index index = new Index.Builder(obj).build();
            bulk.addAction(index);
            BulkResult br = jestClient.execute(bulk.build());
            logger.info("save flag:" + br.isSucceeded());
            return br.isSucceeded();
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(" save error ：" + e.getMessage());
        } finally {
            if (jestClient != null) {
                jestClient.shutdownClient();
            }
        }
        return null;
    }

   /* *//**
     * 清洗平台咨询日志使用
     * @param sms
     * @param esIndex
     * @param esType
     * @return
     *//*
    public Boolean updatePlatformInfomationLog(List<PlatformInformationLogES> sms , String esIndex, String esType) {
        JestClient jestClient = null;
        try {
            //得到链接
            jestClient = elasticFactory.getJestClient();

            int success = 0;
            int error = 0;
            boolean isSuccessed = true;
            Bulk.Builder bulk = new Bulk.Builder().defaultIndex(esIndex).defaultType(esType);
            for (PlatformInformationLogES obj : sms) {
                try {
                    JSONObject jo = new JSONObject();
                    jo.put("doc", obj);
                    Update index = new Update.Builder(jo.toString()).index(esIndex).type(esType).id(obj.getId()).build();
                    bulk.addAction(index);
                    success++;
                } catch (Exception e) {
                    error++;
                    isSuccessed = false;
                }
            }

            BulkResult br = jestClient.execute(bulk.build());
            logger.info("update flag:" + br.isSucceeded());
            logger.info("update success:" + success);
            logger.info("update error:" + error);
            jestClient.shutdownClient();
            return isSuccessed;
        } catch (Exception e) {
            logger.error(" update error ：" + e.getMessage());
        } finally {
            if (jestClient != null) {
                jestClient.shutdownClient();
            }
        }
        return null;
    }*/

    public Boolean batchSave(List sms, String esIndex, String esType) {

        JestClient jestClient = null;
        List bulkList = new ArrayList();
        try {
            //得到链接
            jestClient = elasticFactory.getJestClient();

            Bulk.Builder bulk = new Bulk.Builder().defaultIndex(esIndex).defaultType(esType);
//            BulkResult br = null;
            for (Object obj : sms) {
                bulkList.add(obj);
                Index index = new Index.Builder(obj).build();
                bulk.addAction(index);
                if(bulkList.size() >= 500){
                    BulkResult br = jestClient.execute(bulk.build());
                    logger.info("save data count:" + bulkList.size());
                    logger.info("save flag:" + br.isSucceeded());
                    bulk = new Bulk.Builder().defaultIndex(esIndex).defaultType(esType);
                    bulkList.clear();
                }
            }
            //如果不是1千的倍数，那最后还得再存储一次
            if(sms.size() % 1000 != 0){
                BulkResult br = jestClient.execute(bulk.build());
                logger.info("save data count:" + (sms.size() / 1000));
                logger.info("save flag:" + br.isSucceeded());
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(" save error ：" + e.getMessage());
        } finally {
            if (jestClient != null) {
                jestClient.shutdownClient();
            }
        }
        return null;
    }


}
