package org.springblade.modules.eventbus.service.alarmnotice;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.eventbus.Subscribe;
import com.nepxion.eventbus.annotation.EventBus;
import org.springblade.alarm.alarmgroup.entity.AlarmGroup;
import org.springblade.alarm.alarmgroup.service.IAlarmGroupService;
import org.springblade.alarm.alarmgroupuser.entity.AlarmGroupUser;
import org.springblade.alarm.alarmgroupuser.service.IAlarmGroupUserService;
import org.springblade.community.residential.entity.Residential;
import org.springblade.community.residential.service.IResidentialService;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.jackson.JsonUtil;
import org.springblade.homecare.alarmlist.entity.Alarm;
import org.springblade.openinterface.dto.IotSmsSendDto;
import org.springblade.openinterface.dto.IotSmsTemplateParam;
import org.springblade.openinterface.dto.IotSmsVoiceDto;
import org.springblade.smartapplication.smartsmoke.entity.SmartDevice;
import org.springblade.smartapplication.smartsmoke.service.ISmartDeviceService;
import org.springblade.third.butt.iotdevice.entity.IotAuthentication;
import org.springblade.third.butt.iotdevice.service.IperceptionIotDeviceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.net.URI;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.Month;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

/**
 * Created By lidexi in 2021/3/16
 * 告警发送语音处理类
 **/
@EventBus(identifier = "alarmSendVoiceSubscriber")
@Service
public class AlarmSendVoiceSubscriber {

	@Autowired
	private RedisTemplate<String,String> redisTemplate;
	@Autowired
	private ISmartDeviceService smartDeviceService;
	@Autowired
	private IResidentialService residentialService;
	@Autowired
	private IAlarmGroupService alarmGroupService;
	@Autowired
	private IAlarmGroupUserService alarmGroupUserService;
	@Autowired
	private IperceptionIotDeviceService perceptionIotDevice;

	@Subscribe
	@Async
	public void subscriber(Alarm alarm){

		System.out.println("发送语音。。。。。");
		RestTemplate restTemplate = new RestTemplate();
		String accessToken = redisTemplate.opsForValue().get("sptg:iot:auth:accessToken@#617fb531-c8bb-47c0-b3c4-d2fa4162a18e");
		if(accessToken == null){
			R<IotAuthentication> auth = perceptionIotDevice.auth("617fb531-c8bb-47c0-b3c4-d2fa4162a18e");
			if(auth.isSuccess()){
				accessToken = auth.getData().getAccessToken();
			}
		}

		List<IotSmsVoiceDto> iotSmsSendDtos = buildIotVoiceSendDto(alarm);
		for(IotSmsVoiceDto iotSmsSendDto : iotSmsSendDtos){
			ResponseEntity responseEntity = null;
			HttpHeaders headers = new HttpHeaders();
			headers.add(HttpHeaders.CONTENT_TYPE, "application/json");
			headers.add("accessToken", accessToken);

			HttpEntity<String> requestEntity = new HttpEntity<String>(JSONUtil.toJsonStr(iotSmsSendDto), headers);
			ParameterizedTypeReference<Object> reference = new ParameterizedTypeReference<Object>() {
			};

			//发送语音
			String url = "https://scep-api.ctwing.cn:8000/ctwing/smoke3/voice/sendVoice";
			URI uri = URI.create(url);
			responseEntity = restTemplate.exchange(uri, HttpMethod.POST, requestEntity, reference);
			System.out.println("语音"+iotSmsSendDto.getMobile()+":"+responseEntity);
		}
//		iotSmsSendDtos.parallelStream().forEach(iotSmsSendDto -> {
//			ResponseEntity responseEntity = null;
//			HttpHeaders headers = new HttpHeaders();
//			headers.add(HttpHeaders.CONTENT_TYPE, "application/json");
//			headers.add("accessToken", accessToken);
//
//			HttpEntity<String> requestEntity = new HttpEntity<String>(JSONUtil.toJsonStr(iotSmsSendDto), headers);
//			ParameterizedTypeReference<Object> reference = new ParameterizedTypeReference<Object>() {
//			};
//
//			//发送语音
//			String url = "https://scep-api.ctwing.cn:8000/ctwing/smoke3/voice/sendVoice";
//			URI uri = URI.create(url);
//			responseEntity = restTemplate.exchange(uri, HttpMethod.POST, requestEntity, reference);
//			System.out.println("语音"+iotSmsSendDto.getMobile()+":"+responseEntity);
//		});
	}

