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

import com.liangjian.dataplatform.member.entity.po.secondary.FiltersData;
import com.liangjian.dataplatform.member.entity.po.secondary.FiltersUtils;
import com.liangjian.dataplatform.member.jobUtil.EsUtils;
import com.liangjian.dataplatform.member.service.IPurchaseHistoryService;
import com.liangjian.dataplatform.member.util.QueryBuilderUtil;
import com.liangjian.dataplatform.member.util.StringUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class PurchaseHistoryService implements IPurchaseHistoryService {

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

        Map<String, Object> ret = new HashMap<>();
        List<Map<String, Object>> retList = new ArrayList<Map<String, Object>>();
        int totalCount = 0;
        ret.put("items",retList);
        ret.put("totalCount",totalCount);
        int start = 0;
        String query = null;
        String condition = null;
        if(null != data){
                List<FiltersUtils> filrer = data.getFilters();
                condition = EsUtils.getFilterString(filrer);
                String value = filrer.get(0).getValue();
                int pageSize= data.getPageSize();
                int pageIndex = data.getPageIndex();
                if (pageIndex == 1)
                {
                    start = 0;
                }
                else
                {
                    start = ((pageIndex - 1) * pageSize) + 1;
                }
                query =  "select * from mem_order where 1=1 "+condition+" order by CreationDate limit " + pageSize;
        }

        String sql = EsUtils.query(query,"_sql/translate?format=json",true);
        String from = "\"from\":" + start + ",";
        StringBuilder sb = new StringBuilder(sql);
        sb.insert(1,from);

        String str = EsUtils.query(sb.toString(),"mem_order/_search?format=json",false);

        JSONObject jsonObject = JSONObject.fromObject(str);
        Map<String, Object> hitsMap = (Map<String, Object>) jsonObject.get("hits");
        List<Map<String, Object>> histList = (List<Map<String, Object>>)hitsMap.get("hits");



        if(histList != null && histList.size() > 0){
            for (Map<String, Object> objectObjectMap : histList) {
                Map<String, Object> source = (Map<String, Object>) objectObjectMap.get("_source");
                source.put("_id",objectObjectMap.get("_id"));

                Map<String, Object> fieldsMap = (Map<String, Object>) objectObjectMap.get("fields");
                List<Integer> listSum = (List<Integer>) fieldsMap.get("Sum");
                Integer integer = listSum.get(0);
                fieldsMap.put("Sum",  integer > 0 ? integer / 100:0 );

                retList.add(fieldsMap);
            }

            var countdata = "select count(1) from mem_order  where  1=1 "+ condition ;

            String count = EsUtils.query(countdata,"_sql?format=json",true);
            JSONObject countJson = JSONObject.fromObject(count);
            JSONArray rows = countJson.getJSONArray("rows");
            List<Integer> rowsList = (List<Integer>) rows.get(0);
            totalCount = rowsList.get(0);
            ret.put("items",retList);
            ret.put("totalCount",totalCount);
        }
        return ret;
    }

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


        HashMap<String, Object> ret = new HashMap<>();

        int start = 0;
        String filter = "";
        String query = null;
        if (data != null){
            List<FiltersUtils> filters = data.getFilters();
            filter = EsUtils.getFilterString(filters);
            int pageIndex = data.getPageIndex();
            int pageSize = data.getPageSize();
            if (pageIndex == 1){
                start = 0;
            }else{
                start = ((pageIndex - 1) * pageSize) + 1;
            }
            //根据会员电话号码，先找到他的所有订单
            //找到属于处方的订单
            query = "select * from mem_orderproducts where 1=1"+
                filter +
                " order by CreationDate " +
                "limit " + pageSize;
        };
        String sql = EsUtils.query(query, "_sql/translate?format=json", true);
        String from = "\"from\":" + start + ",";
        StringBuilder sb = new StringBuilder(sql);
        sql = sb.insert(1,from).toString();
        String str  = EsUtils.query(sql, "mem_orderproducts/_search?format=json", false);

        JSONObject jsonObject = JSONObject.fromObject(str);
        Map<String, Object> hitsMap = (Map<String, Object>) jsonObject.get("hits");
        List<Map<String, Object>> histList = (List<Map<String, Object>>)hitsMap.get("hits");

        if (histList != null && histList.size() > 0){
            List<Map<String, Object>> retList = new ArrayList<Map<String, Object>>();
            for (Map<String, Object> stringObjectMap : histList) {
                Map<String, Object> source = (Map<String, Object>) stringObjectMap.get("_source");
                source.put("_id",stringObjectMap.get("_id"));
                Map<String, Object> fields = (Map<String, Object>) stringObjectMap.get("fields");
                List<Integer> actualPrice = (List<Integer>) fields.get("ActualPrice");

                fields.put("ActualPrice", actualPrice.get(0) > 0 ? actualPrice.get(0) / 100:0);

                for (String key : source.keySet()) {
                    fields.put(key, source.get(key));
                }


                retList.add(fields);
            }

            var countdata = "select count(1) from mem_orderproducts  where 1=1"+filter;
            String count = EsUtils.query(countdata, "_sql?format=json", true);
            JSONObject countJson = JSONObject.fromObject(count);
            JSONArray rows = countJson.getJSONArray("rows");
            List<Integer> rowsList = (List<Integer>) rows.get(0);

            ret.put("items",retList);
            ret.put("totalCount",rowsList.get(0));
        }
        return ret;
    }





}
