/**
 * Copyright 2019 DH
 * All right reserved.
 * 项目名称: 大恒泰山系统
 * 创建日期:2022/8/22
 */
package org.springblade.modules.business.check.order.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.*;
import lombok.RequiredArgsConstructor;
import org.springblade.constant.BusinessConstant;
import org.springblade.constant.DictBusinessConstant;
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.secure.utils.AuthUtil;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.Func;
import org.springblade.enums.*;
import org.springblade.modules.baseinfo.dict.entity.DictInfoEntity;
import org.springblade.modules.baseinfo.dict.service.IBaseInfoDictService;
import org.springblade.modules.baseinfo.org.entity.DeptRegionEntity;
import org.springblade.modules.baseinfo.org.service.IDeptRegionService;
import org.springblade.modules.baseinfo.rtu.entity.RtuInfoEntity;
import org.springblade.modules.baseinfo.rtu.service.IRtuBaseInfoService;
import org.springblade.modules.business.check.order.dto.CheckOrderInfoDTO;
import org.springblade.modules.business.check.order.entity.CheckOrderInfoEntity;
import org.springblade.modules.business.check.order.entity.CheckOrderSettingEntity;
import org.springblade.modules.business.check.order.service.ICheckOrderSettingService;
import org.springblade.modules.business.check.order.service.IRtuCheckOrderService;
import org.springblade.modules.business.check.order.vo.CheckOrderCountVO;
import org.springblade.modules.business.check.order.vo.CheckOrderInfoVO;
import org.springblade.modules.business.check.order.vo.OrgCheckOrderCountVO;
import org.springblade.modules.business.check.order.wrapper.RtuCheckOrderWrapper;
import org.springblade.modules.business.check.process.entity.OrderProcessInfoEntity;
import org.springblade.modules.business.check.process.service.IRtuOrderProcessService;
import org.springblade.modules.business.data.entity.RtuDataRainEntity;
import org.springblade.modules.business.data.entity.RtuDataRiverEntity;
import org.springblade.modules.business.data.entity.RtuDataRsvrEntity;
import org.springblade.modules.business.data.service.IRtuDataRainService;
import org.springblade.modules.business.data.service.IRtuDataRiverService;
import org.springblade.modules.business.data.service.IRtuDataRsvrService;
import org.springblade.modules.business.rtumanage.entity.RtuStatusEntity;
import org.springblade.modules.business.rtumanage.service.IRtuManageService;
import org.springblade.modules.business.warning.entity.RtuWarningInfoEntity;
import org.springblade.modules.business.warning.service.IRtuWarningService;
import org.springblade.modules.system.entity.Dept;
import org.springblade.modules.system.entity.DictBiz;
import org.springblade.modules.system.entity.User;
import org.springblade.modules.system.service.IDeptService;
import org.springblade.modules.system.service.IDictBizService;
import org.springblade.modules.system.service.IUserService;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.*;

/***
 * Date:2022/8/22
 * Title:文件所属模块（必须填写）
 * Description：对本文件的详细描述，原则上不能少于30字
 * @author dylan
 * @version 1.0
 * Remark：认为有必要的其他信息
 */
@RestController
@RequestMapping("galaxy-business/rtu/check/order")
@RequiredArgsConstructor
@Api(value = "测站设备故障工单管理模块", tags = "测站设备故障工单管理模块")
public class RtuCheckOrderController extends BladeController {

	private final IRtuCheckOrderService rtuCheckOrderService;
	private final IRtuOrderProcessService rtuOrderProcessService;
	private final IRtuWarningService rtuWarningService;
	private final IDictBizService dictBizService;
	private final IRtuManageService rtuManageService;
	private final IUserService userService;
	private final IDeptService deptService;
	private final IRtuBaseInfoService rtuBaseInfoService;
	private final IRtuDataRainService rtuDataRainService;
	private final IRtuDataRiverService rtuDataRiverService;
	private final IRtuDataRsvrService rtuDataRsvrService;
	private final IBaseInfoDictService baseInfoDictService;
	private final IDeptRegionService deptRegionService;
	private final ICheckOrderSettingService checkOrderSettingService;

