package com.bootdo.datasend.dianxin.task;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bootdo.datasend.dianxin.domain.BaseHighThrowRecord;
import com.bootdo.datasend.dianxin.domain.dto.HighThrowDto;
import com.bootdo.datasend.dianxin.domain.dto.HighThrowRequestDataDTO;
import com.bootdo.datasend.dianxin.domain.dto.HighThrowRequestDataListDTO;
import com.bootdo.datasend.dianxin.service.BaseHighThrowRecordService;
import com.bootdo.util.Base64Util;
import com.bootdo.util.StringKit;
import lombok.RequiredArgsConstructor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
@RequiredArgsConstructor
public class StandardTask {

    private final RabbitTemplate rabbitTemplate;
    private final BaseHighThrowRecordService highThrowRecordService;

    /**
     * 功能描述: 设备发送
     */
    @Scheduled(cron = "0/5 * * * * ? ")
    public void sendDevice() {

        //获取高抛记录
        List<BaseHighThrowRecord> highThrowRecords = highThrowRecordService.list(new QueryWrapper<BaseHighThrowRecord>()
            .eq("is_send","0")
        );

        for (BaseHighThrowRecord h:highThrowRecords){

            HighThrowDto dto = new HighThrowDto();

            HighThrowRequestDataDTO dataDTO = new HighThrowRequestDataDTO();
            dataDTO.setRequestFlag("1");

            HighThrowRequestDataListDTO requestDataListDTO = new HighThrowRequestDataListDTO();
            requestDataListDTO.setGatewaySN(h.getGeminiSn());
            requestDataListDTO.setWarnType("1001");
            requestDataListDTO.setDeviceType("302");
            requestDataListDTO.setDeviceSN(h.getGbsChannelNo());
            requestDataListDTO.setEventName("高抛报警");
            requestDataListDTO.setWarnTime(StringKit.toString(h.getPassTime()));
            requestDataListDTO.setGlobalPicBase64(Base64Util.getBase64ByUrl(h.getHighThrowImgurl()));
            List<HighThrowRequestDataListDTO> list = new ArrayList<>();
            list.add(requestDataListDTO);
            dataDTO.setRequestDataList(list);
            dto.setRequestData(dataDTO);

            //循环发送mq
            boolean b=sendHighThrowMq(dto);
            if(b){
                h.setIsSend(1);
                highThrowRecordService.saveOrUpdate(h);
            }
        }
    }

    public boolean sendHighThrowMq(HighThrowDto bean) {
        try {
            rabbitTemplate.convertAndSend("warnrecord", "routing.key.warnrecord", JSON.toJSONString( bean));
        }catch (Exception e){
            return false;
        }
        return true;
    }


}
