package com.gic.haoban.manage.service.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gic.api.base.commons.ServiceResponse;
import com.gic.commons.util.DateUtil;
import com.gic.commons.util.EntityUtil;
import com.gic.content.api.dto.common.MemberSearchDTO;
import com.gic.enterprise.api.service.StoreService;
import com.gic.haoban.manage.service.service.ESMemberInfoService;
import com.gic.member.api.dto.es.MemberDataDTO;
import com.gic.member.ext.api.service.MemberCrowdApiService;
import com.gic.member.tag.api.dto.MemberExistDTO;
import com.gic.member.tag.api.service.MemberTagEsApiService;
import com.gic.member.tag.api.service.MemberTagGroupApiService;
import com.gic.search.engine.api.constant.OperateEnum;
import com.gic.search.engine.api.dto.ESResponseQueryBatch;
import com.gic.search.engine.api.dto.ESResponseQueryBatchByScroll;
import com.gic.search.engine.api.dto.ESResponseQueryCount;
import com.gic.search.engine.api.dto.ESResponseQuerySingle;
import com.gic.search.engine.api.dto.dynamic.DynamicSearchDTO;
import com.gic.search.engine.api.filter.NewNodeAddUtil;
import com.gic.search.engine.api.service.dynamic.ESDataDynamicOperationApiService;
import com.google.common.collect.Lists;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author: YuZhi
 * @date: 2022/3/14 10:02
 */
@Service
public class ESMemberInfoServiceImpl implements ESMemberInfoService {

    Logger logger = LogManager.getLogger(ESMemberInfoService.class);

    @Autowired
    private ESDataDynamicOperationApiService esApiService;
    @Autowired
    private StoreService storeService;
    @Autowired
    private MemberTagGroupApiService memberTagGroupApiService;
    @Autowired
    private MemberTagEsApiService memberTagEsApiService;

    @Override
    public String getMemberSearchParamOld(String enterpriseId, Integer memberType, String filterJson, String creatorId, boolean readyFlag) {
        String searchParams = "{}";
        if (StringUtils.isBlank(filterJson)) {
            return searchParams;
        }
        logger.info("人群条件参数enterpriseId：{},memberType:{},filterJson:{}",enterpriseId,memberType,filterJson);
        if (memberType == 0) {
            searchParams = filterJson;
        } else if (memberType == 1) {
            MemberExistDTO dto = new MemberExistDTO();
            dto.setEnterpriseId(enterpriseId);
            String[] tagGroupIdArr = filterJson.split(",");
            List<String> list = Arrays.asList(tagGroupIdArr);
            if (readyFlag) {
                // 是否准备好,true可以执行
                boolean finishFlag  = memberTagEsApiService.memberTagReady(enterpriseId, list) ;
                if (!finishFlag) {
                    return null;
                }
            }
            dto.setMemberTagGroupIds(list);
            dto.setUseId(creatorId);
            searchParams = memberTagGroupApiService.getSearchJsonByGroupId(dto);
        }
        logger.info("人群条件：{}",searchParams);
        return searchParams;
    }

    @Override
    public boolean matchMember(String enterpriseId, JSONObject searchJson, String memberId,String creatorId) {
        JSONObject jsonObject = queryDataSingle(enterpriseId, memberId, "");
        if (jsonObject == null) {
            return false;
        }
        searchJson = this.storeService.parseSelectData(searchJson, enterpriseId,creatorId,null);
        return esApiService.matchMember(searchJson, enterpriseId, jsonObject);
    }

    @Override
    public JSONObject queryDataSingle(String enterpriseId, String memberId, String returnFields) {
        JSONObject searchRes = null;
        try {
            JSONObject searchJson = new JSONObject();
            DynamicSearchDTO search = new DynamicSearchDTO();
            searchJson.put("id", memberId);
            search.setSearchJson(searchJson);
            search.setEnterpriseId(enterpriseId);
            search.setColumnCategoryCode("member");
            if (StringUtils.isNotBlank(returnFields)) {
                search.setReturnFileds(returnFields);
            }
            ESResponseQuerySingle single = esApiService.queryDataSingle(search);
            searchRes = single.getRes();
        } catch (Exception e) {
            logger.warn("从搜索引擎搜索会员数据异常memberId: {}", memberId, e);
        }
        return searchRes;
    }

    @Override
    public List<MemberDataDTO> queryDataBatch(String enterpriseId, List<String> memberIdList, String returnFields) {
        DynamicSearchDTO search = new DynamicSearchDTO();
        search.setEnterpriseId(enterpriseId);
        search.setColumnCategoryCode("member");
        String memberIds = String.join(" ", memberIdList);
        JSONObject searchObj = new JSONObject();
        searchObj = NewNodeAddUtil.addNewNodeForAnd("memberId", OperateEnum.OPERATE_CONTAIN.getValue(), memberIds,
                searchObj);
        search.setSearchJson(searchObj);
        search.setReturnFileds(returnFields);
        search.setSortJson(NewNodeAddUtil.createSortNode("memberId", NewNodeAddUtil.SORT_RULE_ASC));
        search.setBegin(0);
        search.setRecordNumber(memberIdList.size());
        ESResponseQueryBatch response = esApiService
                .queryDataBatch(search, Boolean.FALSE, null);
        List<JSONObject> res = response.getRes();
        if (CollectionUtils.isEmpty(res)) {
            return new ArrayList<>();
        }
        return res.stream().map(x -> x.toJavaObject(MemberDataDTO.class)).collect(Collectors.toList());
    }
}
