package com.liangjian.dataplatform.member.service.impl;

import com.liangjian.dataplatform.member.dao.fourthly.MemDataDictoryRepository;
import com.liangjian.dataplatform.member.entity.po.secondary.FiltersUtils;
import com.liangjian.dataplatform.member.entity.response.ResultObject;
import com.liangjian.dataplatform.member.service.IMemberextsService;
import com.liangjian.dataplatform.member.util.QueryBuilderUtil;
import com.liangjian.dataplatform.member.util.StringUtil;
import net.sf.json.JSONObject;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.fetch.subphase.FetchSourceContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.*;

@Service
public class MemberextsService implements IMemberextsService {


    @Autowired
    private MemDataDictoryRepository memDataDictoryRepository;

    @Autowired
    private ElasticsearchRestTemplate elasticsearchTemplate;

    @Override
    public Map<String, Object> memberextsByPhone(String data) {
        Map<String, Object> ret = new HashMap<String, Object>();
        ret.put("items", null);
        ret.put("success", false);
        if (!StringUtil.isEmpty(data)) {
            JSONObject jsonObject = net.sf.json.JSONObject.fromObject(data);
            List<FiltersUtils> filrer = new ArrayList<FiltersUtils>();
            FiltersUtils filters = new FiltersUtils();
            filters.setOperate("equal");
            filters.setField("_id");
            filters.setValue(jsonObject.get("query").toString());
            filrer.add(filters);
            String str = null;
            SearchHit[] searchHit = QueryBuilderUtil.search("mem_memberbase_p", "_doc", 0, 0, filrer);
            List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
            for (int i = 0; i < searchHit.length; i++) {
                SearchHit searchHit1 = searchHit[i];
                Map<String, Object> source = searchHit1.getSourceAsMap();
                source.put("_id", searchHit1.getId());
                list.add(source);
            }
            ret.put("items", list);
            ret.put("success", true);
        }
        return ret;
    }

    @Override
    public Map<String, Object> index(String data) {

        Map<String, Object> ret = new HashMap<String, Object>();
        ret.put("items", null);
        ret.put("success", false);
        if (!StringUtil.isEmpty(data)) {
            JSONObject jsonObject = net.sf.json.JSONObject.fromObject(data);
            List<FiltersUtils> filrer = new ArrayList<FiltersUtils>();
            FiltersUtils filters = new FiltersUtils();
            filters.setOperate("equal");
            filters.setField("_id");
            filters.setValue(jsonObject.get("MemberPhone").toString());
            filrer.add(filters);
            String str = null;
            SearchHit[] searchHit = QueryBuilderUtil.search("mem_memberbase_p", "_doc", 0, 0, filrer);
            List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
            for (int i = 0; i < searchHit.length; i++) {
                SearchHit searchHit1 = searchHit[i];
                Map<String, Object> source = searchHit1.getSourceAsMap();

                String patientPhone = source.get("MemUsualPhone").toString();
                Map<String, Object> patientPhoneMap = memDataDictoryRepository.desDecryptFixKey(patientPhone);// 号码解密.
                patientPhone = (String) patientPhoneMap.get("phone");
                if (!StringUtil.isEmpty(patientPhone)) {
                    String replaced = patientPhone.substring(3, 7);
                    patientPhone = patientPhone.replace(replaced, "****");
                }

                Map<String, Object> itemsMap = new HashMap<String, Object>();
                itemsMap.put("PatientWeight", source.get("PatientWeight"));
                itemsMap.put("PatientGender", source.get("PatientGender"));
                itemsMap.put("PatientId", source.get("PatientId"));
                itemsMap.put("MemberGender", source.get("MemberGender"));
                itemsMap.put("MemEmail", source.get("MemEmail"));
                itemsMap.put("MemberNickName", source.get("MemberNickName"));
                itemsMap.put("MemUsualAddress", source.get("MemUsualAddress"));
                itemsMap.put("MemUsualPhone", patientPhone);
                itemsMap.put("PatientName", source.get("PatientName"));
                itemsMap.put("PatientHeight", source.get("PatientHeight"));
                itemsMap.put("PatientAge", source.get("PatientAge"));
                itemsMap.put("PatientPhoneCr", searchHit1.getId());
                itemsMap.put("_id", searchHit1.getId());
                itemsMap.put("PatientPhoneOr", patientPhone);

                list.add(itemsMap);
            }
            ret.put("items", list);
            ret.put("temsCount", list.size());
            ret.put("success", true);
        }
        return ret;
    }

