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

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.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.springblade.third.butt.iotdevice.service.impl.PerceptionIotDeviceImpl;
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 = "alarmSendSmsSubscriber")
@Service
public class AlarmSendSmsSubscriber {

	@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();
		//获取accessToken
		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<IotSmsSendDto> iotSmsSendDtos = buildIotSmsSendDto(alarm);
		for(IotSmsSendDto 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.toJson(iotSmsSendDto), headers);
			ParameterizedTypeReference<Object> reference = new ParameterizedTypeReference<Object>() {
			};
			String url = "https://scep-api.ctwing.cn:8000/ctwing/smoke3/sms/sendSms";
			URI uri = URI.create(url);
			responseEntity = restTemplate.exchange(uri, HttpMethod.POST, requestEntity, reference);
			System.out.println(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.toJson(iotSmsSendDto), headers);
//			ParameterizedTypeReference<Object> reference = new ParameterizedTypeReference<Object>() {
//			};
//			String url = "https://scep-api.ctwing.cn:8000/ctwing/smoke3/sms/sendSms";
//			URI uri = URI.create(url);
//			responseEntity = restTemplate.exchange(uri, HttpMethod.POST, requestEntity, reference);
//			System.out.println(responseEntity);
//		});
	}

	/**
	 * 构建短信发送对象
	 * @param alarm
	 * @return
	 */
	private  List<IotSmsSendDto> buildIotSmsSendDto(Alarm alarm){

		List<IotSmsSendDto> 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++) {
					IotSmsSendDto iotSmsSendDto = new IotSmsSendDto();
					IotSmsTemplateParam iotSmsTemplateParam = new IotSmsTemplateParam();
					iotSmsTemplateParam.setParam1(alarmGroupUsers.get(i).getPerson());//接收人称呼
					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();
						sb.append(month.getValue()+"月");
						int day = parse.getDayOfMonth();
						sb.append(day+"日");
						int hour = parse.getHour();
						sb.append(hour+"时");
						int minutes = parse.getMinute();
						sb.append(minutes+"分");
						int seconds = parse.getSecond();
						sb.append(seconds+"秒");
					} catch (Exception e) {
						e.printStackTrace();
					}

					iotSmsTemplateParam.setParam2(sb.toString());//告警时间
					if (residential != null) {
						iotSmsTemplateParam.setParam3(residential.getName());//小区名称
					} else {
						iotSmsTemplateParam.setParam3("未知小区");//小区名称
					}

					iotSmsTemplateParam.setParam4(smartDevice.getDeviceName());//设备名称
					iotSmsTemplateParam.setParam5(alarm.getAlarmDesc());


					iotSmsSendDto.setTemplate_param(iotSmsTemplateParam);
					iotSmsSendDto.setMobile(alarmGroupUsers.get(i).getPhone());
					iotSmsSendDto.setTemplate_id("91556324");
					iotSmsSendDto.setPrefix("ctwing/smoke3");
					Long timestamp = null;
					try {
						timestamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(alarm.getRecordTime()).getTime();
					} catch (ParseException e) {
						e.printStackTrace();
					}
					iotSmsSendDto.setTimestamp(timestamp.toString());
					iotSmsSendDtos.add(iotSmsSendDto);
				}
			}


		}
		return iotSmsSendDtos;
	}
}
