/*
 * 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.api.GdglinfoClient;
import com.tofly.common.core.entity.ResultRespone;
import com.tofly.common.core.util.Date8Util;
import com.tofly.common.core.util.DateUtil;
import com.tofly.common.core.util.StringUtil;
import com.tofly.common.oauth.exception.ToflyDeniedException;
import com.tofly.common.oauth.util.SecurityUtils;
import com.tofly.pojo.GdglinfoExtendDto;
import com.tofly.xrtygis.custom.entity.dma.CostomEval;
import com.tofly.xrtygis.custom.entity.dma.CostomWarn;
import com.tofly.xrtygis.custom.entity.dma.DmawarnhandleDto;
import com.tofly.xrtygis.custom.util.Date7Utils;
import com.tofly.xrtygis.em.Constant;
import com.tofly.xrtygis.em.ExcelExportFileTypeEnum;
import com.tofly.xrtygis.entity.Dmawarnhandle;
import com.tofly.xrtygis.mapper.DmawarnhandleMapper;
import com.tofly.xrtygis.service.DmawarnhandleService;
import com.tofly.xrtygis.strategy.ExcelStrategyContext;
import com.tofly.xrtygis.util.ExcelUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 异常处理信息表：TF_YWPN_DMAWARNHANDLE_W
 *
 * @author admin
 * @date Wed Mar 10 00:00:00 CST 2021
 */
@Service("dmawarnhandleService")
public class DmawarnhandleServiceImpl extends ServiceImpl<DmawarnhandleMapper, Dmawarnhandle> implements DmawarnhandleService {
    @Autowired
    private ExcelStrategyContext excelStrategyContext;
    @Autowired
    private GdglinfoClient gdglinfoClient;

