package com.gic.haoban.manage.web.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gic.clerk.api.dto.ClerkDTO;
import com.gic.clerk.api.service.ClerkService;
import com.gic.enterprise.api.dto.StoreDTO;
import com.gic.enterprise.api.service.StoreService;
import com.gic.search.engine.api.constant.OperateEnum;
import com.gic.search.engine.api.dto.ESResponseQueryBatch;
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 lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

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

@Component
@Slf4j
public class EsMemberInfoUtils {

    @Autowired
    private ESDataDynamicOperationApiService esDataDynamicOperationApiService;
    @Autowired
    private StoreService storeService;
    @Autowired
    private ClerkService clerkService;

    public void setMemberInfo(String enterpriseId, List list, Set<String> fieldName) {
        if (CollectionUtils.isNotEmpty(list)) {
            List<String> memberIdList = new ArrayList<>();
            for (Object o : list) {
                String memberId = ReflectUtils.getDateFieldValue(o, "memberId");
                if (org.apache.commons.lang.StringUtils.isNotBlank(memberId) && !"-1".equals(memberId)) {
                    memberIdList.add(memberId);
                }
            }
            if (CollectionUtils.isNotEmpty(memberIdList)) {
                List<JSONObject> memberJson = queryDataBatch(enterpriseId, memberIdList, "memberId,name,mainStoreId,phoneNumber,name,nickName,mainClerkId,photoUrl,cardNo");
                if (CollectionUtils.isNotEmpty(memberJson)) {
                    Map<String, JSONObject> map = memberJson.stream()
                            .collect(Collectors.toMap(e -> e.getString("memberId"), e -> e));

                    Map<String, StoreDTO> storeMap = new HashMap<>();
                    Map<String, ClerkDTO> clerkMap = new HashMap<>();

                    boolean isQueryStore = fieldName.contains("storeName") || fieldName.contains("storeCode");
                    if (isQueryStore) {
                        List<String> mainStoreIdList = memberJson.stream().
                                filter(e -> org.apache.commons.lang3.StringUtils.isNotBlank(e.getString("mainStoreId")))
                                .map(e -> e.getString("mainStoreId")).collect(Collectors.toList());
                        if (CollectionUtils.isNotEmpty(mainStoreIdList)) {
                            List<StoreDTO> mainStoreList = storeService.queryStore(mainStoreIdList);
                            if (CollectionUtils.isNotEmpty(mainStoreList)) {
                                storeMap = mainStoreList.stream().collect(Collectors.toMap(e -> e.getStoreId(), e -> e));
                            }
                        }
                    }

                    boolean isQueryClerk = fieldName.contains("clerkCode") || fieldName.contains("clerkName");
                    if (isQueryClerk) {
                        Set<String> mainClerkIdList = memberJson.stream().
                                filter(e -> org.apache.commons.lang3.StringUtils.isNotBlank(e.getString("mainClerkId")))
                                .map(e -> e.getString("mainClerkId")).collect(Collectors.toSet());
                        if (CollectionUtils.isNotEmpty(mainClerkIdList)) {
                            List<ClerkDTO> mainClerkList = clerkService.getClerkByClerkIds(mainClerkIdList);
                            if (CollectionUtils.isNotEmpty(mainClerkList)) {
                                clerkMap = mainClerkList.stream().collect(Collectors.toMap(e -> e.getClerkId(), e -> e));
                            }
                        }
                    }

                    for (Object vo : list) {
                        String memberId = ReflectUtils.getDateFieldValue(vo, "memberId");
                        JSONObject jsonValue = map.get(memberId);
                        if (jsonValue != null) {
                            if (fieldName.contains("memberPhone")) {
                                ReflectUtils.setDateFieldValue(vo, "memberPhone", jsonValue.getString("phoneNumber"));
                            }
                            if (fieldName.contains("memberName")) {
                                ReflectUtils.setDateFieldValue(vo, "memberName", jsonValue.getString("name"));
                            }
                            if (fieldName.contains("memberNick")) {
                                ReflectUtils.setDateFieldValue(vo, "memberNick", jsonValue.getString("nickName"));
                            }
                            if (fieldName.contains("photoUrl")) {
                                ReflectUtils.setDateFieldValue(vo, "photoUrl", jsonValue.getString("photoUrl"));
                            }
                            if (fieldName.contains("memberScene")) {
                                ReflectUtils.setDateFieldValue(vo, "memberScene", 3);
                            }
                            if (fieldName.contains("memberCard")) {
                                ReflectUtils.setDateFieldValue(vo, "memberCard", jsonValue.getString("cardNo"));
                            }
                            if (fieldName.contains("memberImage")) {
                                ReflectUtils.setDateFieldValue(vo, "memberImage", jsonValue.getString("photoUrl"));
                            }

                            if (isQueryStore) {
                                String mainStoreId = jsonValue.getString("mainStoreId");
//                                ReflectUtils.setDateFieldValue(vo, "storeId", mainStoreId);
                                if (org.apache.commons.lang.StringUtils.isNotBlank(mainStoreId)) {
                                    StoreDTO storeValue = storeMap.get(mainStoreId);
                                    if (storeValue != null) {
                                        ReflectUtils.setDateFieldValue(vo, "storeCode", storeValue.getStoreCode());
                                        ReflectUtils.setDateFieldValue(vo, "storeName", storeValue.getStoreName());

                                        if (fieldName.contains("parentStoreGroupName")) {
                                            ReflectUtils.setDateFieldValue(vo, "parentStoreGroupName", storeValue.getStoreGroupName());
                                        }
                                    }
                                }
                            }

                            if (isQueryClerk) {
                                String mainClerkId = jsonValue.getString("mainClerkId");
//                                ReflectUtils.setDateFieldValue(vo, "clerkId", mainClerkId);
                                if (org.apache.commons.lang.StringUtils.isNotBlank(mainClerkId)) {
                                    ClerkDTO clerkDTO = clerkMap.get(mainClerkId);
                                    if (clerkDTO != null) {
                                        ReflectUtils.setDateFieldValue(vo, "clerkCode", clerkDTO.getClerkCode());
                                        ReflectUtils.setDateFieldValue(vo, "clerkName", clerkDTO.getClerkName());
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    public List<JSONObject> queryDataBatch(String enterpriseId, List<String> memberIdList, String returnFields) {
        if (CollectionUtils.isEmpty(memberIdList)) {
            log.warn("memberIdList 为空", enterpriseId);
            return null;
        }
        List<JSONObject> jsonObjList = new ArrayList<JSONObject>();
        try {
            JSONObject searchJson = new JSONObject();
            String[] memberIdArr = memberIdList.toArray(new String[memberIdList.size()]);
            String memberIds = StringUtils.join(memberIdArr, " ");
            searchJson = NewNodeAddUtil.addNewNodeForAnd("memberId", OperateEnum.OPERATE_CONTAIN.getValue(), memberIds,
                    searchJson);
            DynamicSearchDTO search = new DynamicSearchDTO();
            log.info("==============搜索条件==============: {}", JSON.toJSONString(searchJson));
            search.setRecordNumber(memberIdList.size() + 1);
            search.setSearchJson(searchJson);
            search.setEnterpriseId(enterpriseId);
            search.setColumnCategoryCode("member");
            search.setReturnFileds(returnFields);
            search.setSortJson(NewNodeAddUtil.createSortNode("memberId", NewNodeAddUtil.SORT_RULE_ASC));

            ESResponseQueryBatch esRes = esDataDynamicOperationApiService.queryDataBatch(search, false, null);
            jsonObjList = esRes.getRes();

        } catch (Exception e) {
            log.warn("从搜索引擎搜索会员数据异常", memberIdList, enterpriseId, e);
        }
        return jsonObjList;
    }
}
