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

import com.liangjian.dataplatform.member.dao.tertiary.DataDictoryRepository;
import com.liangjian.dataplatform.member.dao.tertiary.OrderProductsRepository;
import com.liangjian.dataplatform.member.entity.po.tertiary.DataDictory;
import com.liangjian.dataplatform.member.jobUtil.EsUtils;
import com.liangjian.dataplatform.member.service.IOrderFormStatisService;
import com.liangjian.dataplatform.member.util.DateUtil;
import com.liangjian.dataplatform.member.util.StringUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

@Service
public class OrderFormStatisService implements IOrderFormStatisService {

    private static String clickHouseUrl="http://139.159.192.185:8123/?user=default&password=79B084A8D7363488DEBFA5D151CCC9B1";

    //sql查询es
    public static String Host="http://192.168.50.34:9200/_xpack/sql?format=json";
    //链接查询es
    public static EsUtils esUtils=new EsUtils();



    @Autowired
    private DataDictoryRepository dataDictoryRepository;

    @Autowired
    private OrderProductsRepository orderPortProductsRepository;



    @Override
    public Map<String, Object> getTermain() {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            List<Integer> list = new ArrayList<Integer>();
            list.add(785);
            list.add(786);
            List<DataDictory> ListDataDictory = dataDictoryRepository.findInParentIdAndIsHide(list);
            list.clear();

            list.add(783);
            List<DataDictory> ListDataDictory1 = dataDictoryRepository.findInParentIdAndIsHide(list);

            map.put("items",replaceKey(ListDataDictory));
            map.put("items1",replaceKey(ListDataDictory1));
            map.put("sum", new HashMap());
        }catch (Exception e){
            e.printStackTrace();
        }
        return map;
    }

    @Override
    public Map<String, Object> orderProvCount(String terminal, String date) {
        Map<String, Object> ret = new HashMap<String, Object>();
        String str1 = "";
        String redisKey = "3_order_prov";
        if (date != null){// 日期
            if (!date.equals("0")){
                date = "ym" + date.replace("-", "");
                str1 = "{ \"exists\": {\"field\": \"" + date + "\"}}";
                redisKey += date;
            }
        }

        if (str1 != null && str1.length() > 0)
        {
            str1 = ",\"filter\":" + str1;
        }
        String jo = ESQuery("select LEFT(RegionCode,2) AS c, count(distinct id) as cn from mem_repurchaseinfo group by c" + str1);
        //
        String resultCate = ESQuery("select* from areamap where Level = 1 ");

        JSONObject joJson = JSONObject.fromObject(jo);
        JSONObject joResultCate = JSONObject.fromObject(resultCate);

        Map<String, Object> map = new HashMap<String, Object>();
        List<Object> ResultCateRows = (List<Object>) joResultCate.get("rows");
        for (int i = 0; i<ResultCateRows.size(); i++){
            List<Object> temp = (List<Object>)ResultCateRows.get(i);
            String number = temp.get(2).toString();
            if(StringUtil.isEmpty(number)){
                continue;
            }
            map.put(number,temp.get(0).toString());
        }

       List<Object[]> list = new ArrayList<Object[]>();
        List<Object> joRows = (List<Object>) joJson.get("rows");
        for (int i = 0; i<joRows.size(); i++){
            Object [] arrStr = new Object[3];
            List<Object> temp = (List<Object>)joRows.get(i);
            String joKey = temp.get(0).toString()+"0000";
            if(map.containsKey(joKey)){
                String number = temp.get(1).toString();
                arrStr[0] = map.get(joKey);
                arrStr[1] = number.substring(0,number.indexOf("."));
                arrStr[2] = joKey;
                list.add(arrStr);
            }
        }
        for (int i=0;i<list.size()-1;i++){
            for (int j=0;j<list.size()-1-i;j++){
                Object[] o = list.get(j);
                Object[] o1 = list.get(j+1);
                if(Integer.valueOf(o[1].toString()) < Integer.valueOf(o1[1].toString())){
                    list.set(j,o1);
                    list.set(j+1,o);
                }
            }
        }
        ret.put("listJson",list);
        return ret;
    }

    //sql链接es
    public String ESQuery(String sqlStr){
        String esStr="{\"query\":\""+sqlStr+"\"}";
        JSONObject jsonObject=JSONObject.fromObject(esStr);
        return esUtils.post(jsonObject,Host);
    }



    @Override
    public Map<String, Object> orderDay(Integer day) {
        Map<String, Object> map = new HashMap<String, Object>();

        String beginDate = DateUtil.getFrontDayDate(-16);
        String endDate = DateUtil.getFrontDayDate(-1);

        if(null != day && day != 0){
            beginDate = DateUtil.getFrontDayDate(-day);
        }

        List<Map<String, Object>> list = orderPortProductsRepository.findByCreationDate(beginDate, endDate);
        map.put("jsonSum", list);
        return map;
    }

    @Override
    public Map<String, Object> orderCount(String zKey, String tagKey) {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            String str = "";
            String str1 = "";
            String dateStr = "";
            if (tagKey != null){//平台
                String[] keyArr = tagKey.split(",");
                int keyLan = keyArr.length;
                if(keyLan > 0){
                    for (int i = 0;i<keyLan;i++){
                        String keyStr = keyArr[i];
                        str += keyStr + ",";
                    }
                    str = " and OriginType in ("+ str.substring(0,str.length()-1)+ ") ";
                }
            }

            if (zKey != null){//日期
                if (!zKey.equals("0")){
                    String [] datasp = zKey.split("-");
                    LocalDate nowDate = LocalDate.now();
                    int year = nowDate.getYear();//年：一般用这个方法获取年
                    int month = nowDate.getMonthValue();//月：一般用这个方法获取月
                    int dayCount = getSurplusDays(year, month);//本月天数
                    dateStr = " and OrderTime>= '"+ zKey + "-01 00:00:00' and OrderTime<='"+ zKey + "-"+String.valueOf(dayCount) +" 23:59:59'";
                }
            }
            String commandText = "select a.fsm,a.fcn,b.sm,b.cn from ( "+
                                " select SUM(Sum/ 100.0) as fsm,toInt64(COUNT(1)) as fcn ,1 as cid from Orders WHERE AConsigneePhone2 global in " +
                                " (select AConsigneePhone2 from  Orders WHERE  OrderStatus not in(0, 100, 200) and IsReturn = 0 "+
                                " AND RIGHT(OrdersCode,2) <> 'BF' group by AConsigneePhone2 having count(AConsigneePhone2) > 1) "+
                                dateStr+ str+
                                " ) a FULL JOIN " +
                                "(SELECT SUM(Sum / 100) as sm, toInt64(COUNT(1)) as cn, 1 as cid FROM Orders WHERE OrderStatus not in (0, 100, 200) and IsReturn = 0 " + dateStr + str + " )b " +
                                "  ON a.cid = b.cid FORMAT JSON ";
            String url =  clickHouseUrl+"&query="+commandText;
            url= url.replaceAll(" ","%20").replaceAll(">","%3E").replaceAll("<","%3C");
            String retData = EsUtils.httpGetClickHouse(url);

            retData=retData.replaceAll(" ","");
            JSONObject json1=JSONObject.fromObject(retData.replaceAll(" ",""));

            JSONArray jsonArray1= json1.getJSONArray("data");
            Map<String, Object>  data = (Map<String, Object>) jsonArray1.get(0);
            double fsm = (double) data.get("fsm");
            double sm = (double) data.get("sm");

            java.text.NumberFormat NF = java.text.NumberFormat.getInstance();
            NF.setGroupingUsed(false);
            data.put("fsm",NF.format(fsm));
            data.put("sm",NF.format(sm));

            map.put("jsonSum", data);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return map;
    }


    public static int getSurplusDays(int year, int month){
        int days = 0;
        if (month != 2)
        {
            switch (month)
            {
                case 1:
                case 3:
                case 5:
                case 7:
                case 8:
                case 10:
                case 12:
                    days = 31;
                    break;
                case 4:
                case 6:
                case 9:
                case 11:
                    days = 30;
                    break;
            }
        }
        else
        {
            // 闰年
            if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0)
                days = 29;
            else
                days = 28;
        }
        return days;
    }



    public List<Map<String, Object>> replaceKey(List<DataDictory> list){
        List<Map<String, Object>> listData = new ArrayList<Map<String, Object>>();
        for (int i=0; i<list.size(); i++){
            Map<String, Object> map = new HashMap<String, Object>();
            DataDictory dataDictory = list.get(i);
            String text = dataDictory.getText();
            if(StringUtil.isEmpty(text)){
                continue;
            }
            map.put("TerminalDesc",text);

            String value = dataDictory.getValue();
            if(StringUtil.isEmpty(value)){
                continue;
            }
            map.put("ParentTerminalKey",value);
            listData.add(map);
        }
        return listData;
    }
}
