/*
 *      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.device.controller;

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

import org.springblade.community.entity.Residential;
import org.springblade.community.feign.IResidentialClient;
import org.springblade.community.vo.ResidentialVO;
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.device.entity.ElevatorAlarmSetting;
import org.springblade.device.service.IElevatorAlarmSettingService;
import org.springblade.system.expand.feign.IOrgPositionClient;
import org.springblade.system.expand.util.QueryWrapperUtil;
import org.springblade.third.elevator.feign.IThirdElevatorDeviceClient;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RequestParam;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springblade.device.entity.ElevatorDevice;
import org.springblade.device.vo.ElevatorDeviceVO;
import org.springblade.device.wrapper.ElevatorDeviceWrapper;
import org.springblade.device.service.IElevatorDeviceService;
import org.springblade.core.boot.ctrl.BladeController;

import java.util.*;

/**
 * 云梯-电梯信息 控制器
 *
 * @author BladeX
 * @since 2021-04-19
 */
@RestController
@AllArgsConstructor
@RequestMapping("/elevatordevice")
@Api(value = "云梯-电梯信息", tags = "云梯-电梯信息接口")
public class ElevatorDeviceController extends BladeController {

	private final IElevatorDeviceService elevatorDeviceService;
	private final IOrgPositionClient orgPositionClient;
	private final IResidentialClient residentialClient;
	private final IElevatorAlarmSettingService elevatorAlarmSettingService;
	private final IThirdElevatorDeviceClient elevatorDeviceClient;

	/**
	 * 详情
	 */
	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入elevatorDevice")
	public R<ElevatorDeviceVO> detail(ElevatorDevice elevatorDevice) {
		ElevatorDevice detail = elevatorDeviceService.getOne(Condition.getQueryWrapper(elevatorDevice));
		return R.data(ElevatorDeviceWrapper.build().entityVO(detail));
	}

