package com.zcxk.sync.mq;

import com.alibaba.fastjson.JSON;
import com.zcxk.core.utils.DateUtil;
import com.zcxk.core.utils.MqService;
import com.zcxk.rmcp.api.dto.DeviceAreaDto;
import com.zcxk.rmcp.api.dto.device.DeviceSyncDto;
import com.zcxk.rmcp.api.dto.product.ProductVo;
import com.zcxk.rmcp.core.dao.AreaMapper;
import com.zcxk.rmcp.core.dao.ProductMapper;
import com.zcxk.rmcp.core.entity.Device;
import com.zcxk.sync.constant.MqConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

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

/**
 * @author heyumin
 * @version 1.0
 * @date 2021/8/23 9:23
 */
@Component
@Slf4j
public class SyncDeviceProducer {
    @Autowired
    private MqService mqService;
    @Resource
    private AreaMapper areaMapper;
    @Resource
    private ProductMapper productMapper;
    @Value("${iot.exchange.name}")
    private String exchange;
    @Value("${iot.device.routing.key}")
    private String deviceKey;
    @Value("${iot.delete.device.routing.key}")
    private String deleteDeviceKey;

    public void sendDeviceInfo(Device device,String opt){
        DeviceSyncDto deviceSyncDto=new DeviceSyncDto();
        deviceSyncDto.setOperationType(opt);
        try {
            setDeviceSyncDto(deviceSyncDto,device);
            mqService.send(exchange,deviceKey, JSON.toJSONString(deviceSyncDto));
        }catch (Exception e){
          log.error("同步设备信息出错",e);
        }

    }
    private void setDeviceSyncDto(DeviceSyncDto deviceSyncDto,Device device){

        Double lat=device.getLat()==null?null:device.getLat().doubleValue();
        deviceSyncDto.setLatitude(lat);
        Double lng=device.getLng()==null?null:device.getLng().doubleValue();
        deviceSyncDto.setLongitude(lng);
        deviceSyncDto.setId(device.getId());
        deviceSyncDto.setDeviceNo(device.getDeviceNo());
        DeviceAreaDto deviceAreaDto=areaMapper.findAreas(device.getCommunityId());
        deviceSyncDto.setCityId(deviceAreaDto.getCityId());
        deviceSyncDto.setProvinceId(deviceAreaDto.getProvinceId());
        deviceSyncDto.setRegionId(deviceAreaDto.getRegionId());
        ProductVo productVo=productMapper.findProduct(device.getProductId());
        deviceSyncDto.setProductModel(productVo.getProductModel());
        deviceSyncDto.setManufacturerName(productVo.getManufacturerName());
        deviceSyncDto.setProductName(productVo.getProductName());



    }
    public void deleteDeviceInfo(List<Long> ids){
        mqService.send(exchange,deleteDeviceKey,JSON.toJSONString(ids));
    }


}
