/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package org.springblade.homecare.alarmlist.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;

import javax.validation.Valid;

import org.springblade.alarm.alarmgroup.service.IAlarmGroupService;
import org.springblade.alarm.alarmgroupuser.service.IAlarmGroupUserService;
import org.springblade.community.residential.service.IResidentialService;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.Func;
import org.springblade.homecare.alarmlist.vo.AlarmStaticVO;
import org.springblade.smartapplication.smartsmoke.entity.SmartDevice;
import org.springblade.smartapplication.smartsmoke.service.ISmartDeviceService;
import org.springblade.system.orgposition.entity.OrgPosition;
import org.springblade.system.orgposition.service.IOrgPositionService;
import org.springblade.utils.AlarmSendSmsAndVoiceUtil;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springblade.homecare.alarmlist.entity.Alarm;
import org.springblade.homecare.alarmlist.vo.AlarmVO;
import org.springblade.homecare.alarmlist.wrapper.AlarmWrapper;
import org.springblade.homecare.alarmlist.service.IAlarmService;
import org.springblade.core.boot.ctrl.BladeController;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 设备告警 控制器
 *
 * @author BladeX
 * @since 2020-11-17
 */
@RestController
@AllArgsConstructor
@RequestMapping("alarmlist/alarm")
@Api(value = "设备告警", tags = "设备告警接口")
public class AlarmController extends BladeController {

	private IAlarmService alarmService;
	private IOrgPositionService orgPositionService;

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


	/**
	 * 详情
	 */
	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入alarm")
	public R<AlarmVO> detail(Alarm alarm) {
		Alarm detail = alarmService.getOne(Condition.getQueryWrapper(alarm));
		return R.data(AlarmWrapper.build().entityVO(detail));
	}

