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

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
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 org.springblade.community.entity.Residential;
import org.springblade.community.feign.IResidentialClient;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.BeanUtil;
import org.springblade.core.tool.utils.Func;
import org.springblade.device.entity.IotAlarm;
import org.springblade.device.entity.IotAlarmGroup;
import org.springblade.device.entity.IotAlarmGroupUser;
import org.springblade.device.entity.IotDevice;
import org.springblade.device.feign.IIotAlarmClient;
import org.springblade.device.feign.IIotAlarmGroupClient;
import org.springblade.device.feign.IIotAlarmGroupUserClient;
import org.springblade.device.feign.IIotDeviceClient;
import org.springblade.device.vo.IotAlarmGroupUserVO;
import org.springblade.device.vo.IotAlarmGroupVO;
import org.springblade.device.vo.IotAlarmVO;
import org.springblade.device.vo.IotDeviceVO;
import org.springblade.workorder.deviceorder.dto.DeviceOrderDTO;
import org.springblade.workorder.deviceorder.entity.DeviceOrder;
import org.springblade.workorder.deviceorder.service.IDeviceOrderService;
import org.springblade.workorder.deviceorder.vo.DeviceOrderStatisticsVO;
import org.springblade.workorder.deviceorder.vo.DeviceOrderVO;
import org.springblade.workorder.deviceorder.wrapper.DeviceOrderWrapper;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 设备工单 控制器
 *
 * @author BladeX
 * @since 2021-04-21
 */
@RestController
@AllArgsConstructor
@RequestMapping("/deviceorder")
@Api(value = "设备工单", tags = "设备工单接口")
public class DeviceOrderController extends BladeController {

	private final IDeviceOrderService deviceOrderService;
	private final IIotDeviceClient iotDeviceClient;
	private final IResidentialClient residentialClient;
	private final IIotAlarmClient iotAlarmClient;
	private final IIotAlarmGroupClient iotAlarmGroupClient;
	private final IIotAlarmGroupUserClient iotAlarmGroupUserClient;

	/**
	 * 详情
	 */
	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入deviceOrder")
	public R<DeviceOrderVO> detail(DeviceOrder deviceOrder) {
		DeviceOrder detail = deviceOrderService.getOne(Condition.getQueryWrapper(deviceOrder));
		return R.data(DeviceOrderWrapper.build().entityVO(detail));
	}

