package org.springblade.openinterface.iot.listener;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.AllArgsConstructor;
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.log.logger.BladeLogger;
import org.springblade.core.tool.api.R;
import org.springblade.homecare.alarmlist.entity.Alarm;
import org.springblade.homecare.alarmlist.service.IAlarmService;
import org.springblade.jobs.devicejob.entity.DeviceJob;
import org.springblade.jobs.devicejob.service.IDeviceJobService;
import org.springblade.modules.system.entity.User;
import org.springblade.modules.system.service.IDeptService;
import org.springblade.modules.system.service.IUserService;
import org.springblade.openinterface.dto.IotSmsSendDto;
import org.springblade.openinterface.dto.IotSmsTemplateParam;
import org.springblade.openinterface.iot.utils.Ddzy251_NB_Util;
import org.springblade.smartapplication.electricmeterrecord.entity.ElectricMeterRecord;
import org.springblade.smartapplication.electricmeterrecord.service.IElectricMeterRecordService;
import org.springblade.smartapplication.heartbeat.entity.DeviceHeartbeat;
import org.springblade.smartapplication.heartbeat.service.IDeviceHeartbeatService;
import org.springblade.smartapplication.smartsmoke.entity.SmartDevice;
import org.springblade.smartapplication.smartsmoke.service.ISmartDeviceService;
import org.springblade.smartapplication.smartsmoke.service.impl.SmartDeviceServiceImpl;
import org.springblade.system.orgposition.entity.OrgPosition;
import org.springblade.system.orgposition.service.IOrgPositionService;
import org.springblade.utils.ByteConvert;
import org.springblade.utils.OrderGenerateUtilService;
import org.springblade.utils.SerializableUtil;
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.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import sun.misc.BASE64Decoder;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author zwx
 * @create 2020/12/13 13:58
 */
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("openinterface/iot/listen")
public class IotElectricMeterSubscribeController {


	private BladeLogger logger;
	private IElectricMeterRecordService electricMeterRecordService;
	private ISmartDeviceService smartDeviceService;

	@PostMapping("/electricMeter/dataReport")
	public R iotDeviceDataReport(@RequestBody Map<String, Object> map) throws IOException {
		log.error("dataReport --> " + JSONUtil.toJsonStr(map));
		logger.info("electricMeter/dataReport", JSONUtil.toJsonStr(map));
		String rawData = map.get("rawData").toString();
		Map<String, String> result = Ddzy251_NB_Util.decode(rawData.getBytes());
		return R.status(true);
	}

	@PostMapping("/electricMeter/commandResponse")
	public R iotDeviceCommandResponse(@RequestBody Map<String, Object> map) {

		log.error("commandResponse --> " + JSONUtil.toJsonStr(map));
		logger.info("electricMeter/commandResponse", JSONUtil.toJsonStr(map));

		return R.status(true);
	}

	@PostMapping("/electricMeter/eventReport")
	public R iotDeviceEventReport(@RequestBody Map<String, Object> map) {

		log.error("eventReport --> " + JSONUtil.toJsonStr(map));
		logger.info("electricMeter/eventReport", JSONUtil.toJsonStr(map));
		return R.status(true);
	}

	@PostMapping("/electricMeter/deviceOnlineOfflineReport")
	public R iotDeviceDataReportTupUnion(@RequestBody Map<String, Object> map) {

		log.error("deviceOnlineOfflineReport --> " + JSONUtil.toJsonStr(map));
		logger.info("electricMeter/deviceOnlineOfflineReport", JSONUtil.toJsonStr(map));
		return R.status(true);
	}

	@PostMapping("/electricMeter/report")
	public R electricMeterReport(@RequestBody List<Map<String, Object>> mapList) {
		logger.info("/electricMeter/report", JSONUtil.toJsonStr(mapList));
		log.error("electricMeter report--> " + JSONUtil.toJsonStr(mapList));
		for(int i=0;i<mapList.size();i++){
			Map map = mapList.get(i);
			ElectricMeterRecord electricMeterRecord = this.buildElectriMeterRecord(map);
			ElectricMeterRecord isExist = electricMeterRecordService.getBaseMapper().selectOne(new QueryWrapper<>(new ElectricMeterRecord()).lambda().eq(ElectricMeterRecord::getReadTime, electricMeterRecord.getReadTime()).eq(ElectricMeterRecord::getImei,electricMeterRecord.getImei()));
			if(null != isExist){
				electricMeterRecord.setId(isExist.getId());
				electricMeterRecord.setOrgPosition(isExist.getOrgPosition());
			}else {
				SmartDevice smartDevice = smartDeviceService.getOne(new QueryWrapper<>(new SmartDevice()).lambda().eq(SmartDevice::getImei, electricMeterRecord.getImei()));
				if(null != smartDevice){
					electricMeterRecord.setOrgPosition(smartDevice.getOrgPosition());
				}
			}
			electricMeterRecordService.saveOrUpdate(electricMeterRecord);
		}

		return R.status(true);
	}


	/**
	 * 构建电表记录对象

	 * @param map{
	 *				deviceId : 设备id
	 *				deviceName: 设备名称
	 *				deviceType: 设备型号
	 *				imei:设备imei
	 *				deviceFactory: 设备厂家
	 *				installAddress: 设备安装位置
	 *				deviceStatus : 设备状态：1-正常 2-告警 3-失联
	 *				readTime : 抄表时间
	 *				dayValue : 今日用量
	 *				monthValue : 月用量
	 *				yearValue : 年用量
	 *				totalValue : 总用量
	 *           }
	 * @return ElectricMeterRecord
	 */
	private ElectricMeterRecord buildElectriMeterRecord(Map<String,Object> map){
		ElectricMeterRecord electricMeterRecord = new ElectricMeterRecord();

		electricMeterRecord.setDeviceId(map.get("deviceId").toString());
		electricMeterRecord.setDeviceName(map.get("deviceName").toString());
		electricMeterRecord.setDeviceType(map.get("deviceType").toString());
		electricMeterRecord.setImei(map.get("imei").toString());
		electricMeterRecord.setDeviceFactory(map.get("deviceFactory").toString());
		electricMeterRecord.setInstallAddress(map.get("installAddress").toString());
		if(null != map.get("deviceStatus")){
			electricMeterRecord.setDeviceStatus(map.get("deviceStatus").toString());
		}

		electricMeterRecord.setReadTime(map.get("readTime").toString().split(" ")[0]);
		electricMeterRecord.setDayValue(map.get("dayValue").toString());
		electricMeterRecord.setMonthValue(map.get("monthValue").toString());
		electricMeterRecord.setYearValue(map.get("yearValue").toString());
		electricMeterRecord.setTotalValue(map.get("totalValue").toString());

		return electricMeterRecord;
	}
}