    @Override
    public IPage getWarn(HttpServletResponse response, Page page, CostomWarn costomWarn) {
        Date startDate = costomWarn.getStartTime();
        Date endDate = costomWarn.getEndTime();
        String tempLate = costomWarn.getTempLate();
        String isPf = costomWarn.getIshandle();
        String type = costomWarn.getWarnType();
        if (StringUtil.isNull(startDate) || StringUtil.isNull(endDate)) {
            throw new ToflyDeniedException("请输入时间段");
        }
        //判断时间
        //计算12个月后的时间
        Date addDate = Date7Utils.addNextPeriod(12, startDate);
        //比较时间是否大于12个月之后的时间
        if (endDate.after(addDate)) {
            //如果超过了12个月，则最多取到12个月的数据
            endDate = addDate;
        }
        if ("1".equals(tempLate)) {
            List<Dmawarnhandle> mapList = this.list(Wrappers.<Dmawarnhandle>lambdaQuery()
                    .eq(StringUtil.isNotEmpty(isPf), Dmawarnhandle::getIshandle, isPf)
                    .eq(StringUtil.isNotEmpty(type), Dmawarnhandle::getWarnType, type)
                    .le(StringUtil.isNotNull(endDate), Dmawarnhandle::getWarnTime, endDate)
                    .ge(StringUtil.isNotNull(startDate), Dmawarnhandle::getWarnTime, startDate)
                    .orderByDesc(Dmawarnhandle::getWarnTime)
                    .select(Dmawarnhandle::getId, Dmawarnhandle::getWarnType, Dmawarnhandle::getWarnTime,
                            Dmawarnhandle::getWarnValue, Dmawarnhandle::getWarnNotes, Dmawarnhandle::getWarnMonth, Dmawarnhandle::getIshandle,
                            Dmawarnhandle::getNosendOrderBz, Dmawarnhandle::getNosendOrderReason));
            mapList.forEach(k -> {
                k.setTime(DateUtil.parseDateToStr("yyyy-MM-dd HH:mm:ss", k.getWarnTime()));
                if ("1".equals(k.getWarnType())) {
                    //处理数据单位
                    k.setWarnValue(k.getWarnValue() + "m³/h");
                } else {
                    k.setWarnValue(k.getWarnValue() + "%");
                }
            });
            // 根据templateServiceType,templateFlag获取对应模板数据
            ExcelExportFileTypeEnum excelExportFileTypeEnum = ExcelExportFileTypeEnum.getExcelExportFileTypeEnum("warnInfoServiceImpl", tempLate);
            if (null == excelExportFileTypeEnum) {
                return null;
            }
            //将查询的结果转json字符串的格式，因为导出的时候只能传一个字符串
            String resultListToString = JSONArray.toJSONString(mapList);
            // 从模型类型枚举根据templateServiceType获取策略对应模板数据
            List<Map<String, Object>> dataList = excelStrategyContext.getExportData("warnInfoServiceImpl", tempLate, resultListToString);
            ExcelUtil.export(dataList.get(0), excelExportFileTypeEnum, Constant.FILE_PATH_TEST_EXPORT_EXCEL, response);
            return null;
        } else {
            IPage warnPage = this.page(page, Wrappers.<Dmawarnhandle>lambdaQuery()
                    .eq(StringUtil.isNotEmpty(isPf), Dmawarnhandle::getIshandle, isPf)
                    .eq(StringUtil.isNotEmpty(type), Dmawarnhandle::getWarnType, type)
                    .le(StringUtil.isNotNull(endDate), Dmawarnhandle::getWarnTime, endDate)
                    .ge(StringUtil.isNotNull(startDate), Dmawarnhandle::getWarnTime, startDate)
                    .orderByDesc(Dmawarnhandle::getWarnTime)
                    .select(Dmawarnhandle::getId, Dmawarnhandle::getWarnType, Dmawarnhandle::getWarnTime,Dmawarnhandle::getOrderId,
                            Dmawarnhandle::getWarnValue, Dmawarnhandle::getWarnNotes, Dmawarnhandle::getWarnMonth, Dmawarnhandle::getIshandle,
                            Dmawarnhandle::getNosendOrderBz, Dmawarnhandle::getNosendOrderReason));
            List<Dmawarnhandle> mapList = warnPage.getRecords();
            mapList.forEach(k -> {
                k.setTime(DateUtil.parseDateToStr("yyyy-MM-dd HH:mm:ss", k.getWarnTime()));
                if ("1".equals(k.getWarnType())) {
                    //处理数据单位
                    k.setWarnValue(k.getWarnValue() + "m³/h");
                } else {
                    k.setWarnValue(k.getWarnValue() + "%");
                }
            });
            List<Map> maps = JSONObject.parseArray(JSONObject.toJSONString(mapList), Map.class);
            //解决返回全部字段问题，只返回有数据的字段，但是与上面的代码有点重复，小耗时间了 ，后面优化一下
            warnPage.setRecords(maps);
            return warnPage;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean warnHandle(DmawarnhandleDto dmawarnhandle) {
        String id = dmawarnhandle.getId();
        String handle = dmawarnhandle.getIshandle();
        Date orderTime = dmawarnhandle.getOrderTime();
        Long user = SecurityUtils.getUserId();
        Date current = Date8Util.getCurrentDate();
        Long noSendOrderReason = dmawarnhandle.getNosendOrderReason();
        String noSendOrderBz = dmawarnhandle.getNosendOrderBz();
//        Long orderId = dmawarnhandle.getOrderId();
        if (StringUtil.isEmpty(id)) {
            throw new ToflyDeniedException("请传入ID");
        }
        //根据ID查询是否处理了
        Dmawarnhandle dmawarn = this.getOne(Wrappers.<Dmawarnhandle>lambdaQuery().eq(Dmawarnhandle::getId, id));
        String ishandle = dmawarn.getIshandle();
        if (!"0".equals(ishandle)) {
            throw new ToflyDeniedException("当前状态不能操作");
        }
        //派单
        if ("2".equals(handle)) {
            if (StringUtil.isNull(orderTime)) {
                throw new ToflyDeniedException("请传入派工时间");
            }
            //工单参数
            GdglinfoExtendDto dto = new GdglinfoExtendDto();
            dto.setGdlx(dmawarnhandle.getGdlx());
            dto.setGdxf1(dmawarnhandle.getGdxf1());
            dto.setGdxf2(dmawarnhandle.getGdxf2());
            dto.setLcid(dmawarnhandle.getLcid());
            dto.setSlry(dmawarnhandle.getSlry());
            dto.setGdms(dmawarnhandle.getGdms());
            dto.setDjry(dmawarnhandle.getDjry());
            dto.setDjbm(dmawarnhandle.getDjbm());
            dto.setLcjd(dmawarnhandle.getLcjd());
            dto.setSlbm(dmawarnhandle.getSlbm());
            dto.setIsRxlx(dmawarnhandle.getIsRxlx());
            dto.setJjcd(dmawarnhandle.getJjcd());
            dto.setGddjZt(dmawarnhandle.getGddjZt());
            dto.setSqry(dmawarnhandle.getSqry());
            dto.setResultdispList(dmawarnhandle.getResultdispList());

            //工单登记，远程调用
            ResultRespone resultRespone = gdglinfoClient.saveGdglInfo(dto);
            int codeStatus = resultRespone.getCode();
            //code为 1 时，代表登记工单成功
            if (codeStatus == 1) {
                String gdid = resultRespone.getResult().toString();
                Long orderId = Long.parseLong(gdid);
                boolean status = this.update(Wrappers.<Dmawarnhandle>lambdaUpdate()
                        .eq(Dmawarnhandle::getId, id).set(Dmawarnhandle::getCreateTime, current)
                        .set(Dmawarnhandle::getCreateUser, user).set(Dmawarnhandle::getIshandle, handle)
                        .set(Dmawarnhandle::getOrderTime, new Date())
                        .set(Dmawarnhandle::getOrderId, orderId));
                if (!status) {
                    //如果修改不成功，则删除之前登记的工单

                }
            }else {
                throw new ToflyDeniedException(resultRespone.getMessage());
            }
        }
        //不派单
        else if ("1".equals(handle)) {
            if (StringUtil.isNull(noSendOrderReason)) {
                throw new ToflyDeniedException("请选择不派单原因类别");
            }
            this.update(Wrappers.<Dmawarnhandle>lambdaUpdate()
                    .eq(Dmawarnhandle::getId, id).set(Dmawarnhandle::getCreateTime, current)
                    .set(Dmawarnhandle::getCreateUser, user).set(Dmawarnhandle::getIshandle, handle)
                    .set(Dmawarnhandle::getNosendOrderReason, noSendOrderReason)
                    .set(StringUtil.isNotEmpty(noSendOrderBz), Dmawarnhandle::getNosendOrderBz, noSendOrderBz));
            //需求还没有定，就是测试提的
            //添加报警信息数据
//            Warn warn = new Warn();
//            warn.setWarnType("7");
//            warn.setScadaTime(new Date());
//            warn.setNotes(dmawarn.getWarnTypeName()+"-"+dmawarn.getWarnNotes());
//            warn.setIsconfirm("0");
//            warn.setIsclear("0");
//            warn.setIsloc("0");
//            warnService.save(warn);
////            String tableName = WARNHISTORY + Date8Util.getYearMonth();
////            if (!customPollSourceMapper.doesItExistTable(tableName).isEmpty()) {
////                //添加到历史表
////                customPollSourceMapper.insertWarnHistory(tableName, warn.getId(), maxId);
////            }
        }
        return true;
    }

    @Override
    public Map analyze(CostomWarn costomWarn) {
        Date startDate = costomWarn.getStartTime();
        Date endDate = costomWarn.getEndTime();
        if (StringUtil.isNull(startDate) || StringUtil.isNull(endDate)) {
            throw new ToflyDeniedException("请输入时间段");
        }
        //判断时间
        //计算12个月后的时间
        Date addDate = Date7Utils.addNextPeriod(12, startDate);
        //比较时间是否大于12个月之后的时间
        if (endDate.after(addDate)) {
            //如果超过了12个月，则最多取到12个月的数据
            endDate = addDate;
        }
        //夜间最小流量异常占比
        Map nightMinMap = baseMapper.analyze(startDate, endDate, "1");
        //产销差异常占比
        Map podDiffMap = baseMapper.analyze(startDate, endDate, "2");
        Map<String, Map> map = new HashMap();
        map.put("nightMinMap", nightMinMap);
        map.put("podDiffMap", podDiffMap);
        return map;
    }

    @Override
    public IPage resultEval(HttpServletResponse response, Page page, CostomEval costomEval) {

        String tempLate = costomEval.getTempLate();
        //派工时间
        Date orderStartTime = costomEval.getOrderStartTime();
        Date orderEndTime = costomEval.getOrderEndTime();
        //完工时间
        Date handStartTime = costomEval.getHandStartTime();
        Date handEndTime = costomEval.getHandEndTime();
        //评价时间
        Date evaStartTime = costomEval.getEvaStartTime();
        Date evaEndTime = costomEval.getEvaEndTime();

        if (StringUtil.isNotNull(orderStartTime) && StringUtil.isNotNull(orderEndTime)) {
            //判断时间
            //计算12个月后的时间
            Date addDate = Date7Utils.addNextPeriod(12, orderStartTime);
            //比较时间是否大于12个月之后的时间
            if (orderEndTime.after(addDate)) {
                //如果超过了12个月，则最多取到12个月的数据
                orderEndTime = addDate;
            }
        }
        if (StringUtil.isNotNull(handStartTime) && StringUtil.isNotNull(handEndTime)) {
            //判断时间
            //计算12个月后的时间
            Date addDate = Date7Utils.addNextPeriod(12, handStartTime);
            //比较时间是否大于12个月之后的时间
            if (handEndTime.after(addDate)) {
                //如果超过了12个月，则最多取到12个月的数据
                handEndTime = addDate;
            }
        }
        if (StringUtil.isNotNull(evaStartTime) && StringUtil.isNotNull(evaEndTime)) {
            //判断时间
            //计算12个月后的时间
            Date addDate = Date7Utils.addNextPeriod(12, evaStartTime);
            //比较时间是否大于12个月之后的时间
            if (evaEndTime.after(addDate)) {
                //如果超过了12个月，则最多取到12个月的数据
                evaEndTime = addDate;
            }
        }

        if ("1".equals(tempLate)) {
            List<Map> list = baseMapper.getResultEvalNotPage(costomEval);
            // 根据templateServiceType,templateFlag获取对应模板数据
            ExcelExportFileTypeEnum excelExportFileTypeEnum = ExcelExportFileTypeEnum.getExcelExportFileTypeEnum("resultEvalServiceImpl", tempLate);
            if (null == excelExportFileTypeEnum) {
                return null;
            }
            //将查询的结果转json字符串的格式，因为导出的时候只能传一个字符串
            String resultListToString = JSONArray.toJSONString(list);
            // 从模型类型枚举根据templateServiceType获取策略对应模板数据
            List<Map<String, Object>> dataList = excelStrategyContext.getExportData("resultEvalServiceImpl", tempLate, resultListToString);
            ExcelUtil.export(dataList.get(0), excelExportFileTypeEnum, Constant.FILE_PATH_TEST_EXPORT_EXCEL, response);
            return null;
        } else {
            IPage<Map> iPage = baseMapper.getResultEval(page, costomEval);
            return iPage;
        }

    }

    /**
     * dma工单查询
     *
     * @param page  page
     * @param start start
     * @param end   end
     * @return page
     */
    @Override
    public Page workOrderQuery(Page page, String start, String end) {
        return baseMapper.workOrderQuery(page, start, end);
    }
}
