package org.springblade.openinterface.dianxin.xiaoyigj.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.AllArgsConstructor;
import org.springblade.alarm.alarmgroup.service.IAlarmGroupService;
import org.springblade.alarm.alarmgroupuser.service.IAlarmGroupUserService;
import org.springblade.community.houseuser.entity.Houseuser;
import org.springblade.community.houseuser.service.IHouseuserService;
import org.springblade.community.residential.entity.Residential;
import org.springblade.community.residential.service.IResidentialService;
import org.springblade.core.log.logger.BladeLogger;
import org.springblade.jiyueplatform.entity.JiyueDeviceOrder;
import org.springblade.jiyueplatform.service.IJiyueDeviceOrderService;
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.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author lidexi
 * @date 2021/6/24 10:23
 * 宁夏分平台接受集约平台推送的数据
 */
@RestController
@AllArgsConstructor
@RequestMapping("/openinterface/jiyue")
public class DataAcceptController {

	private final IJiyueDeviceOrderService jiyueDeviceOrderService;
	private final IHouseuserService houseuserService;
	private final IResidentialService residentialService;
	private final ISmartDeviceService smartDeviceService;
	private final BladeLogger bladeLogger;

	private final RedisTemplate<String,String> redisTemplate;

	private final IAlarmGroupService alarmGroupService;
	private final IAlarmGroupUserService alarmGroupUserService;

	/**
	 * code	返回值 	int	0：成功；
	 * 1：失败；
	 * 2：未绑定社区；
	 * 3：无此用户	是
	 * @param jiyueDeviceOrder
	 * @return code    返回值 	int
	 *   0：成功；
	 * 	 1：失败；
	 * 	 2：未绑定社区；
	 * 	 3：无此用户
	 */

	@PostMapping("/deviceData")
	public Map<String,Object> deviceDataAccept(@RequestBody JiyueDeviceOrder jiyueDeviceOrder){
		Map<String,Object> resultMap = new HashMap<>();
		resultMap.put("code",0);
		jiyueDeviceOrder.setRemark("成功");
		List<JiyueDeviceOrder> deviceOrders = jiyueDeviceOrderService.getBaseMapper().selectList(new QueryWrapper<>(new JiyueDeviceOrder()).lambda()
			.eq(JiyueDeviceOrder::getOrderNo, jiyueDeviceOrder.getOrderNo()));
		if(deviceOrders.size()>0){
			if("revoke".equals(jiyueDeviceOrder.getActionType())){//取消授权
				List<SmartDevice>  isExistDevice = smartDeviceService.getBaseMapper().selectList(new QueryWrapper<>(
					new SmartDevice()
				).lambda().eq(SmartDevice::getImei, jiyueDeviceOrder.getImei()));
				if(isExistDevice.size()>0){
					SmartDevice smartDevice = isExistDevice.get(0);
					smartDevice.setIsDeleted(-1);
					smartDeviceService.updateById(smartDevice);
				}
			}
			return resultMap;
		}
		jiyueDeviceOrderService.save(jiyueDeviceOrder);

		List<Houseuser> houseuserList = houseuserService.getBaseMapper().selectList(new QueryWrapper<>(new Houseuser())
			.lambda().eq(Houseuser::getTel,jiyueDeviceOrder.getUserPhone()));

		if(houseuserList.size() == 0){
			resultMap.put("code",3);
			jiyueDeviceOrder.setRemark("无此用户");
		}else{
			if(jiyueDeviceOrder.getCommunityId() == null){
				resultMap.put("code",2);
				jiyueDeviceOrder.setRemark("未绑定小区");
			}else{
				List<Long> residentialIds = houseuserList.stream().map(Houseuser::getResidentialId).collect(Collectors.toList());
				boolean flag = false;
				for(Long residentialId : residentialIds){
					if(jiyueDeviceOrder.getCommunityId().equals(residentialId.toString())){
						flag =true;
						SmartDevice smartDevice = new SmartDevice();
						List<SmartDevice> isExistDevice = null;
						if(jiyueDeviceOrder.getImei() != null){
							isExistDevice = smartDeviceService.getBaseMapper().selectList(new QueryWrapper<>(
								new SmartDevice()
							).lambda().eq(SmartDevice::getImei, jiyueDeviceOrder.getImei()));
							smartDevice.setDeviceId(jiyueDeviceOrder.getImei());
							smartDevice.setImei(jiyueDeviceOrder.getImei());
						}else if(jiyueDeviceOrder.getCtei() != null){
							isExistDevice = smartDeviceService.getBaseMapper().selectList(new QueryWrapper<>(
								new SmartDevice()
							).lambda().eq(SmartDevice::getImei, jiyueDeviceOrder.getCtei()));
							smartDevice.setDeviceId(jiyueDeviceOrder.getCtei());
							smartDevice.setImei(jiyueDeviceOrder.getCtei());
						}

						if(isExistDevice == null || isExistDevice.size() ==0){//新增设备
							smartDevice.setDeviceType(jiyueDeviceOrder.getDeviceType());
							if(jiyueDeviceOrder.getDeviceType().equals("3")){
								smartDevice.setDeviceType("100004");
							}

							if(jiyueDeviceOrder.getDeviceType().equals("4")){
								smartDevice.setDeviceType("100020");
							}


							smartDevice.setResidentialId(residentialId);
							Residential residential = residentialService.getById(residentialId);
							if(residential == null){
								resultMap.put("code",2);
								jiyueDeviceOrder.setRemark("小区id："+residentialId+"在本平台不存在");
							}else {
								List<Houseuser> houseusers = houseuserList.stream().filter(houseuser -> houseuser.getResidentialId() == residentialId).collect(Collectors.toList());
								jiyueDeviceOrder.setUserId(houseusers.get(0).getId());
								smartDevice.setDeviceName(jiyueDeviceOrder.getDeviceName());
								smartDevice.setDeviceInstallAddress(jiyueDeviceOrder.getLocation());
								smartDevice.setOrgPosition(residential.getOrgPosition());
								smartDevice.setDeviceUsage(10);
								smartDevice.setOrganization("集约平台推送");
								smartDeviceService.save(smartDevice);
							}
						}else {
							jiyueDeviceOrder.setRemark("设备已经存在，新增设备和用户的关联关系");
						}

					}
				}

				if(!flag){
					jiyueDeviceOrder.setRemark("未绑定小区");
					resultMap.put("code",2);
				}
			}

		}

		jiyueDeviceOrderService.saveOrUpdate(jiyueDeviceOrder);
		return resultMap;
	}

