package org.jeecg.modules.newWarning.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.jeecg.modules.newWarning.mapper.RealTimeZjMapper;
import org.jeecg.modules.newWarning.service.RealTimeZjService;
import org.jeecg.modules.warning.entity.ConditionDateItem;
import org.jeecg.modules.warning.entity.ConditionItem;
import org.jeecg.modules.warning.entity.HttpResultItem;
import org.jeecg.modules.warning.entity.Ltd;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

@Service
@DS("yjDataSource")
public class RealTimeZjServiceImpl extends ServiceImpl<RealTimeZjMapper, Ltd> implements RealTimeZjService {

    @Resource
    private RealTimeZjMapper realTimeZjMapper;

    @Override
    @Cacheable(cacheNames="ltd2",unless = "#result.size() == 0 or !#map.containsKey('timeEnd')")
    public List<Ltd> selectList(Map<String, Object> map) {
        List<Ltd> result = realTimeZjMapper.selectList(map);
        return result;
    }

    @Override
    public List<Ltd> selectYData(Map<String, Object> map) {
        return realTimeZjMapper.selectYData(map);
    }

    @Override
    public List<Ltd> selectNewOne(String table) {
        return realTimeZjMapper.selectNewOne(table);
    }

    @Override
    public Ltd selectDate(Map<String, Object> map) {
        return realTimeZjMapper.selectDate(map);
    }

    @Override
    public Ltd selectByTimeAndJh(String time, String table){
        return realTimeZjMapper.selectByTimeAndJh(time , table);
    }

    @Override
    public List<ConditionItem> getCondition( String startTime, String endTime , String table){


        LocalDateTime now = LocalDateTime.now();
        // 创建一个日期时间格式器来格式化输出
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

        if (StringUtils.isEmpty(startTime)){

            // 获取一周前的日期时间
            LocalDateTime oneWeekAgo = now.minus(Period.ofWeeks(1));

            startTime = oneWeekAgo.format(formatter);
        }

        if (StringUtils.isEmpty(endTime)){
            // 获取一周前的日期时间

            endTime = now.format(formatter);
        }

        // 解析开始和结束日期
        LocalDate startDate = LocalDate.parse(startTime, formatter);
        LocalDate endDate = LocalDate.parse(endTime, formatter);

        // 创建一个列表来保存每一天
        List<ConditionItem> datesInRange = new ArrayList<>();

        // 生成日期范围内的每一天
        while (!startDate.isAfter(endDate)) {
            ConditionItem item = new ConditionItem();
            item.setDateString(startDate.format(formatter));
            item.setConditionDateItem(new ArrayList<>());
            datesInRange.add(item);
            startDate = startDate.plusDays(1);
        }

        startTime += " 00:00:00";
        endTime += " 23:59:59";


        List<ConditionDateItem> list =  realTimeZjMapper.getCondition(startTime,endTime,table);

        for (ConditionItem item : datesInRange){

            for (ConditionDateItem dateItem : list){
                String timeStr = dateItem.getTime().substring(0,10);
                if (timeStr.equals(item.getDateString())){
                    item.getConditionDateItem().add(dateItem);
                }
            }
        }

        return datesInRange;
    }

    @Override
    public List<Map<String, Object>> selectAllDate(Map<String, Object> map) {
        return realTimeZjMapper.selectAllDate(map);
    }

    /**
     *
     * @param jh
     * @param type h为历史数据
     * @return
     */
    @Override
    public List<Ltd> selectJwssList(String jh, String type) {
        String ltdParam =  jh.replace('-', '_');
        String url="http://10.68.224.20:9093/v1/structuredData/serviceData/jwss1h?app_key=meta";
        if(type.equals("h")){
            url="http://10.68.224.20:9093/v1/structuredData/serviceData/jwss?app_key=meta";
        }

        String jsonStr=String.format("{\r\n  \"jh\": {\r\n        \"condition\": [\r\n            {\r\n                \"operational\": \"in\",\r\n                \"value\": \"%s\",\r\n                \"relation\": \"and\"\r\n            }\r\n        ]\r\n    }\r\n}",ltdParam);
        String result2 = HttpRequest.post(url)
                .body(jsonStr)
                .execute().body();
        JSONObject json= JSONUtil.parseObj(result2);
        try {
            String statusCode=json.getStr("statusCode");
            Object item=json.get("data");
            HttpResultItem res= BeanUtil.toBean(item, HttpResultItem.class);
            List<Ltd> list=res.getRows();
            if(list.size()>0){
                for (Ltd item2:list)
                {
                    item2.setTime(item2.getTime().substring(0,19));
                }
            }
            return list;
        }catch(Exception ex){
            return null;
        }

    }


}
