package com.jay.monitor.data.server.store.es;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jay.monitor.data.server.componts.ElasticSearchPartition;
import com.jay.monitor.data.server.config.ElasticSearchBeanConfig;
import com.jay.monitor.data.server.models.entity.es.JayMonitorMQIndex;
import com.jay.monitor.data.server.utils.JayDataUtils;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.zxp.esclientrhl.annotation.EnableESTools;
import org.zxp.esclientrhl.index.ElasticsearchIndex;
import org.zxp.esclientrhl.repository.Attach;
import org.zxp.esclientrhl.repository.PageList;
import org.zxp.esclientrhl.repository.PageSortHighLight;
import org.zxp.esclientrhl.repository.Sort;
import org.zxp.esclientrhl.util.IndexTools;
import org.zxp.esclientrhl.util.MetaData;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = {ElasticSearchBeanConfig.class})
@EnableESTools(basePackages = "com.jay.monitor.data.server.store.es")
public class ElasticMQStoreProcessTest {
    @Autowired
    ElasticsearchIndex elasticsearchIndex;
    @Autowired
    RestHighLevelClient client;
    @Autowired
    ElasticSearchPartition elasticSearchPartition;

    @Test
    public void insert() throws Exception {
        //        String topicId = "97773"; // 晴天
        //        String topicId = "680279"; // 烟花易冷
        insertMusic("102296985");
        insertMusic("680279");
        insertMusic("97773");
    }

    @Test
    public void searchMQEs() throws Exception {
        JayMonitorMQIndex mqIndex = new JayMonitorMQIndex();
        mqIndex.setJsonContent("1221");

        MetaData index = IndexTools.getIndexType(JayMonitorMQIndex.class);
        List<JayMonitorMQIndex> music = this.elasticSearchPartition.searchPartition(JayDataUtils.getTableName(index.getIndexname(),"210319"), mqIndex);
        System.out.println(music);

    }

    /**
     * 查询单条数据的用例
     *
     * @throws Exception
     */
    @Test
    public void searchTemplate() throws Exception {
        String indexName = "music";
        MusicModel musicModel = new MusicModel();
        musicModel.setNick("许南安");
        List<MusicModel> music = this.elasticSearchPartition.searchPartition(indexName, musicModel);
        System.out.println(music);

        musicModel = new MusicModel();
        musicModel.setRootcommentcontent("喜欢");
        PageList pageList = elasticSearchPartition.searchPartitionPage(indexName, musicModel, 1, 10,
            new Sort.Order[] {new Sort.Order(SortOrder.DESC, "time.keyword")});
        System.out.println(pageList);
    }

    @Test
    public void searchTest() throws Exception {
        //        MatchPhraseQueryBuilder matchPhraseQueryBuilder = QueryBuilders.matchPhraseQuery("rootcommentcontent", "喜欢");

        String sorter = "time.keyword";
        Attach attach = new Attach();

        //        attach.setSearchAfter(true);
        PageSortHighLight pageSortHighLight = new PageSortHighLight(1, 10);
        Sort.Order order = new Sort.Order(SortOrder.DESC, sorter);
        pageSortHighLight.setSort(new Sort(order));
        attach.setPageSortHighLight(pageSortHighLight);

        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        //        MatchPhraseQueryBuilder matchPhraseQueryBuilder = QueryBuilders.matchPhraseQuery("", "");
        MusicModel model = new MusicModel();
        model.setNick("青柍");
        //        model.setAvatarurl("sadf");
        Field[] declaredFields = model.getClass().getDeclaredFields();
        for (int i = 0; i < declaredFields.length; i++) {
            Field declaredField = declaredFields[i];
            String name = declaredField.getName();
            String value = BeanUtils.getProperty(model, name);
            if (StringUtils.isNotBlank(value)) {
                MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery(name + ".keyword", value);
                boolQueryBuilder.must(matchQueryBuilder);
            }
        }
        //        boolQueryBuilder.must(matchPhraseQueryBuilder);
        PageList<MusicModel> search1 = elasticSearchPartition.search(boolQueryBuilder, attach, MusicModel.class);
        List<MusicModel> list = search1.getList();
        System.out.println(list);
    }

    private void insertMusic(String topicId) throws Exception {
        String url =
            "https://c.y.qq.com/base/fcgi-bin/fcg_global_comment_h5.fcg?g_tk_new_20200303=5381&g_tk=5381&loginUin=0&hostUin=0&format=json&inCharset=utf8&outCharset=GB2312&notice=0&platform=yqq.json&needNewCode=0&cid=205360772&reqtype=2&biztype=1&topid="
                + topicId
                + "&cmd=8&needmusiccrit=0&pagenum=0&pagesize=100&lasthotcommentid=&domain=qq.com&ct=24&cv=10101010";
        String commentJsonString = HttpUtil.downloadString(url, "UTF-8");
        JSONObject jsonObject = JSON.parseObject(commentJsonString);
        JSONObject hotComment = jsonObject.getJSONObject("hot_comment");
        JSONArray commentList = hotComment.getJSONArray("commentlist");
        List<MusicModel> testModelList = new ArrayList<>();
        for (int i = 0; i < commentList.size(); i++) {
            MusicModel musicModel = commentList.getObject(i, MusicModel.class);
            testModelList.add(musicModel);
        }
        BulkResponse save = elasticSearchPartition.save(testModelList);

        System.out.println("添加完毕 : " + save.hasFailures());
        System.out.println(save.toString());
    }

    @Test
    public void delete() {

    }

    private ESTestModel builderModel(String userName, String text) {
        ESTestModel testModel = new ESTestModel();
        testModel.setId(RandomUtil.randomString(5));
        testModel.setCreated(new Date());
        testModel.setRemark(userName);
        testModel.setUsername(text);
        return testModel;
    }

}