package org.springblade.utils;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
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.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.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.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;

@Slf4j
public class AlarmSendSmsAndVoiceUtil {

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

	public AlarmSendSmsAndVoiceUtil(RedisTemplate redisTemplate, ISmartDeviceService smartDeviceService, IResidentialService residentialService, IAlarmGroupService alarmGroupService, IAlarmGroupUserService alarmGroupUserService){
		this.redisTemplate = redisTemplate;
		this.smartDeviceService = smartDeviceService;
		this.residentialService = residentialService;
		this.alarmGroupService = alarmGroupService;
		this.alarmGroupUserService =alarmGroupUserService;
	}

	/**
	 *
	 *新增告警调用感知平台短信功能发送短信
	 * @param alarm
	 */
	@Deprecated
	public  void sendSms(Alarm alarm){
		RestTemplate restTemplate = new RestTemplate();
		//获取accessToken
		final String accessToken = redisTemplate.opsForValue().get("sptg:iot:auth:accessToken@#617fb531-c8bb-47c0-b3c4-d2fa4162a18e");
		log.error("accessToken" + accessToken);

		List<IotSmsSendDto> iotSmsSendDtos = buildIotSmsSendDto(alarm);
		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
	 */
	@Deprecated
	public void sendVoice(Alarm alarm) {
		RestTemplate restTemplate = new RestTemplate();
		final String accessToken = redisTemplate.opsForValue().get("sptg:iot:auth:accessToken@#617fb531-c8bb-47c0-b3c4-d2fa4162a18e");
//

//		log.error("accessToken" + accessToken);
//		String accessToken = "e02fdb5e-02c9-4eb4-b6b2-e0e52094d847";
		List<IotSmsVoiceDto> iotSmsSendDtos = buildIotVoiceSendDto(alarm);
		iotSmsSendDtos.parallelStream().forEach(iotSmsSendDto -> {
			ResponseEntity responseEntity = null;
			HttpHeaders headers = new HttpHeaders();
			headers.add(HttpHeaders.CONTENT_TYPE, "application/json");
//			headers.add("accessToken", accessToken);
			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;
	}


	/**
	 * 通用短信告警通知（调用感知平台短信功能发送短信）
	 * @param iotSmsSendDtos
	 */
	public void sendNormalSms(List<IotSmsSendDto> iotSmsSendDtos){
		if (iotSmsSendDtos == null || iotSmsSendDtos.size() <= 0){
			return;
		}
		RestTemplate restTemplate = new RestTemplate();
		//获取accessToken
		final String accessToken = redisTemplate.opsForValue().get("sptg:iot:auth:accessToken@#617fb531-c8bb-47c0-b3c4-d2fa4162a18e");

		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;
	}

}
