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

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
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.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;
import org.springblade.community.agency.entity.Agency;
import org.springblade.community.agency.service.IAgencyService;
import org.springblade.community.residential.entity.Residential;
import org.springblade.community.residential.service.IResidentialService;
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.secure.BladeUser;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.Func;
import org.springblade.homecare.alarmlist.entity.Alarm;
import org.springblade.homecare.alarmlist.service.IAlarmService;
import org.springblade.jobs.devicejob.entity.DeviceJob;
import org.springblade.jobs.devicejob.service.IDeviceJobService;
import org.springblade.jobs.devicejob.vo.AppDeviceJobStaticVO;
import org.springblade.jobs.devicejob.vo.DeviceJobStaticVO;
import org.springblade.jobs.devicejob.vo.DeviceJobVO;
import org.springblade.jobs.devicejob.wrapper.DeviceJobWrapper;
import org.springblade.smartapplication.devicelog.wrapper.DeviceLogWrapper;
import org.springblade.smartapplication.smartsmoke.entity.SmartDevice;
import org.springblade.smartapplication.smartsmoke.service.ISmartDeviceService;
import org.springblade.system.orgposition.service.IOrgPositionService;
import org.springblade.utils.QueryWrapperUtil;
import org.springframework.boot.test.autoconfigure.orm.jpa.AutoConfigureTestEntityManager;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.Map;

/**
 * 设备工单 控制器
 *
 * @author BladeX
 * @since 2020-10-17
 */
@RestController
@AllArgsConstructor
@RequestMapping("jobs/devicejob")
@Api(value = "设备工单", tags = "设备工单接口")
public class DeviceJobController extends BladeController {

	private IDeviceJobService deviceJobService;

	private IAlarmService alarmService;
	private ISmartDeviceService smartDeviceService;
	private IResidentialService residentialService;
	private IOrgPositionService orgPositionService;
	private IAgencyService agencyService;

	/**
	 * 详情
	 */
	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入deviceJob")
	public R<DeviceJob> detail(DeviceJob deviceJob) {
		DeviceJob detail = deviceJobService.getOne(Condition.getQueryWrapper(deviceJob));
		return R.data(detail);
	}

