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

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.tofly.common.oauth.util.SecurityUtils;
import com.tofly.pojo.message.Messagepush;
import com.tofly.pojo.message.Messagerecipient;
import com.tofly.pojo.message.Usertask;

import com.tofly.xrtygis.custom.util.DateTimeUtil;
import com.tofly.xrtygis.entity.AbnormalWaterConfig;
import com.tofly.xrtygis.entity.AbnormalWaterUse;
import com.tofly.xrtygis.mapper.AbnormalWaterUseMapper;
import com.tofly.xrtygis.service.AbnormalWaterConfigService;
import com.tofly.xrtygis.service.AbnormalWaterUseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;


/**
 * 分析用户用水量记录表
 *
 * @author admin
 * @date Thu Jul 28 00:00:00 CST 2022
 */
@Service("abnormalWaterUseService")
public class AbnormalWaterUseServiceImpl extends ServiceImpl<AbnormalWaterUseMapper, AbnormalWaterUse> implements AbnormalWaterUseService {

    @Value("${gis.abnormalWater.web}")
    private String web;

    @Value("${gis.abnormalWater.web}")
    private String app;

    @Autowired
    private AbnormalWaterConfigService configService;

    @Override
    public Page<Map> getAbnormalWaterUserPage(Page page,Date startTime, Date endTime,String state, String likeStr) {
        return baseMapper.getAbnormalWaterUserPage(page,startTime,endTime,state,likeStr);
    }

    @Override
    public List<Map> getUserMeterReading(AbnormalWaterUse dto) {
        Date startTime = dto.getStartTime();
        Date endTime = dto.getEndTime();
        if(null == startTime || null == endTime){
            // 默认给30 天时间范围
           endTime = DateTimeUtil.convertLDTToDate(DateTimeUtil.getTodayEndTime());
           startTime = DateTimeUtil.convertLDTToDate(DateTimeUtil.getTodayBeginTime().minusDays(6));
        }
        return baseMapper.getUserMeterReading(startTime,endTime,dto.getYhbh());
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean send(List<Date> dateList) {
        AtomicLong errorCountAll = new AtomicLong();
        dateList.forEach(date -> {
            // 获取当前统计年月日期
            String monthDay = DateTimeUtil.getLocalDate(date, DateTimeUtil.DAY_FORMAT);
            // 获取当前统计日期 前七天日期
            Date startTime = DateTimeUtil.convertLDTToDate(DateTimeUtil.fromLong2LocalDateTime(date.getTime()).minusDays(7));
            List<AbnormalWaterUse> abnormalWaterUserList = baseMapper.getAbnormalWaterUserList(monthDay, startTime, date);

            // 清空统计过的日期数据
            this.remove(new QueryWrapper<AbnormalWaterUse>().lambda().eq(AbnormalWaterUse::getMonthDay, monthDay));
            // 批量新增
            this.saveBatch(abnormalWaterUserList);
            // 获取异常数据大小
            long errorCount = abnormalWaterUserList.stream().filter(i -> "1".equals(i.getState())).count();
            errorCountAll.set(errorCountAll.get() + errorCount);
        });

        if (0 != errorCountAll.get()) {
            // 发送消息给指定配置中的工作人员
            AbnormalWaterConfig config = configService.getConfig();
            Long userId = config.getUserId();
            List<Long> userIdList = new ArrayList<>();
            userIdList.add(userId);
            String stringBuilder = "当前分析用户用水量异常数据为: " +
                    errorCountAll.get();
            sendMessage(userIdList,"用户用水量分析","0","TF_ABNORMAL_WATER_USE",config.getId(),web,app, stringBuilder);
        }


        return true;
    }



    /**
     * 消息发送 TODO 后续修改
     * @param userIdList 发送用户列表id
     * @param topic 消息主题
     * @param type 消息类型
     * @param tableName 消息链接表名
     * @param tableId 链接ID
     * @param webRouteIp web路由地址进行跳转
     * @param appRouteIp APP路由地址进行跳转
     * @param msg 消息详情
     * @return
     */
    public boolean sendMessage(List<Long> userIdList,String topic,String type,String tableName,Long tableId,String webRouteIp,String appRouteIp,String msg) {
        AtomicReference<Long> messagePushId = new AtomicReference<>(baseMapper.getPlanTempMaxId("TF_YWPN_MESSAGEPUSH_W"));
        AtomicReference<Long> messageRecipientId = new AtomicReference<>(baseMapper.getPlanTempMaxId("TF_YWPN_MESSAGERECIPIENT_W"));

        List<Messagepush> messagePushList = new ArrayList<>();
        List<Messagerecipient> messageRecipientList = new ArrayList<>();
        userIdList.forEach(userId->{
            Messagepush messagepush = new Messagepush();
            // 消息主题/消息类型/消息表名/消息表中id/路由地址跳转
            Long message1 = messagePushId.get();
            Long recipient1 = messageRecipientId.get();

            messagepush.setId(message1);
            messagepush.setTopic(topic);
            messagepush.setType(type);
            messagepush.setTableName(tableName);
            messagepush.setTableId(tableId);
            messagepush.setCreateTime(new Date());
            messagepush.setCreateUser(userId);
            messagepush.setMessage(msg);
            // 跳转到计划任务页面
            messagepush.setRouteIp(webRouteIp);
            messagepush.setRouteIpApp(appRouteIp);
            // 消息与接收人信息处理
            Messagerecipient messagerecipient = new Messagerecipient();
            messagerecipient.setId(recipient1);
            messagerecipient.setMessageId(message1);
            messagerecipient.setRecipient(userId);
            messagerecipient.setFlag("0");

            messagePushList.add(messagepush);
            messageRecipientList.add(messagerecipient);

            Long idAndSet = message1 + 1;
            Long andSet = recipient1 + 1;

            messagePushId.set(idAndSet);
            messageRecipientId.set(andSet);
        });


        // 消息存入
        baseMapper.addMessageList(messagePushList);
        baseMapper.addMessageRecipientList(messageRecipientList);

    return true;
    }
}