	@PostMapping("/deviceStatusReport")
	public Map<String,Object> deviceStatusReport(@RequestBody Map<String,Object> map){
		bladeLogger.info("集约平台设备信息(告警上下线)推送接口", JSON.toJSONString(map));
		Map<String,Object> resultMap = new HashMap<>();
		resultMap.put("code",0);
		boolean flag = true;
		Object messageType = map.get("messageType");//内容类型：1-上下线上报 2-状态上报
		Object ctei = map.get("ctei");//设备的imei
		Object phone = map.get("phone");//用户的手机号码
		List<SmartDevice> smartDevices = null;
		if(ctei != null){
			 smartDevices = smartDeviceService.getBaseMapper().selectList(new QueryWrapper<>(new SmartDevice())
				.lambda().eq(SmartDevice::getImei,ctei.toString()));

		}else {
			flag = false;
		}
		if(flag&&smartDevices.size()>0&&messageType != null){
			SmartDevice smartDevice = smartDevices.get(0);
			int type = Integer.valueOf(messageType.toString());
			switch (type){
				case 1://上下线上报 online设备在线状态，1在线，0离线
					Map messageBody = (Map) map.get("messageBody");
					Object online = messageBody.get("online");
					smartDevice.setDeviceStatus(Integer.valueOf(online.toString()) == 1 ? 1 : 3);//本平台设备状态： 1-正常 3-失联
					smartDeviceService.updateById(smartDevice);
					//发送短信通知
					List<IotSmsSendDto> iotSmsSendDtoList = new ArrayList<>();
					if(phone != null){


						IotSmsSendDto iotSmsSendDto = new IotSmsSendDto();
						IotSmsTemplateParam iotSmsTemplateParam = new IotSmsTemplateParam();
						iotSmsTemplateParam.setParam1(phone.toString());//接收人称呼


						iotSmsTemplateParam.setParam2(LocalDateTime.now().toString());//告警时间
						iotSmsTemplateParam.setParam3(smartDevice.getDeviceInstallAddress());//小区名称

						iotSmsTemplateParam.setParam4(smartDevice.getDeviceName());//设备名称
						iotSmsTemplateParam.setParam5(Integer.valueOf(online.toString()) == 1 ? "上线" : "下线");


						iotSmsSendDto.setTemplate_param(iotSmsTemplateParam);
						iotSmsSendDto.setMobile(phone.toString());
						iotSmsSendDto.setTemplate_id("91556324");
						iotSmsSendDto.setPrefix("ctwing/smoke3");

						iotSmsSendDto.setTimestamp(LocalDateTime.now().toString());
						iotSmsSendDtoList.add(iotSmsSendDto);
					}
//					new AlarmSendSmsAndVoiceUtil(redisTemplate,smartDeviceService,residentialService,alarmGroupService,alarmGroupUserService).sendNormalSms(iotSmsSendDtoList);
					break;
				case 2://状态上报

					Map messageBody1 = (Map) map.get("messageBody");
					Object online1 = messageBody1.get("status");
					JSONArray jsonArray = JSONArray.parseArray(online1.toString());
//					jsonArray.toJavaList()
					break;
			}
		}

		return resultMap;
	}


}
