/*
 * Author: wangjian
 * 生成ServiceImpl
 */
package com.tofly.xrtygis.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tofly.common.core.util.DateUtil;
import com.tofly.common.core.util.StringUtil;
import com.tofly.common.oauth.exception.ToflyDeniedException;
import com.tofly.xrtygis.custom.entity.dma.ConstomTableList;
import com.tofly.xrtygis.custom.entity.enums.CompanyName;
import com.tofly.xrtygis.custom.util.Date7Utils;
import com.tofly.xrtygis.custom.util.DateTimeUtil;
import com.tofly.xrtygis.em.Constant;
import com.tofly.xrtygis.em.ExcelExportFileTypeEnum;
import com.tofly.xrtygis.entity.Dmanightflow;
import com.tofly.xrtygis.entity.Dmatable;
import com.tofly.xrtygis.service.DmanightflowService;
import com.tofly.xrtygis.service.DmatableService;
import com.tofly.xrtygis.strategy.ExcelStrategyContext;
import com.tofly.xrtygis.util.ExcelUtil;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.tofly.xrtygis.mapper.DmanightflowMapper;

import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 夜间最小流量分析表
 *
 * @author wangjieliu
 * @date Tue May 25 00:00:00 CST 2021
 */
@Service("dmanightflowService")

public class DmanightflowServiceImpl extends ServiceImpl<DmanightflowMapper, Dmanightflow> implements DmanightflowService {
   @Autowired
    private  ExcelStrategyContext excelStrategyContext;

    @Autowired
    private  DmatableService dmatableService;

    @Value("${xrty.ftp.topCompanyName}")
    private String topCompanyName;

    @Override
    public IPage<Map> getMinFlow(HttpServletResponse response, String tableIds, String startTime, String endTime, String flag, String templateFlag, Page page) {
        //判断时间
        if (StringUtil.isEmpty(startTime) || StringUtil.isEmpty(endTime)) {
            throw new ToflyDeniedException("请选择月份时间");
        }
        if (StringUtil.isEmpty(tableIds)) {
            throw new ToflyDeniedException("请传入仪表ID");
        }
        //格式化时间
        Date startDate = DateUtil.formatDate(startTime, "yyyy-MM-dd");
        Date endDate = DateUtil.formatDate(endTime, "yyyy-MM-dd");
        //计算3个月后的时间
//        Date addDate = Date7Utils.addNextPeriod(3, startDate);
//        //比较时间是否大于3个月之后的时间
//        if (endDate.after(addDate)) {
//            //如果超过了3个月，则最多取到3个月的数据
//            endDate = addDate;
//        }
        if ("1".equals(flag)) {
            return baseMapper.getMinFlowCollet(tableIds, startDate, endDate,page);
        } else if ("2".equals(flag)) {
            //需要导出的
            if ("1".equals(templateFlag)) {
                List<Map> mapList = baseMapper.getMinFlowDetail(tableIds, startDate, endDate);
                //修改时间戳
//                mapList.forEach(k->{
//                    k.put("uday",k.get("uday").toString().substring(0,10));
//                });
                // 根据templateServiceType,templateFlag获取对应模板数据
                ExcelExportFileTypeEnum excelExportFileTypeEnum = ExcelExportFileTypeEnum.getExcelExportFileTypeEnum("nightFlowServiceImpl", templateFlag);
                if (null == excelExportFileTypeEnum) {
                    return null;
                }
                //将查询的结果转json字符串的格式，因为导出的时候只能传一个字符串；toJSONStringWithDateFormat可以转换时间格式字符串
                String resultListToString = JSONArray.toJSONStringWithDateFormat(mapList,"yyyy-MM-dd");
                // 从模型类型枚举根据templateServiceType获取策略对应模板数据
                List<Map<String, Object>> dataList = excelStrategyContext.getExportData("nightFlowServiceImpl", templateFlag, resultListToString);
                ExcelUtil.export(dataList.get(0), excelExportFileTypeEnum, Constant.FILE_PATH_TEST_EXPORT_EXCEL, response);
                return null;
            }else {
                IPage<Map> iPage = baseMapper.getMinFlowDetailPage(tableIds, startDate, endDate , page);
                List<Map> mapList = iPage.getRecords();
                //修改时间戳
                mapList.forEach(k->{
                    k.put("uday",k.get("uday").toString().substring(0,10));
                });
                iPage.setRecords(mapList);
                return iPage;
            }
        }
        return null;
    }

    @Override
    public ConstomTableList getTableTree(String isFlow) {
        //查询所有区域观察表
        List<Dmatable> dmatableList = dmatableService.list(Wrappers.<Dmatable>lambdaQuery().eq("1".equals(isFlow) , Dmatable::getIsflow , "1")
                .eq("2".equals(isFlow) , Dmatable::getIspress , "1"));
        // 自定义一个存放顶级公司名称的对象
        ConstomTableList dmatable = new ConstomTableList();
        dmatable.setId(0L);
        dmatable.setSchName(topCompanyName);
        List<Map> mapList = JSONObject.parseArray(JSONObject.toJSONString(dmatableList) , Map.class);
        //存放区域观察表
        dmatable.setTableList(mapList);
        return new ConstomTableList();
    }
    @Override
    public Boolean nightMinimumFlowAnalysis(Date date){
        // 获取当前日期观察表(2:00 ~ 4:00)流量
        LocalDateTime now = DateTimeUtil.fromLong2LocalDateTime(date.getTime());
        Date startTime = DateTimeUtil.convertLDTToDate(now.plusHours(2));
        Date endTime = DateTimeUtil.convertLDTToDate(now.plusHours(4));
        List<Dmanightflow> flowList = baseMapper.getFlowList(startTime, endTime);
        List<Dmanightflow> pressureList = baseMapper.getPressureList(startTime, endTime);
        flowList.forEach(info->{
            // 保证 流量与压力 采集时间在 5分钟之内
            LocalDateTime time1 = DateTimeUtil.fromLong2LocalDateTime(info.getMintime().getTime());
            Long tableId = info.getTableId();
            pressureList.forEach(pressure->{
                Long pressureTableId = pressure.getTableId();
                LocalDateTime time2 = DateTimeUtil.fromLong2LocalDateTime(pressure.getMintime().getTime());
                LocalDateTime startTime1 = time1.minusMinutes(5);
                LocalDateTime endTime1 = time1.plusMinutes(5);
                if(null!=pressureTableId){
                    if(tableId.equals(pressureTableId)){
                        if(startTime1.isBefore(time2) || time2.isBefore(endTime1)){
                            info.setMinpval(pressure.getMinpval());
                        }

                    }
                }


            });
            Date time = new Date();
            info.setUday(time);
            info.setUtime(time);
            info.setUmonth(DateTimeUtil.getLocalDate(time,DateTimeUtil.MONTHS_FORMAT));
        });
        return this.saveBatch(flowList);
    }

}
