/*
 *      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.smartapplication.facedevice.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.common.Constants;
import org.springblade.community.accessrecord.service.IAccessRecordService;
import org.springblade.community.agency.entity.Agency;
import org.springblade.community.residential.entity.Residential;
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.secure.utils.AuthUtil;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.Func;
import org.springblade.core.tool.utils.StringUtil;
import org.springblade.modules.system.entity.Dept;
import org.springblade.modules.system.service.IDeptService;
import org.springblade.mq.enums.Instruct;
import org.springblade.mq.service.MsgPublishService;
import org.springblade.openinterface.facedevice.qinlin.beans.QinLinApiResultBean;
import org.springblade.openinterface.facedevice.qinlin.util.QinLinHttpUtil;
import org.springblade.openinterface.facedevice.qinlin.util.ZHHttpUtil;
import org.springblade.openinterface.facedevice.qinlin.vo.QLinUserDevice;
import org.springblade.smartapplication.facedevice.dto.FaceDeviceDTO;
import org.springblade.system.orgposition.entity.OrgPosition;
import org.springblade.system.orgposition.service.IOrgPositionService;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springblade.smartapplication.facedevice.entity.FaceDevice;
import org.springblade.smartapplication.facedevice.vo.FaceDeviceVO;
import org.springblade.smartapplication.facedevice.wrapper.FaceDeviceWrapper;
import org.springblade.smartapplication.facedevice.service.IFaceDeviceService;
import org.springblade.core.boot.ctrl.BladeController;

import java.util.List;
import java.util.Map;

/**
 *  控制器
 *
 * @author BladeX
 * @since 2020-12-04
 */
@RestController
@AllArgsConstructor
@RequestMapping("facedevice/facedevice")
@Api(value = "", tags = "接口")
public class FaceDeviceController extends BladeController {

	private IFaceDeviceService faceDeviceService;
	private IResidentialService residentialService;
	private QinLinHttpUtil qinLinHttpUtil;
	private MsgPublishService msgPublishService;
	private IDeptService deptService;
	private IOrgPositionService orgPositionService;
	private ZHHttpUtil zhHttpUtil;

	/**
	 * 详情
	 */
	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入faceDevice")
	public R<FaceDeviceVO> detail(FaceDevice faceDevice) {
		FaceDevice detail = faceDeviceService.getOne(Condition.getQueryWrapper(faceDevice));
		return R.data(FaceDeviceWrapper.build().entityVO(detail));
	}