	/**
	 * 构建语音发送对象
	 *
	 * @param alarm
	 * @return
	 */
	private List<IotSmsVoiceDto> buildIotVoiceSendDto(Alarm alarm) {
		List<IotSmsVoiceDto> iotSmsSendDtos = new ArrayList<>();

		SmartDevice smartDevice = smartDeviceService.getBaseMapper().selectOne(new QueryWrapper<>(new SmartDevice()).lambda().eq(SmartDevice::getDeviceId, alarm.getDeviceId()));
		if(smartDevice == null){
			smartDevice = smartDeviceService.getBaseMapper().selectOne(new QueryWrapper<>(new SmartDevice()).lambda().eq(SmartDevice::getImei,alarm.getDeviceId()));
		}
		Residential residential = residentialService.getById(smartDevice.getResidentialId());
		if (smartDevice != null) {
			//通过设备的类型和所属小区id搜索告警组
			List<AlarmGroup> alarmGroups = alarmGroupService.getBaseMapper().selectList(new QueryWrapper<>(new AlarmGroup()).lambda().eq(AlarmGroup::getResidentialId, smartDevice.getResidentialId()).eq(AlarmGroup::getTag, smartDevice.getDeviceType()));
			if (alarmGroups.size() > 0) {
				//获取告警组中的所有人
				List<AlarmGroupUser> alarmGroupUsers = alarmGroupUserService.getBaseMapper().selectList(new QueryWrapper<>(new AlarmGroupUser()).lambda().eq(AlarmGroupUser::getGroupId, alarmGroups.get(0).getId()));
				for (int i = 0; i < alarmGroupUsers.size(); i++) {
					IotSmsVoiceDto iotSmsSendDto = new IotSmsVoiceDto();
					String recordTime = alarm.getRecordTime();
					DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
					StringBuffer sb = new StringBuffer();
					try {
						LocalDateTime parse = LocalDateTime.parse(recordTime,df);
						int year = parse.getYear();
						sb.append(year+"年");
						Month month = parse.getMonth();
						if(month.getValue()>=10){
							sb.append(month.getValue()+"月");
						}else{
							sb.append("0"+month.getValue()+"月");
						}

						int day = parse.getDayOfMonth();
						if(day>=10){
							sb.append(day+"日");
						}else{
							sb.append("0"+day+"日");
						}

						int hour = parse.getHour();
						if(hour>=10){
							sb.append(hour+"时");
						}else{
							sb.append("0"+hour+"时");
						}

						int minutes = parse.getMinute();
						if(minutes>=10){
							sb.append(minutes+"分");
						}else{
							sb.append("0"+minutes+"分");
						}

						int seconds = parse.getSecond();
						if(seconds>=10){
							sb.append(seconds+"秒");
						}else{
							sb.append("0"+seconds+"秒");
						}

					} catch (Exception e) {
						e.printStackTrace();
					}

					iotSmsSendDto.setMobile(alarmGroupUsers.get(i).getPhone());
					iotSmsSendDto.setContent("您好，"+residential.getName()+"的"+smartDevice.getDeviceName()+"设备在"+sb.toString()+"发生"+alarm.getAlarmDesc()+"，请及时处理。");
					System.out.println(iotSmsSendDto.getContent());
//					iotSmsSendDto.setContent("您好，潘家园街道办事处武农武圣西里6号楼3门501的武农武圣西里6号楼3门501设备在2020年05月13日23时55分19秒发生XX报警，请及时处理。");
					Long timestamp = null;
					try {
						timestamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(recordTime).getTime();
					} catch (ParseException e) {
						e.printStackTrace();
					}
					iotSmsSendDto.setTimestamp(timestamp.toString());
					iotSmsSendDtos.add(iotSmsSendDto);
				}
			}


		}


		return iotSmsSendDtos;
	}
}
