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

import com.tofly.common.core.entity.ResultRespone;
import com.tofly.common.core.util.DateUtil;
import com.tofly.pojo.message.Messagepush;
import com.tofly.pojo.message.Messagerecipient;
import com.tofly.watermeter.config.TimeTaskFeign;
import com.tofly.watermeter.custom.dto.DmawarnhandleDto;
import com.tofly.watermeter.custom.mapper.TimedTaskMapper;
import com.tofly.watermeter.custom.service.ReadDataCheckThreeService;
import com.tofly.watermeter.custom.service.TimedTaskService;
import com.tofly.watermeter.custom.service.sxj.SynchronousAboutService;
import com.tofly.watermeter.service.BwrkdetailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class TimedTaskServiceImpl implements TimedTaskService {
    @Autowired
    private SynchronousAboutService synchronousAboutService;
    @Autowired
    private TimedTaskMapper timedTaskMapper;
    @Autowired
    private TimeTaskFeign timeTaskFeign;
    @Autowired
    private ReadDataCheckThreeService readDataCheckThreeService;
    @Autowired
    private BwrkdetailService bwrkdetailService;
    @Value("${meter.warnTime.minTime}")
    private int minTime;
    @Value("${meter.intervalHour}")
    private int intervalHour;

    private static final String MESSAGE_TABLE_NAME = "TF_YWPN_MESSAGEPUSH_W";
    private static final String MESSAGERECIPIENT = "TF_YWPN_MESSAGERECIPIENT_W";

    /**
     * @param thisWay 0 前一个月财务填报  1 当天日填报
     */
    @Override
    public boolean sendMsgAbout(Long thisWay, Long menuId) {
        List<Long> aubotUserList = timedTaskMapper.getAubotUser(menuId);

        if (!aubotUserList.isEmpty()) {
            Messagepush mp;
            Messagerecipient mr;
            int nowMonth = DateUtil.getNowMonth();
            int month = nowMonth == 1 ? 12 : nowMonth - 1;
            String msg;
            if (thisWay == 0) {
                msg = "请填写上月" + month + "月份的财务填报";
            } else {
                msg = "请填写今日实际管理-日填报";
            }


            for (Long userId : aubotUserList) {

                Long maxId = bwrkdetailService.getMaxId(MESSAGE_TABLE_NAME);

                mp = new Messagepush();
                mr = new Messagerecipient();
                mp.setId(maxId);
                mp.setMessage(msg);
                mp.setTopic("制水成本-实际管理填报");
                mp.setType("0");
                if (thisWay == 0) {
                    mp.setRouteIp("realCostManagement/produceWaterRealPerChange");
                } else {
                    mp.setRouteIp("realCostManagement/produceWaterRealUsage");
                }
                mp.setCreateTime(new Date());
                mp.setCreateUser(0L);

                timedTaskMapper.insertMsg(mp);

                mr.setRecipient(userId);
                mr.setMessageId(maxId);
                mr.setFlag("0");

                timedTaskMapper.insertMsgStateClient(mr);
//                messageStateClient.save(mr);
            }
        }
        return true;
    }

    /**
     * 发送消息与短信
     *
     * @return Boolean
     */
    @Override
    public boolean sendWarnMsgAndSMS() {
        List<Map<String, Object>> userInfoList = timedTaskMapper.getMsgAndSMSUser();
        List<Map<String, Object>> thresholdValueList = timedTaskMapper.thresholdValue(minTime);
        if (!userInfoList.isEmpty()) {

            Messagepush mp;
            Messagerecipient mr;

            for (Map<String, Object> map : userInfoList) {
                String itcd = map.get("itcd").toString();
                String msgUser = !StringUtils.isEmpty(map.get("msgUser")) ? map.get("msgUser").toString() : null;
                String smsUser = !StringUtils.isEmpty(map.get("smsUser")) ? map.get("smsUser").toString() : null;
                String smsWarn = !StringUtils.isEmpty(map.get("smsWarn")) ? map.get("smsWarn").toString() : null;
                String msgWarn = !StringUtils.isEmpty(map.get("msgWarn")) ? map.get("msgWarn").toString() : null;

                String warnNeedInfo = timedTaskMapper.warnNeedInfo(itcd);

                if (!StringUtils.isEmpty(msgUser) && !"1".equals(msgWarn) && !StringUtils.isEmpty(warnNeedInfo)) {
                    String[] msgUserList = msgUser.split(",");

                    for (String user : msgUserList) {
                        Long maxId = bwrkdetailService.getMaxId(MESSAGE_TABLE_NAME);
                        mp = new Messagepush();
                        mr = new Messagerecipient();
                        mp.setId(maxId);
                        mp.setMessage(warnNeedInfo);
                        mp.setTopic("SCADA报警信息提醒");
                        mp.setType("0");
                        mp.setRouteIp("");
                        mp.setCreateTime(new Date());
                        mp.setCreateUser(0L);

                        timedTaskMapper.insertMsg(mp);

                        mr.setRecipient(Long.valueOf(user));
                        mr.setMessageId(maxId);
                        mr.setFlag("0");
                        timedTaskMapper.insertMsgStateClient(mr);

                        timedTaskMapper.updateWarnTable(itcd, "MSG_WARN");
                    }
                }
                if (!StringUtils.isEmpty(smsUser) && !"1".equals(smsWarn) && !StringUtils.isEmpty(warnNeedInfo)) {
                    List<String> userTel = timedTaskMapper.getUserTel(Arrays.asList(smsUser.split(",")));
                    if (!userTel.isEmpty()) {
                        for (String tel : userTel) {
                            timeTaskFeign.sendNoteFeign(tel, warnNeedInfo);
                            timedTaskMapper.updateWarnTable(itcd, "SMS_WARN");
                        }
                    }
                }
            }
        }
        //指标突升突降报警
        if (!thresholdValueList.isEmpty()) {

            Messagepush mp = new Messagepush();
            Messagerecipient mr = new Messagerecipient();

            for (Map<String, Object> map : thresholdValueList) {
                String itcd = map.get("itcd").toString();
                String msgUser = !StringUtils.isEmpty(map.get("msgUser")) ? map.get("msgUser").toString() : null;
                String upWarn = !StringUtils.isEmpty(map.get("upWarn")) ? map.get("upWarn").toString() : null;
                String downWarn = !StringUtils.isEmpty(map.get("downWarn")) ? map.get("downWarn").toString() : null;
                String downSms = !StringUtils.isEmpty(map.get("downSms")) ? map.get("downSms").toString() : null;
                String upSms = !StringUtils.isEmpty(map.get("upSms")) ? map.get("upSms").toString() : null;
                String smsUser = !StringUtils.isEmpty(map.get("smsUser")) ? map.get("smsUser").toString() : null;
                String openUpWarn = !StringUtils.isEmpty(map.get("openUpWarn")) ? map.get("openUpWarn").toString() : null;
                String openDownWarn = !StringUtils.isEmpty(map.get("openDownWarn")) ? map.get("openDownWarn").toString() : null;


                if (!StringUtils.isEmpty(msgUser)) {

                    List<String> msgUserList = Arrays.asList(msgUser.split(","));

                    mp.setTopic("SCADA报警信息提醒");
                    mp.setType("0");
                    mp.setCreateTime(new Date());
                    mp.setCreateUser(0L);
                    mp.setRouteIp("");
                    mr.setFlag("0");

                    timedTaskMapper.updateWarnTable(itcd, "MSG_WARN");

                    if (!StringUtils.isEmpty(openUpWarn) && "1".equals(openDownWarn) && !"1".equals(upWarn)) {
                        //间隔时间
                        Double upWarnTime = Double.parseDouble(map.get("upWarnTime").toString());
                        //发送短信需要达到的值
                        double upWarnVal = Double.parseDouble(map.get("upWarnVal").toString());
                        //查询区间最大、最小报警的值和时间
                        Map<String, Object> maxWarnValAndTime = timedTaskMapper.getMaxWarnValAndTime(itcd, upWarnTime);
                        Map<String, Object> minWarnValAndTime = timedTaskMapper.getMinWarnValAndTime(itcd, upWarnTime);
                        if (maxWarnValAndTime != null && !maxWarnValAndTime.isEmpty() && minWarnValAndTime != null && !minWarnValAndTime.isEmpty()) {
                            //值
                            double maxVal = Double.parseDouble(maxWarnValAndTime.get("itval").toString());
                            double minVal = Double.parseDouble(minWarnValAndTime.get("itval").toString());
                            //时间
                            String maxTime = maxWarnValAndTime.get("scadaTime").toString();
                            String minTime = minWarnValAndTime.get("scadaTime").toString();
                            //最大值的时间如果小于最小值时间视为突降，这里不做处理
                            if (maxTime.compareTo(minTime) > 0) {

                                double val = maxVal - minVal;
                                if (val > upWarnVal) {
                                    Long maxId = bwrkdetailService.getMaxId(MESSAGE_TABLE_NAME);
                                    mp.setId(maxId);
                                    mp.setMessage(timedTaskMapper.upWarnInfo(itcd, minVal, upWarnTime, maxVal, val));
                                    timedTaskMapper.insertMsg(mp);
                                    mr.setMessageId(maxId);
                                    Long mrId = bwrkdetailService.getMaxId(MESSAGERECIPIENT);
                                    for (int i = 0; i < msgUserList.size(); i++) {
                                        mr.setId(mrId);
                                        mrId++;
                                    }
                                    timedTaskMapper.insertMsgStateClientBatch(mr, msgUserList);
                                    timedTaskMapper.updateScadaTable(itcd, "UP_WARN");
                                }
                            }
                        }
                    }
                    if (!StringUtils.isEmpty(openDownWarn) && "1".equals(openDownWarn) && !"1".equals(downWarn)) {
                        //间隔时间
                        Double downWarnTime = Double.parseDouble(map.get("downWarnTime").toString());
                        //发送短信需要达到的值
                        double downWarnVal = Double.parseDouble(map.get("downWarnVal").toString());
                        //查询区间最大、最小报警的值和时间
                        Map<String, Object> maxWarnValAndTime = timedTaskMapper.getMaxWarnValAndTime(itcd, downWarnTime);
                        Map<String, Object> minWarnValAndTime = timedTaskMapper.getMinWarnValAndTime(itcd, downWarnTime);
                        if (maxWarnValAndTime != null && !maxWarnValAndTime.isEmpty() && minWarnValAndTime != null && !minWarnValAndTime.isEmpty()) {
                            //值
                            double maxVal = Double.parseDouble(maxWarnValAndTime.get("itval").toString());
                            double minVal = Double.parseDouble(minWarnValAndTime.get("itval").toString());
                            //时间
                            String maxTime = maxWarnValAndTime.get("scadaTime").toString();
                            String minTime = minWarnValAndTime.get("scadaTime").toString();
                            //最大值的时间如果小于最小值时间视为突降，这里不做处理
                            if (minTime.compareTo(maxTime) > 0) {

                                double val = maxVal - minVal;
                                if (val > downWarnVal) {
                                    Long maxId = bwrkdetailService.getMaxId(MESSAGE_TABLE_NAME);
                                    mp.setId(maxId);
                                    mp.setMessage(timedTaskMapper.downWarnInfo(itcd, minVal, downWarnTime, maxVal, val));
                                    timedTaskMapper.insertMsg(mp);
                                    mr.setMessageId(maxId);
                                    Long mrId = bwrkdetailService.getMaxId(MESSAGERECIPIENT);
                                    for (int i = 0; i < msgUserList.size(); i++) {
                                        mr.setId(mrId);
                                        mrId++;
                                    }
                                    timedTaskMapper.insertMsgStateClientBatch(mr, msgUserList);
                                    timedTaskMapper.updateScadaTable(itcd, "DOWN_WARN");
                                }
                            }
                        }
                    }
                }
                if (!StringUtils.isEmpty(smsUser)) {
                    List<String> userTel = timedTaskMapper.getUserTel(Arrays.asList(smsUser.split(",")));
                    if (!userTel.isEmpty()) {
                        if (!StringUtils.isEmpty(openUpWarn) && "1".equals(openDownWarn) && !"1".equals(upSms)) {
                            //间隔时间
                            Double upWarnTime = Double.parseDouble(map.get("upWarnTime").toString());
                            //发送短信需要达到的值
                            double upWarnVal = Double.parseDouble(map.get("upWarnVal").toString());
                            //查询区间最大、最小报警的值和时间
                            Map<String, Object> maxWarnValAndTime = timedTaskMapper.getMaxWarnValAndTime(itcd, upWarnTime);
                            Map<String, Object> minWarnValAndTime = timedTaskMapper.getMinWarnValAndTime(itcd, upWarnTime);
                            if (maxWarnValAndTime != null && !maxWarnValAndTime.isEmpty() && minWarnValAndTime != null && !minWarnValAndTime.isEmpty()) {
                                //值
                                double maxVal = Double.parseDouble(maxWarnValAndTime.get("itval").toString());
                                double minVal = Double.parseDouble(minWarnValAndTime.get("itval").toString());
                                //时间
                                String maxTime = maxWarnValAndTime.get("scadaTime").toString();
                                String minTime = minWarnValAndTime.get("scadaTime").toString();
                                //最大值的时间如果小于最小值时间视为突降，这里不做处理
                                if (maxTime.compareTo(minTime) > 0) {

                                    double val = maxVal - minVal;
                                    if (val > upWarnVal) {
                                        for (String tel : userTel) {
                                            timeTaskFeign.sendNoteFeign(tel, timedTaskMapper.upWarnInfo(itcd, minVal, upWarnTime, maxVal, val));
                                        }
                                        timedTaskMapper.updateScadaTable(itcd, "UP_SMS");
                                    }
                                }
                            }
                        }
                        if (!StringUtils.isEmpty(openDownWarn) && "1".equals(openDownWarn) && !"1".equals(downSms)) {
                            //间隔时间
                            Double upWarnTime = Double.parseDouble(map.get("downWarnTime").toString());
                            //发送短信需要达到的值
                            double upWarnVal = Double.parseDouble(map.get("downWarnVal").toString());
                            //查询区间最大、最小报警的值和时间
                            Map<String, Object> maxWarnValAndTime = timedTaskMapper.getMaxWarnValAndTime(itcd, upWarnTime);
                            Map<String, Object> minWarnValAndTime = timedTaskMapper.getMinWarnValAndTime(itcd, upWarnTime);
                            if (maxWarnValAndTime != null && !maxWarnValAndTime.isEmpty() && minWarnValAndTime != null && !minWarnValAndTime.isEmpty()) {
                                //值
                                double maxVal = Double.parseDouble(maxWarnValAndTime.get("itval").toString());
                                double minVal = Double.parseDouble(minWarnValAndTime.get("itval").toString());
                                //时间
                                String maxTime = maxWarnValAndTime.get("scadaTime").toString();
                                String minTime = minWarnValAndTime.get("scadaTime").toString();
                                //最大值的时间如果小于最小值时间视为突降，这里不做处理
                                if (minTime.compareTo(maxTime) > 0) {
                                    double val = maxVal - minVal;
                                    if (val > upWarnVal) {
                                        for (String tel : userTel) {
                                            timeTaskFeign.sendNoteFeign(tel, timedTaskMapper.downWarnInfo(itcd, minVal, upWarnTime, maxVal, val));
                                        }
                                        timedTaskMapper.updateScadaTable(itcd, "DOWN_SMS");
                                    }
                                }
                            }
                        }

                    }
                }
            }
        }
        return true;
    }

    /**
     * dma异常信息绩效评价
     */
    @Override
    public boolean performanceEvaluation() {
        //查询满足条件的异常信息id
        List<String> workIds = timedTaskMapper.getWarnHandle(intervalHour);
        if (workIds != null && !workIds.isEmpty()) {
            //通过id查询信息
            List<DmawarnhandleDto> warnHandleInfo = timedTaskMapper.warnHandleInfo(workIds);

            if (warnHandleInfo != null && !warnHandleInfo.isEmpty()) {

                for (DmawarnhandleDto warn : warnHandleInfo) {
                    Long warnId = warn.getWarnId();
                    //获取正常后的最小流量，即当天的夜间最小流量
                    Double minFlow = timedTaskMapper.getNightMinFlow(warnId);
                    //维修后流量
                    warn.setMinFlowAfter(minFlow);
                    Double warnValue = Double.parseDouble(warn.getWarnValue());
                    //维修前后差值
                    double abs = Math.abs(warnValue - minFlow);
                    warn.setEvaluate(abs * 30 * 24);
                    timedTaskMapper.updateWarnHandle(warn);
                }
            }
        }
        return true;
    }

    /**
     * 同步抄表信息
     *
     * @return boolean
     */
    @Override
    public boolean synchronizingInformation() {
        while (true){
            //一次只查20条同步
            List<String> userCodes = timedTaskMapper.getNowMonthUserCode();
            if (userCodes != null && !userCodes.isEmpty()) {
                String monthPlan = cn.hutool.core.date.DateUtil.format(new Date(), "yyyyMM");
                ResultRespone resultRespone = readDataCheckThreeService.synCbsl(String.join(",", userCodes), monthPlan, "0");
                //打印只是为了让提交不是那么频繁
                System.out.println(resultRespone.getMessage());
            }else {
                break;
            }
        }
        return true;
    }

    /**
     * 同步基础信息
     *
     * @return Boolean
     */
    @Override
    public boolean synFoundationInfo() {
        synchronousAboutService.syncFactory();
        return true;
    }
}