	/**
	 * 分页 云梯-电梯信息
	 */
	@GetMapping("/list")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "分页", notes = "传入elevatorDevice")
	public R<IPage<ElevatorDeviceVO>> list(@RequestParam Map<String,Object> elevatorDevice, Query query,BladeUser bladeUser) {
		LambdaQueryWrapper<ElevatorDevice> basicQueryWrapper = new QueryWrapperUtil<ElevatorDevice>().getBasicQueryWrapperByMap(ElevatorDevice::getOrgPosition, elevatorDevice,new ElevatorDevice(), bladeUser, orgPositionClient);
		IPage<ElevatorDevice> pages = elevatorDeviceService.page(Condition.getPage(query), basicQueryWrapper.eq(ElevatorDevice::getTenantId,bladeUser.getTenantId()));
		return R.data(ElevatorDeviceWrapper.build().pageVO(pages));
	}


	/**
	 * 自定义分页 云梯-电梯信息
	 */
	@GetMapping("/page")
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "分页", notes = "传入elevatorDevice")
	public R<IPage<ElevatorDeviceVO>> page(ElevatorDeviceVO elevatorDevice, Query query) {
		IPage<ElevatorDeviceVO> pages = elevatorDeviceService.selectElevatorDevicePage(Condition.getPage(query), elevatorDevice);
		return R.data(pages);
	}

	/**
	 * 新增 云梯-电梯信息
	 */
	@PostMapping("/save")
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "新增", notes = "传入elevatorDevice")
	public R save(@Valid @RequestBody ElevatorDevice elevatorDevice) {
		return R.status(elevatorDeviceService.save(elevatorDevice));
	}

	/**
	 * 修改 云梯-电梯信息
	 */
	@PostMapping("/update")
	@ApiOperationSupport(order = 5)
	@ApiOperation(value = "修改", notes = "传入elevatorDevice")
	public R update(@Valid @RequestBody ElevatorDevice elevatorDevice) {
		return R.status(elevatorDeviceService.updateById(elevatorDevice));
	}

	/**
	 * 新增或修改 云梯-电梯信息
	 */
	@PostMapping("/submit")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "新增或修改", notes = "传入elevatorDevice")
	public R submit(@Valid @RequestBody ElevatorDevice elevatorDevice) {
		if (elevatorDevice.getResidentialId() != null){
			Residential residential = residentialClient.getById(elevatorDevice.getResidentialId());
			elevatorDevice.setResidentialName(residential.getName());
			elevatorDevice.setOrgPosition(residential.getOrgPosition());
			elevatorDevice.setTenantId(residential.getTenantId());
		}
		return R.status(elevatorDeviceService.saveOrUpdate(elevatorDevice));
	}


	/**
	 * 删除 云梯-电梯信息
	 */
	@PostMapping("/remove")
	@ApiOperationSupport(order = 7)
	@ApiOperation(value = "逻辑删除", notes = "传入ids")
	public R remove(@ApiParam(value = "主键集合", required = true) @RequestParam String ids) {
		return R.status(elevatorDeviceService.deleteLogic(Func.toLongList(ids)));
	}


	/**
	 * 获取电梯小区名称select
	 */
	@GetMapping("/getLiftResidentialSelect")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入elevator")
	public R getLiftResidentialSelect(BladeUser bladeUser) {

		LambdaQueryWrapper<ElevatorDevice> basicQueryWrapper = new QueryWrapperUtil<ElevatorDevice>().getBasicQueryWrapper(ElevatorDevice::getOrgPosition, new ElevatorDevice(), bladeUser, orgPositionClient);
		List<ElevatorDevice> elevatorDevices = this.elevatorDeviceService.getBaseMapper().selectList(basicQueryWrapper);
		Set hs = new HashSet();
		elevatorDevices.forEach(item -> {
			hs.add(item.getNbhdName());
		});

		return R.data(hs);
	}

	/**
	 * 获取电梯list
	 */
	@GetMapping("/getLiftList")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入elevator")
	public R getLiftList(ElevatorDevice elevator) {
		List<ElevatorDevice> list = elevatorDeviceService.list(Condition.getQueryWrapper(elevator));
		return R.data(list);
	}

	/**
	 * 同步云梯信息
	 * @return
	 */
	@PostMapping("/sync")
	@ApiOperationSupport(order = 8)
	@ApiOperation(value = "同步云梯信息", notes = "")
	public R syncElevator(){
		List<ElevatorDevice> list = elevatorDeviceClient.sync();
		if(list != null && list.size() > 0){
			list.forEach(item -> {
				ElevatorDevice wrapper = new ElevatorDevice();
				wrapper.setRegisterCode(item.getRegisterCode());
				ElevatorDevice one = this.elevatorDeviceService.getOne(Condition.getQueryWrapper(wrapper));
				if (one != null){
					item.setId(one.getId());
				}else{
					item.setOrgPosition("/");
					item.setTenantId("000000");
				}

			});
			boolean saveResult = this.elevatorDeviceService.saveOrUpdateBatch(list);
			return R.status(saveResult);
		}else{
			return R.status(true);
		}
	}

	/**
	 * 获取电梯实时监控信息
	 */
	@GetMapping("/getRealvideo")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入elevator")
	public R getRealvideo(String registerCode) {
		R realvideo = elevatorDeviceClient.getRealvideo(registerCode);
		return realvideo;
	}

	/**
	 * 获取电梯历史告警信息(云梯接口)
	 */
	@GetMapping("/getLiftHisAlarm")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入elevator")
	public R getLiftHisAlarm(String registerCodes) {
		R liftHisAlarm = elevatorDeviceClient.getLiftHisAlarm(registerCodes);
		return liftHisAlarm;
	}


	/**
	 * 获取电梯小区列表（去重）
	 */
	@GetMapping("/getListWithYtelevatorXq")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入elevator")
	public R getListWithYtelevatorXq() {
		List<Long> residentialIds = elevatorDeviceService.getResidentialIds();
		List<Residential> list = residentialClient.getListWithYtelevatorXq(residentialIds);
		return R.data(list);
	}

	/**
	 * 获取电梯实时监控信息
	 */
	@GetMapping("/getAlarmVideo")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "获取电梯实时监控信息", notes = "传入alarmCode")
	public R getAlarmVideo(String alarmCode) {
		R alarmVideo = elevatorDeviceClient.getAlarmVideo(alarmCode);
		return alarmVideo;
	}

	/**
	 * 获取电梯当前状态
	 */
	@GetMapping("/getLiftStatus")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "获取电梯当前状态", notes = "传入elevator")
	public R getLiftStatus(String registerCode) {
		R liftStatus = elevatorDeviceClient.getLiftStatus(registerCode);
		return liftStatus;
	}

	/**
	 * 获取电梯环境监测数据
	 */
	@GetMapping("/getLiftPointData")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "获取电梯环境监测数据", notes = "传入registerCode")
	public R getLiftPointData(String registerCode) {
		R liftPointData = elevatorDeviceClient.getLiftPointData(registerCode);
		return liftPointData;
	}

	/**
	 * 电梯告警订阅
	 */
	@GetMapping("/getSubscribeUrl")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "获取电梯告警订阅", notes = "")
	public R getSubscribeUrl() {
		return R.data(elevatorAlarmSettingService.getById(1L));
	}
	/**
	 * 电梯告警订阅
	 */
	@PostMapping("/subscribeAlarmData")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "电梯告警订阅", notes = "传入webHookUrl")
	public R subscribeAlarmData(String webHookUrl) {
		R subscribeResult = elevatorDeviceClient.subscribeAlarmData(webHookUrl);
		ElevatorAlarmSetting setting = elevatorAlarmSettingService.getById(1L);
		if (subscribeResult.isSuccess()){
			//订阅或者取消订阅成功
			setting.setWebHookUrl(webHookUrl);
			elevatorAlarmSettingService.updateById(setting);
		}
		return subscribeResult;
	}

	/**
	 * 电梯告警订阅
	 */
	@PostMapping("/initData")
	public R initData() {
		List<ElevatorDevice> elevatorDevices = elevatorDeviceService.getBaseMapper().selectList(new QueryWrapper<>(new ElevatorDevice()));
		elevatorDevices.forEach(elevatorDevice -> {
			if(elevatorDevice.getResidentialId() != null){
				Residential searchResidential = new Residential();
				searchResidential.setGridId(elevatorDevice.getResidentialId());
				ResidentialVO detail = residentialClient.detail(searchResidential);
				if(detail != null){
					elevatorDevice.setResidentialId(detail.getId());
					elevatorDevice.setResidentialName(detail.getName());
					elevatorDevice.setOrgPosition(detail.getOrgPosition());
				}
				elevatorDeviceService.updateById(elevatorDevice);

			}

		});
		return R.data(true);
	}

}