	/**
	 * 分页 设备工单
	 */
	@GetMapping("/list")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "分页", notes = "传入deviceOrder")
	public R<IPage<DeviceOrderVO>> list(DeviceOrder deviceOrder, Query query) {
		QueryWrapper<DeviceOrder> queryWrapper = Condition.getQueryWrapper(deviceOrder);
		queryWrapper.lambda().ne(DeviceOrder::getTenantId, "000000");
		IPage<DeviceOrder> pages = deviceOrderService.page(Condition.getPage(query), queryWrapper);
		return R.data(DeviceOrderWrapper.build().pageVO(pages));
	}


	/**
	 * 自定义分页 设备工单
	 */
	@GetMapping("/page")
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "分页", notes = "传入deviceOrder")
	public R<IPage<DeviceOrderVO>> page(DeviceOrderVO deviceOrder, Query query) {
		IPage<DeviceOrderVO> pages = deviceOrderService.selectDeviceOrderPage(Condition.getPage(query), deviceOrder);
		return R.data(pages);
	}

	/**
	 * 新增 设备工单
	 */
	@PostMapping("/save")
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "新增", notes = "传入deviceOrder")
	public R save(@Valid @RequestBody DeviceOrder deviceOrder) {
		return R.status(deviceOrderService.save(deviceOrder));
	}

	/**
	 * 修改 设备工单
	 */
	@PostMapping("/update")
	@ApiOperationSupport(order = 5)
	@ApiOperation(value = "修改", notes = "传入deviceOrder")
	public R update(@Valid @RequestBody DeviceOrder deviceOrder) {
		return R.status(deviceOrderService.updateById(deviceOrder));
	}

	/**
	 * 新增或修改 设备工单
	 */
	@PostMapping("/submit")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "新增或修改", notes = "传入deviceOrder")
	public R submit(@Valid @RequestBody DeviceOrderVO deviceOrder) {
		Long alarmId = deviceOrder.getId();
		deviceOrder.setId(null);
		deviceOrder.setAlarmTime(deviceOrder.getRecordTime());
		deviceOrder.setAlarmReason(deviceOrder.getName());
		deviceOrder.setJobStatus(1);//处理中

		IotDevice iotDevice = new IotDevice();
		iotDevice.setDeviceId(deviceOrder.getDeviceId());
		IotDeviceVO deviceVO = iotDeviceClient.detail(iotDevice);
		if (deviceVO != null) {
			deviceOrder.setAlarmPosition(deviceVO.getDeviceInstallAddress());
			Residential residential = residentialClient.getById(deviceVO.getResidentialId());
			Assert.notNull(residential, "告警设备所在小区不存在");
			//查询该告警设备是否已经存在告警组，如果有则生成工单，否则不生成工单。
			IotAlarmGroup iotAlarmGroup = new IotAlarmGroup();
			iotAlarmGroup.setTag(deviceVO.getDeviceType());
			iotAlarmGroup.setResidentialId(deviceVO.getResidentialId());
			IotAlarmGroupVO iotAlarmGroupVO = iotAlarmGroupClient.detail(iotAlarmGroup);
			Assert.notNull(iotAlarmGroupVO, "请先设置告警组");
			IotAlarmGroupUser iotAlarmGroupUser = new IotAlarmGroupUser();
			iotAlarmGroupUser.setGroupId(iotAlarmGroupVO.getId());
			List<IotAlarmGroupUserVO> iotAlarmGroupUserVOList = iotAlarmGroupUserClient.list(iotAlarmGroupUser);
			Assert.notEmpty(iotAlarmGroupUserVOList, "请先设置告警组处理人");
			String personNameString = iotAlarmGroupUserVOList.stream().map(IotAlarmGroupUserVO::getPerson).collect(Collectors.joining(","));
			String personPhoneString = iotAlarmGroupUserVOList.stream().map(IotAlarmGroupUserVO::getPhone).collect(Collectors.joining(","));
			deviceOrder.setHandlePerson(personNameString);
			deviceOrder.setHandlePhone(personPhoneString);
			deviceOrder.setTenantId(residential.getTenantId());
		}

		deviceVO = iotDeviceClient.getDeviceByDeviceIdOrImei(deviceOrder.getDeviceId());
		deviceOrder.setAlarmPosition(deviceVO.getDeviceInstallAddress());

		boolean result = deviceOrderService.saveOrUpdate(deviceOrder);
		//设置告警记录的工单id
		IotAlarm iotAlarm = new IotAlarm();
		iotAlarm.setId(alarmId);
		IotAlarmVO iotAlarmVO = iotAlarmClient.detail(iotAlarm);
		if (iotAlarmVO != null) {
			iotAlarmVO.setOrderId(deviceOrder.getId().toString());
			iotAlarmClient.update(iotAlarmVO);
		}

		return R.status(result);
	}


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

	@PostMapping("/getListByDeviceTypeList")
	public List<DeviceOrder> getListByDeviceTypeList(@RequestBody DeviceOrderDTO deviceOrderDTO) {
		DeviceOrder deviceOrder = Objects.requireNonNull(BeanUtil.copy(deviceOrderDTO, DeviceOrder.class));
		return this.deviceOrderService.list(Condition.getQueryWrapper(deviceOrder)
			.lambda().in(deviceOrderDTO.getDeviceTypeList().size() > 0, DeviceOrder::getDeviceType, deviceOrderDTO.getDeviceTypeList()));
	}

	/**
	 * 设备工单分类统计
	 */
	@GetMapping("/getDeviceJobStaticVo")
	public R<DeviceOrderStatisticsVO> getDeviceJobStaticVo() {

		DeviceOrderStatisticsVO deviceJobStaticVO = new DeviceOrderStatisticsVO();

		deviceJobStaticVO.setGasCount(getDeviceCount(100020, 10000017));//燃气监控总数
		deviceJobStaticVO.setSmokeCount(getDeviceCount(100004, 10000002));//烟感总数
		deviceJobStaticVO.setAlarmCount(getDeviceCount(950414, 0));//一键告警总数
		deviceJobStaticVO.setCoverCount(getDeviceCount(10000001, 0));//井盖监控总数
		deviceJobStaticVO.setLampCount(getDeviceCount(100011, 0));//智慧路灯总数
		deviceJobStaticVO.setParkCount(getDeviceCount(100007, 0));//地磁
		deviceJobStaticVO.setTrashbinCount(getDeviceCount(100022, 0));//垃圾桶
		deviceJobStaticVO.setXfCount(getDeviceCount(960417, 0));//智慧消防


		return R.data(deviceJobStaticVO);
	}

	/**
	 * 根据设备类型查询工单数量
	 *
	 * @param i 设备类型
	 * @param j 设备类型
	 * @return 工单数量
	 */
	private Integer getDeviceCount(int i, int j) {
		return deviceOrderService.getBaseMapper().selectCount(new QueryWrapper<>(new DeviceOrder()).lambda()
			.eq(DeviceOrder::getDeviceType, i).or(j != 0, qw -> qw.eq(DeviceOrder::getDeviceType, j)));
	}

	/**
	 * 开启流程
	 */
	@PostMapping("start-process")
	public R startProcess(@RequestBody DeviceOrder deviceOrder) {
		return R.status(this.deviceOrderService.startProcess(deviceOrder));
	}

	/**
	 * 完成流程
	 */
	@PostMapping("complete-process")
	public R completeProcess(@RequestBody DeviceOrderDTO deviceOrderDTO) {
		return R.status(this.deviceOrderService.completeProcess(deviceOrderDTO));
	}
}