    @Override
    public Map<String, Object> tagByMemberPhone(String data) {
        Map<String, Object> ret = new HashMap<String, Object>();
        Map<String, Object> itemsMap = new HashMap<String, Object>();
        ret.put("items", itemsMap);
        ret.put("success", true);
        try {
            if (!StringUtil.isEmpty(data)) {
                JSONObject jsonObject = net.sf.json.JSONObject.fromObject(data);
                List<FiltersUtils> filrer = new ArrayList<FiltersUtils>();
                FiltersUtils filters = new FiltersUtils();
                filters.setOperate("equal");
                filters.setField("MemberPhone");
                filters.setValue(jsonObject.get("query").toString());
                filrer.add(filters);
                String str = null;
                SearchHit[] memberSearch = QueryBuilderUtil.search("mem_membertag", "_doc", 0, 0, filrer);

                for (int i = 0; i < memberSearch.length; i++) {
                    SearchHit searchHit1 = memberSearch[i];
                    Map<String, Object> source = searchHit1.getSourceAsMap();
                    String TagTypeName = source.get("TagTypeName").toString();

//                    param.clear();
//                    map.clear();
//                    param.put("MemberPhone",jsonObject.get("query").toString());
//                    param.put("TagTypeName",TagTypeName);
//                    map.put("equals",param);
                    filrer.clear();
                    filters = new FiltersUtils();
                    filters.setOperate("equal");
                    filters.setField("MemberPhone");
                    filters.setValue(jsonObject.get("query").toString());
                    filrer.add(filters);

                    FiltersUtils filters1 = new FiltersUtils();
                    filters1.setOperate("equal");
                    filters1.setField("TagTypeName");
                    filters1.setValue(TagTypeName);
                    filrer.add(filters1);
                    SearchHit[] nameSearch = QueryBuilderUtil.search("mem_membertag", "_doc", 0, 0, filrer);

                    Map<String, Object>[] nameSearchArr = new Map[nameSearch.length];
                    for (int j = 0; j < nameSearch.length; j++) {
                        SearchHit nameSearch1 = nameSearch[j];
                        Map<String, Object> nameSearchMap = nameSearch1.getSourceAsMap();
                        nameSearchArr[i] = nameSearchMap;
                    }
                    itemsMap.put(TagTypeName, nameSearchArr);
                }
                ret.put("items", itemsMap);
                ret.put("success", true);
            }
        } catch (Exception e) {
            e.printStackTrace();
            ret.put("items", null);
            ret.put("success", false);
        }
        return ret;
    }

    /**
     * 根据手机号查询用户的所有标签
     * @param phone
     * @return 用户的所有标签
     * @throws IOException
     */
    @Override
    public ResultObject<List<Map<String, Object>>> findTagsByMemberPhone(String phone) throws IOException {

        String secretPhone = memDataDictoryRepository.desEncryptFixKey(phone).get("phone").toString();

        return findTagsByMemberSecretPhone(secretPhone);

    }

    /**
     * 根据加密的手机号查询所有的标签
     * @param secretPhone
     * @return 用户的所有标签
     * @throws IOException
     */
    @Override
    public ResultObject<List<Map<String, Object>>> findTagsByMemberSecretPhone(String secretPhone) throws IOException {

        RestHighLevelClient client = elasticsearchTemplate.getClient();

        GetResponse response = client.get(new GetRequest("mem_memberbase_p").id(secretPhone)
                        .fetchSourceContext(new FetchSourceContext(true, new String[]{"Tags"}, null)),
                RequestOptions.DEFAULT);

        Map<String, Object> sourceAsMap = response.getSourceAsMap();

        if (!response.isExists()) {
            return ResultObject.error("没有该用户");
        }

        List<Map<String, Object>> result = (List<Map<String, Object>>) sourceAsMap.get("Tags");

        return ResultObject.success("响应成功",result);
    }


    /**
     * 根据用户手机号查询基本信息
     * @param phone
     * @return
     * @throws IOException
     */
    @Override
    public ResultObject<Map<String, Object>> findBaseInfoByMemberPhone(String phone) throws IOException {

        String secretPhone = memDataDictoryRepository.desEncryptFixKey(phone).get("phone").toString();

       return findBaseInfoByMemberSecretPhone(secretPhone);
    }


    /**
     * 根据用户加密手机号查询基本信息
     * @param secretPhone
     * @return
     * @throws IOException
     */
    @Override
    public ResultObject<Map<String, Object>> findBaseInfoByMemberSecretPhone(String secretPhone) throws IOException {

        RestHighLevelClient client = elasticsearchTemplate.getClient();

        // 返回字段
        String[] includeField = new String[]{"MemberGender", "MemberHeaPic", "MemberNickName", "MemUsualPhone", "MemPhone1", "MemPhone2", "MemPhone3", "MemUsualAddress", "OriginType", "RegisterTime", "MemUsualAreaCode", "MemUsualCityCode", "MemUsualProvinceCode", "HasOrder", "RegisterYear", "RegisterMonth", "RegisterDay", "OrderHour", "OrderMinute", "OrderSecond", "MemberId", "OrdersCode", "MemEmail", "MemDesc", "CreationDate", "OrderTime", "order_join_field", "PatientId", "PatientName", "PatientHeight", "PatientWeight", "PatientGender", "PatientPhone", "PatientAge", "MemName", "Gender", "DeliveryAddress"};
        GetResponse response = client.get(new GetRequest("mem_memberbase_p").id(secretPhone)
                        .fetchSourceContext(new FetchSourceContext(true, includeField, null)),
                RequestOptions.DEFAULT);

        if(!response.isExists()){
            return ResultObject.error("没有该用户");
        }

        Map<String, Object> sourceAsMap = response.getSourceAsMap();

        if(sourceAsMap != null && sourceAsMap.containsKey("Gender")){
            switch (sourceAsMap.get("Gender").toString().trim()){
                case "0":
                    sourceAsMap.put("Gender", "女");
                    break;
                case "1":
                    sourceAsMap.put("Gender", "男");
                    break;
                default:
                    sourceAsMap.put("Gender", "未知");
            }
        }else{
            sourceAsMap.put("Gender", "未知");
        }

        return ResultObject.success("响应成功",sourceAsMap);
    }


}
