package com.usky.iot.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
//import com.usky.backend.client.DeviceDataClient;
import com.usky.iot.service.config.mqtt.MqttOutConfig;
import com.usky.iot.service.vo.DeviceDataInfoVO;
import com.usky.common.core.exception.BusinessException;
import com.usky.common.mybatis.core.AbstractCrudService;
import com.usky.common.security.utils.SecurityUtils;
import com.usky.iot.domain.*;
import com.usky.iot.mapper.DmpDataInfoMapper;
import com.usky.iot.service.*;
import com.usky.backend.domain.request.DmpDeviceDataRequestVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;

/**
 * <p>
 * 数据信息 服务实现类
 * </p>
 *
 * @author ya
 * @since 2022-10-08
 */
@Service
public class DmpDataInfoServiceImpl extends AbstractCrudService<DmpDataInfoMapper, DmpDataInfo> implements DmpDataInfoService {
    @Autowired
    private DmpProductInfoService dmpProductInfoService;

    @Autowired
    private DmpProductAttributeService dmpProductAttributeService;

    @Autowired
    private DmpDeviceInfoService dmpDeviceInfoService;
//
//    @Autowired
//    private DeviceDataClient deviceDataClient;

    @Resource
    private MqttOutConfig.MqttGateway mqttGateway;

    @Autowired
    private DmpDeviceTypeService dmpDeviceTypeService;

    @Override
    public void data(DmpDeviceDataRequestVO dmpDeviceDataRequestVO){
        DeviceDataInfoVO dataInfo = new DeviceDataInfoVO();

        LambdaQueryWrapper<DmpProductInfo> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.select(DmpProductInfo::getId,DmpProductInfo::getDeviceType,DmpProductInfo::getTenantId)
                .eq(DmpProductInfo::getDeleteFlag,0)
                .eq(DmpProductInfo::getProductCode,dmpDeviceDataRequestVO.getProductCode());
        List<DmpProductInfo> list = dmpProductInfoService.list(queryWrapper);
        if(CollectionUtils.isNotEmpty(list)){

            LambdaQueryWrapper<DmpDeviceInfo> dmpDeviceQuery = Wrappers.lambdaQuery();
            dmpDeviceQuery.eq(DmpDeviceInfo::getDeleteFlag,0)
                    .eq(DmpDeviceInfo::getDeviceId,dmpDeviceDataRequestVO.getDeviceId())
                    .eq(DmpDeviceInfo::getTenantId, list.get(0).getTenantId());
            List<DmpDeviceInfo> deviceDataInfo = dmpDeviceInfoService.list(dmpDeviceQuery);
            if(CollectionUtils.isEmpty(deviceDataInfo)){
                throw new BusinessException("录入数据失败，"+dmpDeviceDataRequestVO.getDeviceId()+" 这个设备没有注册");
            }

            LambdaQueryWrapper<DmpDeviceType> deviceTypeList = Wrappers.lambdaQuery();
            deviceTypeList.eq(DmpDeviceType::getTypeCode,list.get(0).getDeviceType());
            List<DmpDeviceType> lt = dmpDeviceTypeService.list(deviceTypeList);
            if(CollectionUtils.isEmpty(lt)){
                throw new BusinessException("查找设备类型简称失败，"+list.get(0).getDeviceType()+" 在设备类型表中不存在");
            }
            String shortName = lt.get(0).getTypeAbbrevia();

            LambdaQueryWrapper<DmpProductAttribute> queryWrapper1 = Wrappers.lambdaQuery();
            queryWrapper1.select(DmpProductAttribute::getAttributeCode)
                    .eq(DmpProductAttribute::getDeleteFlag,0)
                    .eq(DmpProductAttribute::getTenantId,list.get(0).getTenantId())
                    .eq(DmpProductAttribute::getProductId,list.get(0).getId());
            List<DmpProductAttribute> list1 = dmpProductAttributeService.list(queryWrapper1);
            if(CollectionUtils.isNotEmpty(list1)){
                    Map<String,Float> metrics = dmpDeviceDataRequestVO.getMetrics();
                    if(metrics.size()>0){
                        Map<String,Object> mp = new HashMap<>();
                        for(Map.Entry<String,Float> map:metrics.entrySet()){
                            boolean find = false;
                            String key = map.getKey();
                            float value = map.getValue();
                            for(int i=0;i<list1.size();i++){
                                if(key.equals(list1.get(i).getAttributeCode())){   //属性名需和产品注册信息一致
                                    mp.put(key,value);
                                    find = true;
                                }
                            }
                            if(find == false){
                                throw new BusinessException("对应这个产品下面的设备属性"+key+" 在产品属性表中不存在");
                            }
                        }
                        dataInfo.setMetrics(mp);
                        dataInfo.setDevice_id(dmpDeviceDataRequestVO.getDeviceId());
                        dataInfo.setProduct_id(list.get(0).getProductCode());
                        dataInfo.setTimestamp(dmpDeviceDataRequestVO.getTimestamp());
                        dataInfo.setDevice_type(list.get(0).getDeviceType()+"-"+shortName);
                    }
            }else{
                throw new BusinessException("查找产品属性表失败，"+dmpDeviceDataRequestVO.getProductCode()+" 该产品对应的属性在产品信息表没有信息");
            }
        }else{
            throw new BusinessException("查找产品信息失败，"+dmpDeviceDataRequestVO.getProductCode()+" 在产品信息表中不存在");
        }
        if(dataInfo != null){
            mqttGateway.sendToMqtt("data-collector", JSONArray.toJSON(dataInfo).toString());
            System.out.println(JSONArray.toJSON(dataInfo).toString());
        }
    }

}
