package com.tofly.watermeter.custom.service.statisticanalysis.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tofly.common.core.util.DateUtil;
import com.tofly.common.oauth.exception.ToflyDeniedException;
import com.tofly.watermeter.config.ComConstans;
import com.tofly.watermeter.custom.mapper.statisticanalysis.QueryStatisticsMapper;
import com.tofly.watermeter.custom.service.statisticanalysis.IQueryStatisticsService;
import com.tofly.watermeter.util.CallAPIUtil;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Service
@AllArgsConstructor
public class QueryStatisticsServiceImpl implements IQueryStatisticsService {

    private final QueryStatisticsMapper mapper;

    @Override
    @SneakyThrows
    public Page<HashMap<String,String>> getEventQuery(Page page,String startDate, String endDate, String yhbh,String yhxm) {
        Page<HashMap<String,String>> res = page;
        if (StringUtils.isBlank(yhbh) && StringUtils.isBlank(yhxm)) {
            return res;
        }
        YearMonth start = YearMonth.parse(startDate, DateTimeFormatter.ofPattern(DateUtil.DATE_DEFAULT_FORMAT));
        YearMonth end = YearMonth.parse(endDate, DateTimeFormatter.ofPattern(DateUtil.DATE_DEFAULT_FORMAT));
        if (end.isBefore(start)) {
            return res;
        }

        HashMap<String, String> params = new HashMap<>();
        params.put("ACTION","query");
        if(StringUtils.isNotBlank(yhxm)) {
            params.put("YHXM",yhxm);
        }
        if (StringUtils.isNotBlank(yhbh)) {
            params.put("YHBH",yhbh);
        }
        params.put("YHZT","1");
        String CUSTOMER_INFO_URL = "api/Business/GetCustomerData";
        Map customers = CallAPIUtil.callAPIUtil(params, CUSTOMER_INFO_URL);
        if (!customers.isEmpty() && "0000".equals(customers.get("code"))) {
            List<HashMap> users = JSON.parseArray(JSON.toJSONString(customers.get("data")), HashMap.class);
//            ArrayList<HashMap<String,String>> users = JSON.parseArray(JSON.toJSONString(customers.get("data")), Map.class);
//            List<HashMap<String,String>> users = (ArrayList<HashMap<String,String>>);
            long skip = page.getSize() * (page.getCurrent() - 1L);
//            List<HashMap<String, String>> resList = users.stream().skip(skip).limit(page.getSize()).collect(Collectors.toList())
//                    .stream().map(x -> {
//                        if (x.get("YHBH") != null) {
//                            HashMap<String, String> query = mapper.getEventQuery(startDate, endDate, x.get("YHBH"));
//                            x.putAll(query);
//                        }
//                        return x;
//                    }).collect(Collectors.toList());
            List<HashMap<String, String>> resList = users.stream().skip(skip).limit(page.getSize()).collect(Collectors.toList())
                    .stream().map(x -> {
                        HashMap<String, String> map = JSON.parseObject(JSON.toJSONString(x), HashMap.class);
                        if (map.get("YHBH") != null) {
                            HashMap<String, String> query = mapper.getEventQuery(startDate, endDate, map.get("YHBH"));
                            if (query != null && !query.isEmpty()) {
                                map.putAll(query);
                            } else {
                                map.put("cbsl", "0");
                                map.put("gdsl", "0");
                                map.put("zjsl", "0");
                            }
                        }
                        return map;
                    }).collect(Collectors.toList());
            page.setTotal(Long.parseLong(customers.get("count").toString()));
            page.setRecords(resList);
        } else {
            throw new ToflyDeniedException("网络繁忙，请重试。");
        }
//        return mapper.getEventQuery(page,startDate,endDate,queryCode);
        return res;
    }

    @Override
    public List getHouseholdsQuery(List<HashMap<String,String>> queryData) {
        if (queryData.size() <= 0) {
            return null;
        }
        List<Map<String,Object>> res = new ArrayList<>();
        for (HashMap<String, String> query : queryData) {
            List<String> list = mapper.getHouseholdsQuery(query);
                HashMap<String, Object> map = new HashMap<>();
                map.put("yhbhList", list);
                map.put("query",query);
                res.add(map);
        }
        return res;
    }

    @Override
    public Page<HashMap<String, String>> getHouseholdsDetail(Page page, String query) {
        if (query != null && query.length() > 0 ) {
            String script = StringEscapeUtils.unescapeJavaScript(query);
            HashMap<String,String> parseObject = JSONObject.parseObject(script, HashMap.class);
            return  mapper.getHouseholdsQueryDetail(page,parseObject);
        }
        return null;
    }



    @Override
    public Page getEventQueryDetail(Page page,String quertType, String startDate, String endDate, String khbh) {
        if ("cb".equals(quertType)) {
            return mapper.getCBEvent(page,startDate,endDate,khbh);
        } else if ("gd".equals(quertType)) {
            return mapper.getGDEvent(page,startDate,endDate,khbh);
        } else if ("zj".equals(quertType)) {
            return mapper.getZJEvent(page,startDate,endDate,khbh);
        } else {
            return page;
        }
    }

//    @Override
//    public List getHouseholdsQuery(List<String> queryData) {
//        if (queryData.size() <= 0) {
//            return null;
//        }
//        List<Map<String,Object>> res = new ArrayList<>();
//        for (String queryDatum : queryData) {
//
//        }
//        for (String query : queryList) {
//            String[] queryList = queryData.split(ComConstans.CSV);
//            HashMap parseObject = JSONObject.parseObject(query, HashMap.class);
//            if(!parseObject.isEmpty()){
//                List<String> list = mapper.getHouseholdsQuery(parseObject);
//                HashMap<String, Object> map = new HashMap<>();
//                map.put("yhbhList",list);
//                res.add(map);
//            }
//        }
//        return res;
//    }
}