	/**
	 * 分页 设备告警
	 */
	@GetMapping("/list")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "分页", notes = "传入alarm")
	public R<IPage<Alarm>> list(@RequestParam Map<String,Object> alarm, Query query, BladeUser bladeUser) {

		String deptId = bladeUser.getDeptId();
		String[] deptIds = deptId.split(",");
		LambdaQueryWrapper<Alarm> wrapper = Condition.getQueryWrapper(alarm,Alarm.class).lambda();
		for(int i=0;i<deptIds.length;i++){
			OrgPosition orgPosition = orgPositionService.getOne(new QueryWrapper<>(new OrgPosition()).lambda().eq(OrgPosition::getOrgId,deptIds[i]));
			if(i ==0){
				wrapper.like(Alarm::getOrgPosition,orgPosition.getOrgPosition());
			}else{
				wrapper.or().like(Alarm::getOrgPosition,orgPosition.getOrgPosition());
			}
		}

		query.setDescs("record_time");

//		IPage<Alarm> pages = alarmService.page(Condition.getPage(query), Condition.getQueryWrapper(alarm));

		IPage<Alarm> pages = alarmService.page(Condition.getPage(query), wrapper.eq(Alarm::getTenantId, bladeUser.getTenantId()));
		return R.data(pages);
	}


	/**
	 * 自定义分页 设备告警
	 */
	@GetMapping("/page")
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "分页", notes = "传入alarm")
	public R<IPage<AlarmVO>> page(AlarmVO alarm, Query query, BladeUser bladeUser) {
		IPage<AlarmVO> pages = alarmService.selectAlarmPage(Condition.getPage(query), alarm);
		return R.data(pages);
	}

	/**
	 * 新增 设备告警
	 */
	@PostMapping("/save")
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "新增", notes = "传入alarm")
	public R save(@Valid @RequestBody Alarm alarm) {
		return R.status(alarmService.save(alarm));
	}

	/**
	 * 修改 设备告警
	 */
	@PostMapping("/update")
	@ApiOperationSupport(order = 5)
	@ApiOperation(value = "修改", notes = "传入alarm")
	public R update(@Valid @RequestBody Alarm alarm) {
		return R.status(alarmService.updateById(alarm));
	}

	/**
	 * 新增或修改 设备告警
	 */
	@PostMapping("/submit")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "新增或修改", notes = "传入alarm")
	public R submit(@Valid @RequestBody Alarm alarm) {

		return R.status(alarmService.saveOrUpdate(alarm));
	}


	/**
	 * 删除 设备告警
	 */
	@PostMapping("/remove")
	@ApiOperationSupport(order = 8)
	@ApiOperation(value = "删除", notes = "传入ids")
	public R remove(@ApiParam(value = "主键集合", required = true) @RequestParam String ids) {
		return R.status(alarmService.removeByIds(Func.toLongList(ids)));
	}


	/**
	 * 告警统计
	 */
	@GetMapping("/staticAlarm")
	@ApiOperationSupport(order = 9)
	@ApiOperation(value = "统计", notes = "")
	public R<AlarmStaticVO> staticAlarm() {

		AlarmStaticVO alarmStaticVO = new AlarmStaticVO();
		/*
		 * 获取近七日日期值
		 * */
		List<String> dateList = getDates();
		alarmStaticVO.setDateList(dateList);
		return R.data(alarmStaticVO);
	}

	private List<String> getDates() {
		List<String> dateList = new ArrayList<>();

		dateList.add(LocalDate.now().plusDays(-7).toString());
		dateList.add(LocalDate.now().plusDays(-6).toString());
		dateList.add(LocalDate.now().plusDays(-5).toString());
		dateList.add(LocalDate.now().plusDays(-4).toString());
		dateList.add(LocalDate.now().plusDays(-3).toString());
		dateList.add(LocalDate.now().plusDays(-2).toString());
		dateList.add(LocalDate.now().plusDays(-1).toString());

		return dateList;
	}

	/**
	 * 告警统计
	 */
	@GetMapping("/test")
	@ApiOperationSupport(order = 9)
	@ApiOperation(value = "统计", notes = "")
	public R test() {
		List<Alarm> list = alarmService.list();

		list.forEach(item -> {
			String deviceId = item.getDeviceId();
			SmartDevice device = new SmartDevice();
			device.setDeviceId(deviceId);
			SmartDevice one = smartDeviceService.getOne(Condition.getQueryWrapper(device));
			if (one != null) {
				item.setOrgPosition(one.getOrgPosition());
				alarmService.updateById(item);
			}
		});

		return  R.status(true);
	}

	/**
	 * 实时获取告警信息
	 */
	@GetMapping("/getAlarmFromRedis")
	@ApiOperationSupport(order = 9)
	@ApiOperation(value = "实时获取告警信息", notes = "")
	public R getAlarmFromRedis(BladeUser bladeUser) {

		Set<String> keys = redisTemplate.keys("ycwg:alarm:" + bladeUser.getUserId()+"*");
		if(keys.size()>0){
			for(String key : keys){
				redisTemplate.delete(key);
			}
			return R.data("true");
		}else{
			return  R.data("false");
		}

	}



	/**
	 * 大屏发送告警短信
	 */
	@PostMapping("/sendAlarmSms")
	@ApiOperationSupport(order = 9)
	@ApiOperation(value = "大屏发送告警短信", notes = "")
	public R sendAlarmSms(@RequestBody Alarm alarm) {
		new AlarmSendSmsAndVoiceUtil(redisTemplate,smartDeviceService,residentialService,alarmGroupService,alarmGroupUserService).sendSms(alarm);
		return R.status(true);
	}

	@PostMapping("/setOrgPosition")
	public R setOrgPosition(BladeUser bladeUser) {
		List<Alarm> alarms = alarmService.getBaseMapper().selectList(new QueryWrapper<>(new Alarm()).lambda().eq(Alarm::getTenantId,bladeUser.getTenantId()));
		for(int i = 0;i<alarms.size();i++){
			Alarm alarm = alarms.get(i);
			String imei = alarms.get(i).getDeviceId();//设备imei

			SmartDevice smartDevice = smartDeviceService.getBaseMapper().selectOne(new QueryWrapper<>(new SmartDevice()).lambda().eq(SmartDevice::getImei, imei));
			if(smartDevice != null){
				alarm.setOrgPosition(smartDevice.getOrgPosition()+"/"+alarm.getId());
				alarmService.updateById(alarm);
			}
		}

		return R.status(true);
	}


}