	/**
	 * 工单查询，分页
	 */
	@GetMapping("/page")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "rtuCode", value = "测站编码", paramType = "query", dataType = "string"),
		@ApiImplicitParam(name = "rtuName", value = "测站名称", paramType = "query", dataType = "string"),
		@ApiImplicitParam(name = "adCode", value = "行政区划编码", paramType = "query", dataType = "string"),
		@ApiImplicitParam(name = "orderConfirm", value = "是否确认", paramType = "query", dataType = "int"),
		@ApiImplicitParam(name = "orderClose", value = "是否关闭", paramType = "query", dataType = "int"),
		@ApiImplicitParam(name = "servicePersonId", value = "运维人员", paramType = "query", dataType = "long"),
		@ApiImplicitParam(name = "deptId", value = "部门ID", paramType = "query", dataType = "long"),
		@ApiImplicitParam(name = "warnKind", value = "异常类型", paramType = "query", dataType = "int")
	})
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "分页", notes = "传入实体类CheckOrderInfoDTO")
	public R<IPage<CheckOrderInfoVO>> page(@ApiIgnore CheckOrderInfoDTO checkOrderInfoDTO, Query query) {
		BladeUser user = AuthUtil.getUser();
		if (checkOrderInfoDTO.getDeptId() != null) {
			LambdaQueryWrapper<DeptRegionEntity> deptLambdaQueryWrapper = Wrappers.<DeptRegionEntity>query().lambda();
			deptLambdaQueryWrapper.eq(DeptRegionEntity::getIsDeleted, 0);
			deptLambdaQueryWrapper.eq(DeptRegionEntity::getDeptId, checkOrderInfoDTO.getDeptId());
			DeptRegionEntity deptRegionEntity = deptRegionService.getOne(deptLambdaQueryWrapper);
			checkOrderInfoDTO.setAdCode(deptRegionEntity.getAdcd());
		} else {
			if (BusinessConstant.ROLE_SYS_ADMIN.equals(user.getRoleName())) {
				if (checkOrderInfoDTO.getAdCode() == null) {
					checkOrderInfoDTO.setAdCode(BusinessConstant.REGION_NM_ADCODE);
				}
			} else if (BusinessConstant.ROLE_ORG_ADMIN.equals(user.getRoleName()) || BusinessConstant.ROLE_COMPANY_ADMIN.equals(user.getRoleName()) || BusinessConstant.ROLE_COMPANY_SERVICE_PERSON.equals(user.getRoleName())) {
				if (checkOrderInfoDTO.getAdCode() == null) {
					LambdaQueryWrapper<DeptRegionEntity> deptRegionEntityLambdaQueryWrapper = Wrappers.<DeptRegionEntity>query().lambda();
					deptRegionEntityLambdaQueryWrapper.eq(DeptRegionEntity::getIsDeleted, 0);
					deptRegionEntityLambdaQueryWrapper.eq(DeptRegionEntity::getDeptId, Func.toLong(user.getDeptId()));
					DeptRegionEntity deptRegionEntity = deptRegionService.getOne(deptRegionEntityLambdaQueryWrapper);
					checkOrderInfoDTO.setAdCode(deptRegionEntity.getAdcd());
				}
			}
			 if (BusinessConstant.ROLE_COMPANY_SERVICE_PERSON.equals(user.getRoleName())) {
			     if(checkOrderInfoDTO.getOrderConfirm()!=null&&checkOrderInfoDTO.getOrderConfirm()==1 ){
					 checkOrderInfoDTO.setContactUser(user.getUserId());
				 }
			}
		}
		if (checkOrderInfoDTO.getWarnKind()!=null){
			IPage<CheckOrderInfoVO> pages = rtuCheckOrderService.selectWarnPage(Condition.getPage(query), checkOrderInfoDTO);
			List<CheckOrderInfoVO> list = pages.getRecords();
			for (CheckOrderInfoVO v : list) {
				RtuCheckOrderWrapper.build().entityVO(v);
			}
			return R.data(pages);
		}else{
			IPage<CheckOrderInfoVO> pages = rtuCheckOrderService.selectPage(Condition.getPage(query), checkOrderInfoDTO);
			List<CheckOrderInfoVO> list = pages.getRecords();
			for (CheckOrderInfoVO v : list) {
				RtuCheckOrderWrapper.build().entityVO(v);
			}
			return R.data(pages);
		}
	}

	/**
	 * 我的工单查询，分页
	 */
	@GetMapping("/my/page")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "rtuCode", value = "测站编码", paramType = "query", dataType = "string"),
		@ApiImplicitParam(name = "rtuName", value = "测站名称", paramType = "query", dataType = "string")
	})
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "分页", notes = "传入实体类CheckOrderInfoDTO")
	public R<IPage<CheckOrderInfoVO>> mypage(@ApiIgnore CheckOrderInfoDTO checkOrderInfoDTO, Query query) {
		BladeUser user = AuthUtil.getUser();
		checkOrderInfoDTO.setContactUser(user.getUserId());
		checkOrderInfoDTO.setOrderConfirm(OrderConfirmEnum.ACTIVE_CONFIRM.getCode());
		checkOrderInfoDTO.setOrderClose(OrderCloseEnum.ACTIVE_OPEN.getCode());
		IPage<CheckOrderInfoVO> pages = rtuCheckOrderService.selectMyPage(Condition.getPage(query), checkOrderInfoDTO);
		List<CheckOrderInfoVO> list = pages.getRecords();
		for (CheckOrderInfoVO v : list) {
			RtuCheckOrderWrapper.build().entityVO(v);
		}
		return R.data(pages);
	}

	/**
	 * 未确认工单列表，不分页,最多返回10条数据
	 */
	@GetMapping("/unconfirm/last/list")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "rtuCode", value = "测站编码", paramType = "query", dataType = "string"),
		@ApiImplicitParam(name = "rtuName", value = "测站名称", paramType = "query", dataType = "string"),
		@ApiImplicitParam(name = "adCode", value = "行政区划编码", paramType = "query", dataType = "string"),
	})
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "不分页", notes = "传入实体类CheckOrderInfoDTO")
	public R<List<CheckOrderInfoVO>> unconfirmOrderList(@ApiIgnore CheckOrderInfoDTO checkOrderInfoDTO) {
		BladeUser user = AuthUtil.getUser();
		if (BusinessConstant.ROLE_SYS_ADMIN.equals(user.getRoleName())) {
			if (checkOrderInfoDTO.getAdCode() == null) {
				checkOrderInfoDTO.setAdCode(BusinessConstant.REGION_NM_ADCODE);
			}
		} else if (BusinessConstant.ROLE_ORG_ADMIN.equals(user.getRoleName()) || BusinessConstant.ROLE_COMPANY_ADMIN.equals(user.getRoleName()) || BusinessConstant.ROLE_COMPANY_SERVICE_PERSON.equals(user.getRoleName())) {
			if (checkOrderInfoDTO.getAdCode() == null) {
				LambdaQueryWrapper<DeptRegionEntity> deptRegionEntityLambdaQueryWrapper = Wrappers.<DeptRegionEntity>query().lambda();
				deptRegionEntityLambdaQueryWrapper.eq(DeptRegionEntity::getIsDeleted, 0);
				deptRegionEntityLambdaQueryWrapper.eq(DeptRegionEntity::getDeptId, Func.toLong(user.getDeptId()));
				DeptRegionEntity deptRegionEntity = deptRegionService.getOne(deptRegionEntityLambdaQueryWrapper);
				checkOrderInfoDTO.setAdCode(deptRegionEntity.getAdcd());
			}
		}
		List<CheckOrderInfoVO> list = rtuCheckOrderService.unconfirmOrderList(checkOrderInfoDTO);
		for (CheckOrderInfoVO v : list) {
			RtuCheckOrderWrapper.build().entityVO(v);
		}
		return R.data(list);
	}

	@GetMapping("/confirm/delay/page")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "rtuCode", value = "测站编码", paramType = "query", dataType = "string"),
		@ApiImplicitParam(name = "rtuName", value = "测站名称", paramType = "query", dataType = "string"),
		@ApiImplicitParam(name = "adCode", value = "行政区划编码", paramType = "query", dataType = "string"),
	})
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "分页", notes = "传入实体类CheckOrderInfoDTO")
	public R<IPage<CheckOrderInfoVO>> unconfirmDelayPage(@ApiIgnore CheckOrderInfoDTO checkOrderInfoDTO, Query query) {
		BladeUser user = AuthUtil.getUser();
		if (BusinessConstant.ROLE_SYS_ADMIN.equals(user.getRoleName())) {
			if (checkOrderInfoDTO.getAdCode() == null) {
				checkOrderInfoDTO.setAdCode(BusinessConstant.REGION_NM_ADCODE);
			}
		} else if (BusinessConstant.ROLE_ORG_ADMIN.equals(user.getRoleName()) || BusinessConstant.ROLE_COMPANY_ADMIN.equals(user.getRoleName()) || BusinessConstant.ROLE_COMPANY_SERVICE_PERSON.equals(user.getRoleName())) {
			if (checkOrderInfoDTO.getAdCode() == null) {
				LambdaQueryWrapper<DeptRegionEntity> deptRegionEntityLambdaQueryWrapper = Wrappers.<DeptRegionEntity>query().lambda();
				deptRegionEntityLambdaQueryWrapper.eq(DeptRegionEntity::getIsDeleted, 0);
				deptRegionEntityLambdaQueryWrapper.eq(DeptRegionEntity::getDeptId, Func.toLong(user.getDeptId()));
				DeptRegionEntity deptRegionEntity = deptRegionService.getOne(deptRegionEntityLambdaQueryWrapper);
				checkOrderInfoDTO.setAdCode(deptRegionEntity.getAdcd());
			}
		}
		CheckOrderSettingEntity vo = new CheckOrderSettingEntity();
		LambdaQueryWrapper<CheckOrderSettingEntity> wrapper = Wrappers.<CheckOrderSettingEntity>query().lambda();
		wrapper.eq(CheckOrderSettingEntity::getIsDeleted, 0);
		List<CheckOrderSettingEntity> settingEntityList = checkOrderSettingService.list(wrapper);
		if (null != settingEntityList && settingEntityList.size() > 0) {
			CheckOrderSettingEntity settingEntity = settingEntityList.get(0);
			checkOrderInfoDTO.setOrderComfireDelayTime(settingEntity.getOrderComfireDelayTime());
		} else {
			checkOrderInfoDTO.setOrderComfireDelayTime(120);
		}

		IPage<CheckOrderInfoVO> pages = rtuCheckOrderService.selectConfirmDelayPage(Condition.getPage(query), checkOrderInfoDTO);
		List<CheckOrderInfoVO> list = pages.getRecords();
		for (CheckOrderInfoVO v : list) {
			RtuCheckOrderWrapper.build().entityVO(v);
		}
		return R.data(pages);
	}

	/**
	 * 详情
	 */
	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入实体类CheckOrderInfoEntity")
	public R<CheckOrderInfoVO> detail(CheckOrderInfoEntity checkOrderInfoEntity) {
		if (checkOrderInfoEntity.getId() == null) {
			return R.fail("参数错误");
		}
		CheckOrderInfoEntity detail = rtuCheckOrderService.getById(checkOrderInfoEntity.getId());
		LambdaQueryWrapper<RtuInfoEntity> wrapper = Wrappers.<RtuInfoEntity>query().lambda();
		wrapper.eq(RtuInfoEntity::getRtuCode, detail.getRtuCode());
		wrapper.eq(RtuInfoEntity::getIsDeleted, 0L);
		RtuInfoEntity rtuInfoEntity = rtuBaseInfoService.getOne(wrapper);
		CheckOrderInfoVO vo = RtuCheckOrderWrapper.build().entityVO(detail);
		vo.setRtuName(rtuInfoEntity.getRtuName());
		vo.setAdCity(rtuInfoEntity.getAdCity());
		vo.setAdDist(rtuInfoEntity.getAdDist());
		vo.setLocationDesc(rtuInfoEntity.getLocationDesc());
		vo.setLng(rtuInfoEntity.getLng());
		vo.setLat(rtuInfoEntity.getLat());
		vo.setNetworkPayer(rtuInfoEntity.getNetworkPayer());
		vo.setNetworkSimId(rtuInfoEntity.getNetworkSimId());
		vo.setIsRain(rtuInfoEntity.getIsRain());
		vo.setIsRiver(rtuInfoEntity.getIsRiver());
		vo.setIsRes(rtuInfoEntity.getIsRes());
		vo.setIsGround(rtuInfoEntity.getIsGround());
		vo.setIsVideo(rtuInfoEntity.getIsVideo());
		LambdaQueryWrapper<RtuStatusEntity> statusWwrapper = Wrappers.<RtuStatusEntity>query().lambda();
		statusWwrapper.eq(RtuStatusEntity::getRtuCode, detail.getRtuCode());
		statusWwrapper.eq(RtuStatusEntity::getIsDeleted, 0L);
		RtuStatusEntity statusEntity = rtuManageService.getOne(statusWwrapper);
		if (null != statusEntity) {
			vo.setLastUpTime(statusEntity.getLastUpTime());
		}
		if (rtuInfoEntity.getIsRain() != null && rtuInfoEntity.getIsRain() == 1) {
			LambdaQueryWrapper<RtuDataRainEntity> rainwrapper = Wrappers.<RtuDataRainEntity>query().lambda();
			rainwrapper.eq(RtuDataRainEntity::getRtuCode, detail.getRtuCode());
			rainwrapper.eq(RtuDataRainEntity::getIsDeleted, 0L);
			RtuDataRainEntity rainEntity = rtuDataRainService.getOne(rainwrapper);
			if (null != rainEntity) {
				vo.setDrp(rainEntity.getDrp());
			}
		} else if (rtuInfoEntity.getIsRiver() != null && rtuInfoEntity.getIsRiver() == 1) {
			LambdaQueryWrapper<RtuDataRiverEntity> riverwrapper = Wrappers.<RtuDataRiverEntity>query().lambda();
			riverwrapper.eq(RtuDataRiverEntity::getRtuCode, detail.getRtuCode());
			riverwrapper.eq(RtuDataRiverEntity::getIsDeleted, 0L);
			RtuDataRiverEntity riverEntity = rtuDataRiverService.getOne(riverwrapper);
			if (riverEntity != null) {
				vo.setZ(riverEntity.getZ());
			}
		} else if (rtuInfoEntity.getIsRes() != null && rtuInfoEntity.getIsRes() == 1) {
			LambdaQueryWrapper<RtuDataRsvrEntity> rsvrWrapper = Wrappers.<RtuDataRsvrEntity>query().lambda();
			rsvrWrapper.eq(RtuDataRsvrEntity::getRtuCode, detail.getRtuCode());
			rsvrWrapper.eq(RtuDataRsvrEntity::getIsDeleted, 0L);
			RtuDataRsvrEntity rsvrEntity = rtuDataRsvrService.getOne(rsvrWrapper);
			if (rsvrEntity != null) {
				vo.setRz(rsvrEntity.getRz());
			}
		} else if (rtuInfoEntity.getIsGround() != null && rtuInfoEntity.getIsGround() == 1) {

		}
		return R.data(vo);
	}

	/**
	 * 详情
	 */
	@GetMapping("/setting/detail")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "设置详情")
	public R<CheckOrderSettingEntity> settingDetail() {
		CheckOrderSettingEntity vo = new CheckOrderSettingEntity();
		LambdaQueryWrapper<CheckOrderSettingEntity> wrapper = Wrappers.<CheckOrderSettingEntity>query().lambda();
		wrapper.eq(CheckOrderSettingEntity::getIsDeleted, 0);
		List<CheckOrderSettingEntity> list = checkOrderSettingService.list(wrapper);
		if (null != list && list.size() > 0) {
			vo = list.get(0);
		} else {
			vo.setOrderComfireDelayTime(120);
		}
		return R.data(vo);
	}

	/**
	 * 新增
	 */
	@PostMapping("/save")
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "新增", notes = "传入实体类CheckOrderInfoEntity")
	public R save(@RequestBody CheckOrderInfoEntity checkOrderInfoEntity) {
		DictInfoEntity dictInfoEntity = baseInfoDictService.getDict(DictBusinessConstant.ORDER_STATUS_CODE, OrderStatusEnum.STATUS_CREATE.getCode());
		checkOrderInfoEntity.setOrderStatusKey(dictInfoEntity.getId());
		rtuCheckOrderService.save(checkOrderInfoEntity);
		OrderProcessInfoEntity processInfoEntity = new OrderProcessInfoEntity();
		processInfoEntity.setOrderId(checkOrderInfoEntity.getId());
		processInfoEntity.setOrderStatusKey(checkOrderInfoEntity.getOrderStatusKey());
		processInfoEntity.setProcessDesc(checkOrderInfoEntity.getOrderDesc());
		return R.status(rtuOrderProcessService.save(processInfoEntity));
	}

	/**
	 * 修改
	 */
	@PostMapping("/update")
	@ApiOperationSupport(order = 5)
	@ApiOperation(value = "修改", notes = "传入实体类CheckOrderInfoEntity")
	public R update(@RequestBody CheckOrderInfoEntity checkOrderInfoEntity) {
		return R.status(rtuCheckOrderService.updateById(checkOrderInfoEntity));
	}

	/**
	 * 新增或修改
	 */
	@PostMapping("/submit")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "新增或修改", notes = "传入实体类CheckOrderInfoEntity")
	public R submit(@RequestBody CheckOrderInfoEntity checkOrderInfoEntity) {
		return R.status(rtuCheckOrderService.saveOrUpdate(checkOrderInfoEntity));
	}

	/**
	 * 新增或修改
	 */
	@PostMapping("/setting/submit")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "新增或修改", notes = "传入实体类CheckOrderInfoEntity")
	public R settingSubmit(@RequestBody CheckOrderSettingEntity checkOrderSettingEntity) {
		if (checkOrderSettingEntity.getId() <= 0L) {
			checkOrderSettingEntity.setId(null);
		}
		return R.status(checkOrderSettingService.saveOrUpdate(checkOrderSettingEntity));
	}

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

	/**
	 * 工单关闭
	 *
	 * @param checkOrderInfoEntity
	 * @return
	 */
	@PostMapping("/close")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "id", value = "工单ID", paramType = "query", dataType = "long"),
		@ApiImplicitParam(name = "orderDesc", value = "处理意见", paramType = "query", dataType = "string")
	})
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "工单关闭", notes = "传入实体类CheckOrderInfoEntity")
	public R orderClose(@ApiIgnore CheckOrderInfoEntity checkOrderInfoEntity) {
		BladeUser user = AuthUtil.getUser();
		DictInfoEntity dictInfoEntity = baseInfoDictService.getDict(DictBusinessConstant.ORDER_STATUS_CODE, OrderStatusEnum.STATUS_CLOSE.getCode());
		checkOrderInfoEntity.setOrderStatusKey(dictInfoEntity.getId());
		CheckOrderInfoEntity detail = this.rtuCheckOrderService.getById(checkOrderInfoEntity.getId());
		if (null == detail || detail.getOrderClose() == OrderCloseEnum.ACTIVE_CLOSE.getCode()) {
			return R.status(false);
		}
		detail.setOrderStatusKey(checkOrderInfoEntity.getOrderStatusKey());
		detail.setOrderClose(OrderCloseEnum.ACTIVE_CLOSE.getCode());
		detail.setOrderConfirm(OrderConfirmEnum.ACTIVE_CONFIRM.getCode());
		detail.setUpdateTime(new Date());
		detail.setUpdateUser(user.getUserId());
		rtuCheckOrderService.updateById(detail);
		OrderProcessInfoEntity processInfoEntity = new OrderProcessInfoEntity();
		processInfoEntity.setOrderId(detail.getId());
		processInfoEntity.setOrderStatusKey(detail.getOrderStatusKey());
		if (checkOrderInfoEntity.getOrderDesc() != null) {
			processInfoEntity.setProcessDesc("由用户[" + user.getNickName() + "]人工关闭维修任务,处理意见:" + checkOrderInfoEntity.getOrderDesc());
		} else {
			processInfoEntity.setProcessDesc("由用户[" + user.getNickName() + "]人工关闭维修任务");
		}
		processInfoEntity.setCreateUser(user.getUserId());
		processInfoEntity.setUpdateUser(user.getUserId());
		rtuOrderProcessService.save(processInfoEntity);
		if (null != detail.getWarnId()) {
			List<DictBiz> orderFromDict = dictBizService.getList("rtu_check_order_from");
			for (DictBiz biz : orderFromDict) {
				if (biz.getDictKey().equals(OrderFromEnum.FROM_WARNING.getCode())) {
					RtuWarningInfoEntity warningInfoEntity = this.rtuWarningService.getById(detail.getWarnId());
					if (null != warningInfoEntity) {
						warningInfoEntity.setWarningRecoveryTime(new Date());
						warningInfoEntity.setWarningStatus(WarningStatusEnum.STATUS_CLOSE.getCode());
						warningInfoEntity.setUpdateTime(new Date());
						warningInfoEntity.setUpdateUser(user.getUserId());
						this.rtuWarningService.updateById(warningInfoEntity);
					}
					break;
				}
			}
		}
		RtuStatusEntity rtuStatusEntity = new RtuStatusEntity();
		rtuStatusEntity.setRunStatusId(EquipmentStatusEnum.STATUS_RUN.getCode());
		this.rtuManageService.updateRtuStatus(rtuStatusEntity);
		return R.success("工单关闭已操作成功！");
	}

	/**
	 * 查询最新的数据
	 */
	@GetMapping("/last/list")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "分页")
	public R<List<CheckOrderInfoVO>> lastList() {
		LambdaQueryWrapper<CheckOrderInfoEntity> wrapper = Wrappers.<CheckOrderInfoEntity>query().lambda();
		wrapper.orderByDesc(CheckOrderInfoEntity::getUpdateTime);
		wrapper.last("limit 1");
		List<CheckOrderInfoEntity> pages = rtuCheckOrderService.list(wrapper);
		return R.data(RtuCheckOrderWrapper.build().listVO(pages));
	}

	/**
	 * 工单确认
	 *
	 * @param checkOrderInfoEntity
	 * @return
	 */
	@PostMapping("/confirm")
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "工单确认", notes = "传入实体类CheckOrderInfoEntity")
	public R orderConfirm(@RequestBody CheckOrderInfoEntity checkOrderInfoEntity) {
		DictInfoEntity dictInfoEntity = baseInfoDictService.getDict(DictBusinessConstant.ORDER_STATUS_CODE, OrderStatusEnum.STATUS_CONFIRM.getCode());
		checkOrderInfoEntity.setOrderStatusKey(dictInfoEntity.getId());
		BladeUser user = AuthUtil.getUser();
		User userInfo = userService.getById(user.getUserId());
		CheckOrderInfoEntity detail = this.rtuCheckOrderService.getById(checkOrderInfoEntity.getId());
		if (null == detail || null != detail.getOrderConfirmUser()) {
			return R.status(false);
		}
		detail.setOrderConfirm(OrderConfirmEnum.ACTIVE_CONFIRM.getCode());
		detail.setOrderStatusKey(checkOrderInfoEntity.getOrderStatusKey());
		detail.setOrderConfirmUser(user.getUserId());
		detail.setOrderConfirmTime(new Date());
		detail.setUpdateTime(new Date());
		detail.setContactUser(userInfo.getId());
		detail.setContactPhone(userInfo.getPhone());
		rtuCheckOrderService.updateById(detail);
		OrderProcessInfoEntity processInfoEntity = new OrderProcessInfoEntity();
		processInfoEntity.setOrderId(checkOrderInfoEntity.getId());
		processInfoEntity.setOrderStatusKey(checkOrderInfoEntity.getOrderStatusKey());
		processInfoEntity.setProcessDesc("维修任务由[" + userInfo.getRealName() + "]确认");
		return R.status(rtuOrderProcessService.save(processInfoEntity));
	}

	@PostMapping("/manually")
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "人工生成工单", notes = "传入实体类CheckOrderInfoDTO")
	public R manuallyOrder(@RequestBody CheckOrderInfoDTO checkOrderInfoDTO) {
		if (null == checkOrderInfoDTO.getRtuCode()) {
			return R.status(false);
		}
		BladeUser user = AuthUtil.getUser();
		LambdaQueryWrapper<CheckOrderInfoEntity> wrapper = Wrappers.<CheckOrderInfoEntity>query().lambda();
		wrapper.eq(CheckOrderInfoEntity::getIsDeleted, 0);
		wrapper.eq(CheckOrderInfoEntity::getOrderClose, 0);
		wrapper.eq(CheckOrderInfoEntity::getRtuCode, checkOrderInfoDTO.getRtuCode());
		long orders = rtuCheckOrderService.count(wrapper);
		if (orders > 0) {
			return R.fail("当前测站已经有维修任务");
		}
		DictInfoEntity statusdict = baseInfoDictService.getDict(DictBusinessConstant.ORDER_STATUS_CODE, OrderStatusEnum.STATUS_CREATE.getCode());
		DictInfoEntity fromdict = baseInfoDictService.getDict(DictBusinessConstant.ORDER_FROM_CODE, OrderFromEnum.FROM_MANUALLY.getCode());
		checkOrderInfoDTO.setOrderClose(OrderCloseEnum.ACTIVE_OPEN.getCode());
		checkOrderInfoDTO.setOrderConfirm(OrderConfirmEnum.ACTIVE_CREATE.getCode());
		checkOrderInfoDTO.setOrderFromKey(fromdict.getId());
		checkOrderInfoDTO.setOrderStatusKey(statusdict.getId());
		checkOrderInfoDTO.setStatus(1);
		checkOrderInfoDTO.setCreateTime(new Date());
		checkOrderInfoDTO.setCreateUser(user.getUserId());
		checkOrderInfoDTO.setCreateDept(Func.toLong(user.getDeptId()));
		rtuCheckOrderService.save(checkOrderInfoDTO);
		//增加工单处理创建记录
		OrderProcessInfoEntity processInfoEntity = new OrderProcessInfoEntity();
		processInfoEntity.setOrderId(checkOrderInfoDTO.getId());
		processInfoEntity.setOrderStatusKey(statusdict.getId());
		processInfoEntity.setProcessDesc(checkOrderInfoDTO.getOrderDesc());

		rtuOrderProcessService.save(processInfoEntity);
		//更新测站状态
		RtuStatusEntity statusEntity = new RtuStatusEntity();
		statusEntity.setRtuCode(checkOrderInfoDTO.getRtuCode());
		statusEntity.setRunStatusId(EquipmentStatusEnum.STATUS_FAILURE.getCode());
		rtuManageService.updateRtuStatus(statusEntity);

		return R.status(true);
	}


	@PostMapping("/change")
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "任务指派", notes = "传入实体类CheckOrderInfoDTO")
	public R orderChange(@RequestBody CheckOrderInfoDTO checkOrderInfoDTO) {
		CheckOrderInfoEntity detail = this.rtuCheckOrderService.getById(checkOrderInfoDTO.getId());
		if (null == detail) {
			return R.status(false);
		}
		BladeUser user = AuthUtil.getUser();
		DictInfoEntity dictInfoEntity = baseInfoDictService.getDict(DictBusinessConstant.ORDER_STATUS_CODE, OrderStatusEnum.STATUS_CONFIRM.getCode());
		if (detail.getOrderConfirm() != OrderConfirmEnum.ACTIVE_CONFIRM.getCode()) {
			detail.setOrderConfirm(OrderConfirmEnum.ACTIVE_CONFIRM.getCode());
			detail.setOrderStatusKey(dictInfoEntity.getId());
			detail.setOrderConfirmUser(user.getUserId());
			detail.setOrderConfirmTime(new Date());
		}
		User userInfo = userService.getById(checkOrderInfoDTO.getServicePersonId());
		OrderProcessInfoEntity processInfoEntity = new OrderProcessInfoEntity();
		processInfoEntity.setOrderId(detail.getId());
		processInfoEntity.setOrderStatusKey(dictInfoEntity.getId());
		processInfoEntity.setProcessDesc("维修任务指派给[" + userInfo.getRealName() + "]");
		rtuOrderProcessService.save(processInfoEntity);
		detail.setUpdateTime(new Date());
		detail.setContactUser(userInfo.getId());
		detail.setContactPhone(userInfo.getPhone());
		rtuCheckOrderService.updateById(detail);
		return R.status(rtuCheckOrderService.updateById(detail));
	}


	/**
	 * 工单统计
	 *
	 * @return
	 */
	@GetMapping("/statistics")
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "统计表格")
	public R<List<CheckOrderCountVO>> orderStatistics() {
		BladeUser user = AuthUtil.getUser();
		List<CheckOrderCountVO> countList = new LinkedList<>();
		LambdaQueryWrapper<User> userQueryWrapper = Wrappers.<User>query().lambda();
		userQueryWrapper.eq(User::getIsDeleted, 0);
		userQueryWrapper.eq(User::getDeptId, Func.toLong(user.getDeptId()));
		List<User> list = userService.list(userQueryWrapper);
		for (User u : list) {
			CheckOrderCountVO vo = new CheckOrderCountVO();
			vo.setUserId(u.getId());
			vo.setServicePersonName(u.getRealName());
			LambdaQueryWrapper<CheckOrderInfoEntity> queryWrapper = Wrappers.<CheckOrderInfoEntity>query().lambda();
			queryWrapper.eq(CheckOrderInfoEntity::getIsDeleted, 0);
			queryWrapper.eq(CheckOrderInfoEntity::getOrderConfirm, OrderConfirmEnum.ACTIVE_CONFIRM.getCode());
			queryWrapper.eq(CheckOrderInfoEntity::getOrderConfirmUser, u.getId());
			long count = rtuCheckOrderService.count(queryWrapper);
			vo.setOrderCount(count);
			LambdaQueryWrapper<OrderProcessInfoEntity> reportQueryWrapper = Wrappers.<OrderProcessInfoEntity>query().lambda();
			reportQueryWrapper.eq(OrderProcessInfoEntity::getIsDeleted, 0);
			reportQueryWrapper.eq(OrderProcessInfoEntity::getCreateUser, u.getId());
			count = rtuOrderProcessService.count(reportQueryWrapper);
			vo.setProcessingOrderCount(count);
			countList.add(vo);
		}
		return R.data(countList);


	}

	/**
	 * 按机构统计工单
	 *
	 * @return
	 */
	@GetMapping("/org/statistics")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "adCode", value = "行政区划编码", paramType = "query", dataType = "string"),
	})
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "统计表格")
	public R<List<OrgCheckOrderCountVO>> orgOrderStatistics() {
		BladeUser user = AuthUtil.getUser();
		List<OrgCheckOrderCountVO> list = new LinkedList<>();
		LambdaQueryWrapper<Dept> wrapper = Wrappers.<Dept>query().lambda();
		wrapper.eq(Dept::getIsDeleted, 0);
		wrapper.eq(Dept::getParentId, Func.toLong(user.getDeptId()));
		List<Dept> root = this.deptService.list(wrapper);
		for (Dept dept : root) {
			OrgCheckOrderCountVO orgCheckOrderCountVO = new OrgCheckOrderCountVO();
			orgCheckOrderCountVO.setDeptId(dept.getId());
			orgCheckOrderCountVO.setOrgName(dept.getDeptName());
			CheckOrderInfoDTO checkOrderInfoDTO = new CheckOrderInfoDTO();
			LambdaQueryWrapper<DeptRegionEntity> deptLambdaQueryWrapper = Wrappers.<DeptRegionEntity>query().lambda();
			deptLambdaQueryWrapper.eq(DeptRegionEntity::getIsDeleted, 0);
			deptLambdaQueryWrapper.eq(DeptRegionEntity::getDeptId, dept.getId());
			DeptRegionEntity deptRegionEntity = deptRegionService.getOne(deptLambdaQueryWrapper);
			checkOrderInfoDTO.setAdCode(deptRegionEntity.getAdcd());
			checkOrderInfoDTO.setOrderClose(OrderCloseEnum.ACTIVE_OPEN.getCode());
			Long orderCount = rtuCheckOrderService.orderCount(checkOrderInfoDTO);
			orgCheckOrderCountVO.setOrderCount(orderCount);
			checkOrderInfoDTO.setOrderConfirm(OrderConfirmEnum.ACTIVE_CONFIRM.getCode());
			checkOrderInfoDTO.setOrderClose(OrderCloseEnum.ACTIVE_OPEN.getCode());
			Long unCloseOrderCount = rtuCheckOrderService.unCloseOrderCount(checkOrderInfoDTO);
			orgCheckOrderCountVO.setProcessingOrderCount(unCloseOrderCount);
			checkOrderInfoDTO.setOrderConfirm(OrderConfirmEnum.ACTIVE_CREATE.getCode());
			checkOrderInfoDTO.setOrderClose(OrderCloseEnum.ACTIVE_OPEN.getCode());
			long count = rtuCheckOrderService.unconfirmOrderCount(checkOrderInfoDTO);
			orgCheckOrderCountVO.setUnconfirmOrderCount(count);
			list.add(orgCheckOrderCountVO);
		}
		return R.data(list);
	}

	@GetMapping("/count")
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "统计表格")
	public R<Map<String, Object>> orderCount(@ApiIgnore CheckOrderInfoDTO checkOrderInfoDTO) {
		if (checkOrderInfoDTO.getAdCode() == null) {
			return R.status(false);
		}
		checkOrderInfoDTO.setOrderClose(0);
		Long orderCount = rtuCheckOrderService.orderCount(checkOrderInfoDTO);
		Long unConfirmOrderCount = rtuCheckOrderService.unconfirmOrderCount(checkOrderInfoDTO);
		Long unCloseOrderCount = rtuCheckOrderService.unCloseOrderCount(checkOrderInfoDTO);
		Map<String, Object> data = new HashMap<>();
		data.put("orderCount", orderCount);
		data.put("orderUnconfirm", unConfirmOrderCount);
		data.put("orderProcessing", unCloseOrderCount);
		checkOrderInfoDTO.setOrderConfirm(1);
		checkOrderInfoDTO.setOrderClose(1);
		Long reportOrderCount = rtuCheckOrderService.orderCount(checkOrderInfoDTO);
		data.put("reportOrderCount", reportOrderCount);
		return R.data(data);
	}
}
