package com.yuchen.saas.park.service.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yuchen.saas.message.api.dto.WebSocketMessagDTO;
import com.yuchen.saas.message.api.feign.ws.WebSocketFeignServer;
import com.yuchen.saas.park.api.dto.park.TemperaturePreventionDTO;
import com.yuchen.saas.park.api.dto.prevention.TemperaturePageQueryDTO;
import com.yuchen.saas.park.api.entity.device.PmgBatSmartEquipment;
import com.yuchen.saas.park.api.entity.park.TemperaturePrevention;
import com.yuchen.saas.park.api.enums.TemperatureStatus;
import com.yuchen.saas.park.api.vo.park.prevention.TemperaturePreventionVO;
import com.yuchen.saas.park.service.constant.TorchConstant;
import com.yuchen.saas.park.service.mapper.TemperaturePreventionMapper;
import com.yuchen.saas.park.service.service.PmgBatSmartEquipmentService;
import com.yuchen.saas.park.service.service.TemperaturePreventionService;
import com.yuchen.saas.park.service.util.DateTimeUtils;
import com.yuchen.saas.park.service.wrapper.TemperaturePreventionWrapper;
import org.apache.commons.lang3.ObjectUtils;
import org.nest.springwrap.core.mp.base.BaseServiceImpl;
import org.nest.springwrap.core.mp.support.Condition;
import org.nest.springwrap.core.mp.support.Query;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author 颜艺波
 * @date 2022/6/16 16:19
 * @Description
 */
@Service
public class TemperaturePreventionServiceImpl extends BaseServiceImpl<TemperaturePreventionMapper, TemperaturePrevention>
        implements TemperaturePreventionService {

    @Resource
    //SimpMessagingTemplate simpMessagingTemplate;
    private WebSocketFeignServer webSocketClient;

    @Autowired
    PmgBatSmartEquipmentService equipmentService;

    @Override
    public boolean add(TemperaturePreventionDTO temperaturePreventionDTO) {
        TemperaturePrevention temperaturePrevention = new TemperaturePrevention();
        BeanUtils.copyProperties(temperaturePreventionDTO, temperaturePrevention);
        // 园区id通过设备查询数据库获取
        PmgBatSmartEquipment equipment = equipmentService.getOne(Wrappers.<PmgBatSmartEquipment>lambdaQuery()
                .select(PmgBatSmartEquipment::getParkId, PmgBatSmartEquipment::getTenantId)
                .eq(PmgBatSmartEquipment::getProductKey, temperaturePreventionDTO.getProductKey())
                .eq(PmgBatSmartEquipment::getDeviceName, temperaturePreventionDTO.getDeviceName()));
        if (equipment != null) {
            temperaturePrevention.setParkId(equipment.getParkId());
            temperaturePrevention.setTenantId(equipment.getTenantId());

            // 设备识别失败丢掉数据
            this.save(temperaturePrevention);
            // webSocket推送前端
            //simpMessagingTemplate.convertAndSendToUser(String.valueOf(temperaturePrevention.getParkId()), "/tempPrevention/latestData", new TemperaturePreventionWrapper().entityVO(temperaturePrevention));
            Map<String, Object> objectMap = BeanUtil.beanToMap(temperaturePrevention);
            objectMap.put("enterTime", DateUtil.format(new Date(temperaturePrevention.getEnterTime()),"yyyy-MM-dd HH:mm:ss"));
            WebSocketMessagDTO dto = new WebSocketMessagDTO(String.valueOf(temperaturePrevention.getParkId()),
                    "/tempPrevention/latestData", objectMap);
            webSocketClient.convertAndSendToUser(dto);
        }

        return true;
    }

    @Override
    public List<TemperaturePreventionVO> latestDataQuery(Long parkId) {
        List<TemperaturePrevention> preventionList = this.list(Wrappers.<TemperaturePrevention>lambdaQuery()
                .eq(TemperaturePrevention::getParkId, parkId)
                .orderByDesc(TemperaturePrevention::getEnterTime).last("limit 8"));
        return new TemperaturePreventionWrapper().listVO(preventionList);
    }

    @Override
    public IPage<TemperaturePreventionVO> pageQuery(TemperaturePageQueryDTO temperaturePageQueryDTO, Query query) {
        LambdaQueryWrapper<TemperaturePrevention> pageQueryWrapper = new LambdaQueryWrapper<>();
        pageQueryWrapper.eq(TemperaturePrevention::getParkId, temperaturePageQueryDTO.getParkId())
                .ge(ObjectUtils.isNotEmpty(temperaturePageQueryDTO.getBeginTime()),
                        TemperaturePrevention::getEnterTime,
                        DateTimeUtils.dateTimeToTimestamp(temperaturePageQueryDTO.getBeginTime()))
                .le(ObjectUtils.isNotEmpty(temperaturePageQueryDTO.getEndTime()),
                        TemperaturePrevention::getEnterTime,
                        DateTimeUtils.dateTimeToTimestamp(temperaturePageQueryDTO.getEndTime()))
                .le(temperaturePageQueryDTO.getTemperatureStatus() != null
                                && TemperatureStatus.NORMAL.getCode().equals(temperaturePageQueryDTO.getTemperatureStatus()),
                        TemperaturePrevention::getTemperature, Float.parseFloat(TorchConstant.TEMPERATURE))
                .gt(temperaturePageQueryDTO.getTemperatureStatus() != null
                                && TemperatureStatus.ABNORMAL.getCode().equals(temperaturePageQueryDTO.getTemperatureStatus()),
                        TemperaturePrevention::getTemperature, Float.parseFloat(TorchConstant.TEMPERATURE))
                .eq(temperaturePageQueryDTO.getWearMask() != null, TemperaturePrevention::getWearMask,
                        temperaturePageQueryDTO.getWearMask())
                .orderByDesc(TemperaturePrevention::getEnterTime);
        IPage<TemperaturePrevention> tempPreventionPage = this.page(Condition.getPage(query), pageQueryWrapper);
        TemperaturePreventionWrapper tempPreventionWrapper = new TemperaturePreventionWrapper();
        IPage<TemperaturePreventionVO> pageVO = tempPreventionWrapper.pageVO(tempPreventionPage);
        // 获取设备名称
        for (TemperaturePreventionVO preventionVO : pageVO.getRecords()) {
            PmgBatSmartEquipment equipment = equipmentService.getOne(Wrappers.<PmgBatSmartEquipment>lambdaQuery()
                    .select(PmgBatSmartEquipment::getName)
                    .eq(PmgBatSmartEquipment::getProductKey, preventionVO.getProductKey())
                    .eq(PmgBatSmartEquipment::getDeviceName, preventionVO.getDeviceName()));
            if (equipment != null) {
                preventionVO.setDeviceAliasName(equipment.getName());
            }
        }
        return pageVO;
    }
}
