/*
 *      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.common.constant.CommonConstant;
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.constant.BladeConstant;
import org.springblade.core.tool.utils.Func;
import org.springblade.third.doordevice.feign.IDoorDeviceButtClient;
import org.springframework.util.Assert;
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.DoorDevice;
import org.springblade.device.vo.DoorDeviceVO;
import org.springblade.device.wrapper.DoorDeviceWrapper;
import org.springblade.device.service.IDoorDeviceService;
import org.springblade.core.boot.ctrl.BladeController;

import java.util.*;

/**
 *  控制器
 *
 * @author BladeX
 * @since 2021-04-19
 */
@RestController
@AllArgsConstructor
@RequestMapping("/doordevice")
@Api(value = "", tags = "接口")
public class DoorDeviceController extends BladeController {

	private final IDoorDeviceService doorDeviceService;
	private final IResidentialClient residentialClient;
	private final IDoorDeviceButtClient doorDeviceButtClient;

	/**
	 * 详情
	 */
	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入doorDevice")
	public R<DoorDeviceVO> detail(DoorDevice doorDevice) {
		DoorDevice detail = doorDeviceService.getOne(Condition.getQueryWrapper(doorDevice));
		return R.data(DoorDeviceWrapper.build().entityVO(detail));
	}

	/**
	 * 分页
	 */
	@GetMapping("/list")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "分页", notes = "传入doorDevice")
	public R<IPage<DoorDeviceVO>> list(@RequestParam Map<String,Object> doorDevice, Query query, BladeUser bladeUser) {
		QueryWrapper<DoorDevice> queryWrapper = Condition.getQueryWrapper(doorDevice, DoorDevice.class);
		queryWrapper.lambda().orderByDesc(DoorDevice::getCreateTime);
		IPage<DoorDevice> pages = doorDeviceService.page(Condition.getPage(query), (!bladeUser.getTenantId().equals(BladeConstant.ADMIN_TENANT_ID)) ? queryWrapper.lambda().eq(DoorDevice::getTenantId, bladeUser.getTenantId()) : queryWrapper);
		return R.data(DoorDeviceWrapper.build().pageVO(pages));
	}


	/**
	 * 自定义分页
	 */
	@GetMapping("/page")
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "分页", notes = "传入doorDevice")
	public R<IPage<DoorDeviceVO>> page(DoorDeviceVO doorDevice, Query query) {
		IPage<DoorDeviceVO> pages = doorDeviceService.selectDoorDevicePage(Condition.getPage(query), doorDevice);
		return R.data(pages);
	}

	/**
	 * 新增
	 */
	@PostMapping("/save")
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "新增", notes = "传入doorDevice")
	public R save(@Valid @RequestBody DoorDevice doorDevice) {
		return R.status(doorDeviceService.save(doorDevice));
	}

	/**
	 * 修改
	 */
	@PostMapping("/update")
	@ApiOperationSupport(order = 5)
	@ApiOperation(value = "修改", notes = "传入doorDevice")
	public R update(@Valid @RequestBody DoorDevice doorDevice) {
		return R.status(doorDeviceService.updateById(doorDevice));
	}

	/**
	 * 批量更新
	 */
	@PostMapping("/updateBatch")
	@ApiOperationSupport(order = 5)
	@ApiOperation(value = "批量更新", notes = "传入doorDevice")
	public R update(@Valid @RequestBody List<DoorDevice> doorDevices) {
		return R.status(doorDeviceService.saveOrUpdateBatch(doorDevices));
	}

	/**
	 * 新增或修改
	 */
	@PostMapping("/submit")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "新增或修改", notes = "传入doorDevice")
	public R submit(@Valid @RequestBody DoorDevice doorDevice) {
		Assert.hasText(doorDevice.getSerialNum(), "设备序列号必传");
		Residential residential = new Residential();
		residential.setId(doorDevice.getResidentialId());
		ResidentialVO residentialVO = residentialClient.detail(residential);
		Assert.notNull(residentialVO,"找不到对应的小区");
		doorDevice.setAgencyId(residentialVO.getAgencyId());
		LambdaQueryWrapper<DoorDevice> lambdaQueryWrapper = new LambdaQueryWrapper<>();
		lambdaQueryWrapper.eq(DoorDevice::getSerialNum, doorDevice.getSerialNum());
		List<DoorDevice> deviceList = doorDeviceService.list(lambdaQueryWrapper);
		Assert.isTrue(deviceList.size() == 0,"设备序列号已存在");
		doorDeviceService.saveOrUpdate(doorDevice);
//		if(saveOrUpdate && isNewDoorDevice){
//			doorDeviceButtClient.addDevices(Arrays.asList(doorDevice));
//		}
		return R.data(doorDevice);
	}


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

	/**
	 * 远程开门
	 * 兼容开门和关门
	 */
	@PostMapping("/remoteOpenDoor")
	@ApiOperationSupport(order = 8)
	@ApiOperation(value = "一键开门", notes = "传入id")
	public R remoteOpenDoor(@ApiParam(value = "主键", required = true) @RequestParam String id, @RequestParam boolean isOpen, BladeUser bladeUser) {
		DoorDevice doorDevice = doorDeviceService.getById(Func.toLong(id));
		if(doorDevice == null){
			return fail("设备不存在");
		}
		return doorDeviceService.remoteOpenDoor(CommonConstant.UserFlag.ADMIN_FLAG.getValue() + String.valueOf(bladeUser.getUserId()), bladeUser.getUserName(), CommonConstant.UserFlag.ADMIN_FLAG.getValue(), doorDevice.getSerialNum(), doorDevice.getDeviceFactory(), isOpen);
	}
	/**
	 * 获取门禁设备的经纬度坐标集合
	 */
	@GetMapping("/getDoorDeviceCoordinates")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入doorDevice")
	public R getDoorDeviceCoordinates() {
		List<DoorDevice> list = doorDeviceService.list(Condition.getQueryWrapper(new DoorDevice()).lambda()
			.ne(DoorDevice::getLatitude, "")
			.ne(DoorDevice::getLongitude, ""));
		return R.data(list);
	}



}