	/**
	 * 分页
	 */
	@GetMapping("/list")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "分页", notes = "传入faceDevice")
	public R<IPage<FaceDeviceVO>> list(@RequestParam Map<String, Object> faceDevice, Query query, BladeUser bladeUser) {
		String deptId = bladeUser.getDeptId();
		String[] deptIds = deptId.split(",");

		LambdaQueryWrapper<FaceDevice> wrapper = Condition.getQueryWrapper(faceDevice, FaceDevice.class).lambda().eq(FaceDevice::getTenantId, bladeUser.getTenantId());
		for (int i = 0; i < deptIds.length; i++) {
			Dept dept = deptService.getById(deptIds[i]);
			if(dept.getDeptCategory() == 1){
				return R.data(null);
			}
			OrgPosition orgPosition = orgPositionService.getBaseMapper().selectOne(new QueryWrapper<>(new OrgPosition()).lambda().eq(OrgPosition::getOrgId, deptIds[i]));
			if (i == 0) {
				wrapper.like(FaceDevice::getOrgPosition,orgPosition.getOrgPosition());
			}else{
				wrapper.or().like(FaceDevice::getOrgPosition,orgPosition.getOrgPosition());
			}
		}

		IPage<FaceDevice> pages = faceDeviceService.page(Condition.getPage(query), wrapper);
		return R.data(FaceDeviceWrapper.build().pageVO(pages));
	}


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

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

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

	/**
	 * 新增或修改
	 */
	@PostMapping("/submit")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "新增或修改", notes = "传入faceDevice")
	public R submit(@Valid @RequestBody FaceDevice faceDevice) {

		Residential residential = residentialService.getById(faceDevice.getResidentialId());
		Assert.notNull(residential, "residentialId为空！");
		faceDevice.setAgencyId(residential.getAgencyId());
		if(faceDevice.getId() == null){
			LambdaQueryWrapper<FaceDevice> lambdaQueryWrapper = new LambdaQueryWrapper<>();
			lambdaQueryWrapper.eq(FaceDevice::getMacAddress, faceDevice.getMacAddress());
			int count = faceDeviceService.count(lambdaQueryWrapper);
			if(count > 0){
				return R.fail("设备mac码已存在，请勿重复创建设备");
			}
			faceDeviceService.save(faceDevice);
			faceDevice.setOrgPosition(residential.getOrgPosition() + "/" + faceDevice.getId());
			boolean update = faceDeviceService.updateById(faceDevice);
			if(update){
				String tenantId = AuthUtil.getTenantId();
				if(StringUtil.isNotBlank(tenantId) && !"000000".equals(tenantId)) { //只允许园区区域注册小区到第三方
					return faceDeviceService.registerToThird(faceDevice);
				}else{
					return R.status(true);
				}
			}
		}
		faceDevice.setOrgPosition(residential.getOrgPosition() + "/" + faceDevice.getId());
		return R.status(faceDeviceService.updateById(faceDevice));
	}


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

	/**
	 * 设置orgPosition
	 */
	@PostMapping("/setOrgPosition")
	@ApiOperationSupport(order = 8)
	@ApiOperation(value = "设置orgPosition")
	public R setOrgPosition() {
		List<FaceDevice> faceDevices = faceDeviceService.getBaseMapper().selectList(new QueryWrapper<>(new FaceDevice()));
		for(int i =0;i<faceDevices.size();i++){
			FaceDevice faceDevice = faceDevices.get(i);
			Residential residential = residentialService.getById(faceDevice.getResidentialId());
			if(residential!=null){
				faceDevice.setOrgPosition(residential.getOrgPosition()+"/"+faceDevice.getId());
				faceDeviceService.updateById(faceDevice);
			}

		}

		return R.status(true);
	}


	/**
	 * 设置orgPosition
	 */
	@PostMapping("/remoteOpenDoor")
	@ApiOperationSupport(order = 9)
	@ApiOperation(value = "门禁设备远程开门")
	public R remoteOpenDoor(@RequestBody FaceDeviceDTO faceDeviceDTO){
		Long userId = faceDeviceDTO.getUserId();
		String macAddress = faceDeviceDTO.getMacAddress();
		if(userId == null){
			return R.fail("开门用户不能为空");
		}
		FaceDevice faceDevice = this.faceDeviceService.selectByMacAddress(macAddress);
		if(faceDevice != null){
			String deviceFactory = faceDevice.getDeviceFactory();
			switch (deviceFactory){
				case "qinlin":
					QLinUserDevice qLinUserDevice = new QLinUserDevice();
					qLinUserDevice.setUserId(userId.toString());
					qLinUserDevice.setDeviceId(macAddress);
					QinLinApiResultBean qinLinApiResultBean = qinLinHttpUtil.remoteOpenDoor(qLinUserDevice);
					if(qinLinApiResultBean.getCode().equals(0)){
						return R.status(true);
					}else{
						return R.fail("远程开门失败");
					}
				case "JVT":
					msgPublishService.publishJVT(userId, faceDevice.getMacAddress(), Instruct.JVT_OPEN_DOOR);
					break;
				case "zongheng":
					//创建开门纪录
					if(faceDeviceDTO.getUserType() == null){
						faceDeviceDTO.setUserType(Constants.UserType.STAFF.getType());
					}
					zhHttpUtil.remoteOpenDoor(userId, faceDeviceDTO.getUserType(), faceDevice.getMacAddress(), true);
					break;
			}
		}
		return R.status(true);
	}
}