	/**
	 * 分页 设备工单
	 */
	@GetMapping("/list")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "分页", notes = "传入deviceJob")
	public R<IPage<DeviceJobVO>> list(@RequestParam Map<String, Object> deviceJob, Query query) {
		if (deviceJob.get("deviceUsage") == null){
			deviceJob.put("deviceUsage", "20");
		}
		Object agencyId = deviceJob.get("agencyId");
		if (agencyId != null){
			Agency agency = this.agencyService.getById(Long.parseLong(agencyId.toString()));
			deviceJob.put("orgPosition", agency.getOrgPosition());
			deviceJob.remove("agencyId");
		}
		Object residentialId = deviceJob.get("residentialId");
		if (residentialId != null){
			Residential residential = this.residentialService.getById(Long.parseLong(residentialId.toString()));
			deviceJob.put("orgPosition", residential.getOrgPosition());
			deviceJob.remove("residentialId");
		}
		IPage<DeviceJob> pages = deviceJobService.page(Condition.getPage(query), Condition.getQueryWrapper(deviceJob, DeviceJob.class).lambda().orderByDesc(DeviceJob::getAlarmTime));
		return R.data(DeviceJobWrapper.build(alarmService).pageVO(pages));
	}

	/**
	 * 自定义分页 设备工单
	 */
	@GetMapping("/page")
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "分页", notes = "传入deviceJob")
	public R<IPage<DeviceJobVO>> page(DeviceJobVO deviceJob, Query query, BladeUser bladeUser) {
		LambdaQueryWrapper<DeviceJob> wrapper = new QueryWrapperUtil<DeviceJob>().getBasicQueryWrapper(DeviceJob::getOrgPosition, deviceJob, bladeUser, orgPositionService);
		IPage<DeviceJob> pages = deviceJobService.page(Condition.getPage(query), wrapper);
		return R.data(DeviceJobWrapper.build(alarmService).pageVO(pages));
	}

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

	/**
	 * 修改 设备工单
	 */
	@PostMapping("/update")
	@ApiOperationSupport(order = 5)
	@ApiOperation(value = "修改", notes = "传入deviceJob")
	public R update(@Valid @RequestBody DeviceJob deviceJob) {
		boolean update = deviceJobService.updateById(deviceJob);
		if(update){
			if(deviceJob.getJobStatus() == 2){
				SmartDevice smartDevice = smartDeviceService.getDevice(null, deviceJob.getDeviceId());
				smartDevice.setDeviceStatus(1);
				smartDeviceService.updateById(smartDevice);
				return R.status(true);
			}
			return R.status(true);
		}
		return R.status(true);
	}

	/**
	 * 新增或修改 设备工单
	 */
	@PostMapping("/submit")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "新增或修改", notes = "传入deviceJob")
	@Transactional
	public R submit(@Valid @RequestBody DeviceJobVO deviceJob) {

		Long alarmId = deviceJob.getId();
		deviceJob.setId(null);
		deviceJob.setAlarmTime(deviceJob.getRecordTime());
		deviceJob.setAlarmReason(deviceJob.getName());
		deviceJob.setJobStatus(1);//处理中

		SmartDevice deviceWrapper = new SmartDevice();
		deviceWrapper.setDeviceId(deviceJob.getDeviceId());
		SmartDevice device = smartDeviceService.getOne(Condition.getQueryWrapper(deviceWrapper));
		if (device != null) {
			deviceJob.setAlarmPosition(device.getDeviceInstallAddress());
			Residential residential = residentialService.getById(device.getResidentialId());
			if (residential == null) {
				System.out.println("找不到该小区！！！！");
				R.status(false);
			}
			deviceJob.setHandler(residential.getPersonName());
			deviceJob.setPhone(residential.getPersonTel());
			deviceJob.setTenantId(residential.getTenantId());
		}
		boolean result = deviceJobService.saveOrUpdate(deviceJob);
		//设置告警记录的工单id
		Alarm alarm = alarmService.getById(alarmId);
		if(alarm!=null){
			alarm.setOrderId(deviceJob.getId().toString());
			alarmService.updateById(alarm);
		}

		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(deviceJobService.deleteLogic(Func.toLongList(ids)));
	}


	/**
	 * 设备工单分类统计
	 */
	@GetMapping("/getDeviceJobStaticVo")
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "设备工单分类统计")
	public R<DeviceJobStaticVO> getDeviceJobStaticVo() {

		DeviceJobStaticVO deviceJobStaticVO = new DeviceJobStaticVO();

		//烟感总数
		Integer smokeCount = deviceJobService.getBaseMapper().selectCount(new QueryWrapper<>(new DeviceJob()).lambda().eq(DeviceJob::getDeviceType, 100004).or().eq(DeviceJob::getDeviceType,10000002));
		//燃气监控总数
		Integer gasCount = deviceJobService.getBaseMapper().selectCount(new QueryWrapper<>(new DeviceJob()).lambda().eq(DeviceJob::getDeviceType, 100020).or().eq(DeviceJob::getDeviceType,10000017));

		//井盖监控总数
		Integer coverCount = deviceJobService.getBaseMapper().selectCount(new QueryWrapper<>(new DeviceJob()).lambda().eq(DeviceJob::getDeviceType, 3));
		//一键告警总数
		Integer alarmCount = deviceJobService.getBaseMapper().selectCount(new QueryWrapper<>(new DeviceJob()).lambda().eq(DeviceJob::getDeviceType, 4));
		//智慧路灯总数
		Integer lampCount = deviceJobService.getBaseMapper().selectCount(new QueryWrapper<>(new DeviceJob()).lambda().eq(DeviceJob::getDeviceType, 5));
		//智慧消防
		Integer xfCount = deviceJobService.getBaseMapper().selectCount(new QueryWrapper<>(new DeviceJob()).lambda().eq(DeviceJob::getDeviceType, 960417));
		//垃圾桶
		Integer trashBinCount = deviceJobService.getBaseMapper().selectCount(new QueryWrapper<>(new DeviceJob()).lambda().eq(DeviceJob::getDeviceType, 7));
		//停车监控
		Integer parkCount = deviceJobService.getBaseMapper().selectCount(new QueryWrapper<>(new DeviceJob()).lambda().eq(DeviceJob::getDeviceType, 8));
		//门磁
		Integer gateCount = deviceJobService.getBaseMapper().selectCount(new QueryWrapper<>(new DeviceJob()).lambda().eq(DeviceJob::getDeviceType, 9));

		deviceJobStaticVO.setAlarmCount(alarmCount);
		deviceJobStaticVO.setCoverCount(coverCount);
		deviceJobStaticVO.setGasCount(gasCount);
		deviceJobStaticVO.setGateCount(gateCount);
		deviceJobStaticVO.setLampCount(lampCount);
		deviceJobStaticVO.setParkCount(parkCount);
		deviceJobStaticVO.setSmokeCount(smokeCount);
		deviceJobStaticVO.setTrashbinCount(trashBinCount);
		deviceJobStaticVO.setXfCount(xfCount);


		return R.data(deviceJobStaticVO);
	}

	@PostMapping("/setOrgPosition")
	public R setOrgPosition(){
		List<DeviceJob> deviceJobs = deviceJobService.getBaseMapper().selectList(new QueryWrapper<>(new DeviceJob()));
		deviceJobs.parallelStream().forEach(deviceJob -> {
			String imei = deviceJob.getDeviceId();//设备imei
			if(imei != null){
				SmartDevice smartDevice = smartDeviceService.getBaseMapper().selectOne(new QueryWrapper<>(new SmartDevice()).lambda().eq(SmartDevice::getImei, imei));
				if(smartDevice != null){
					deviceJob.setOrgPosition(smartDevice.getOrgPosition()+"/"+deviceJob.getId());
					deviceJobService.updateById(deviceJob);
				}
			}

		});
		return new R();
	}


	@ApiOperation("园区小程序获取消防场景告警工单统计")
	@GetMapping("/getDeviceJobStaticByApp")
	public R<AppDeviceJobStaticVO> getDeviceJobStaticByApp(BladeUser bladeUser){
		AppDeviceJobStaticVO appDeviceJobStaticVO = new AppDeviceJobStaticVO();

		List<DeviceJob> deviceJobs = deviceJobService.getBaseMapper().selectList(new QueryWrapper<>(new DeviceJob()).lambda()
			.eq(DeviceJob::getDeviceType, 100004).or()
			.eq(DeviceJob::getDeviceType, 10000002).or()
			.eq(DeviceJob::getDeviceType, 960417).or()
			.eq(DeviceJob::getDeviceType, 100020).or()
			.eq(DeviceJob::getDeviceType, 10000017).eq(DeviceJob::getTenantId, bladeUser.getTenantId()));

		appDeviceJobStaticVO.setDeviceJobAmount(deviceJobs.size());
		long finish = deviceJobs.stream().filter(deviceJob -> 2 == deviceJob.getJobStatus()).count();
		appDeviceJobStaticVO.setResolvedAmount(Math.toIntExact(finish));
		appDeviceJobStaticVO.setResolvingAmount(appDeviceJobStaticVO.getDeviceJobAmount()-appDeviceJobStaticVO.getResolvedAmount());

		return R.data(appDeviceJobStaticVO);
	}
}
