/**
 * Copyright 2019 DH
 * All right reserved.
 * 项目名称: 大恒泰山系统
 * 创建日期:2022/8/22
 */
package org.springblade.modules.business.check.process.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.AllArgsConstructor;
import org.springblade.common.cache.DictBizCache;
import org.springblade.constant.BusinessConstant;
import org.springblade.constant.DictBusinessConstant;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.log.annotation.ApiLog;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.oss.model.BladeFile;
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.ConcurrentDateFormat;
import org.springblade.core.tool.utils.Func;
import org.springblade.enums.OrderStatusEnum;
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.service.IRtuCheckOrderService;
import org.springblade.modules.business.check.process.dto.OrderProcessInfoDTO;
import org.springblade.modules.business.check.process.entity.OrderProcessInfoEntity;
import org.springblade.modules.business.check.process.service.IRtuOrderProcessService;
import org.springblade.modules.business.check.process.vo.OrderProcessInfoVO;
import org.springblade.modules.business.check.process.wrapper.RtuOrderProcessWrapper;
import org.springblade.modules.resource.builder.oss.OssBuilder;
import org.springblade.modules.system.entity.DictBiz;
import org.springblade.modules.system.entity.User;
import org.springblade.modules.system.service.IUserService;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/***
 * Date:2022/8/22
 * Title: 维修任务填报管理模块
 * Description：对本文件的详细描述，原则上不能少于30字
 * @author dylan
 * @version 1.0
 * Remark：认为有必要的其他信息
 */
@RestController
@RequestMapping("galaxy-business/rtu/check/order/process")
@AllArgsConstructor
@Api(value = "工单处理管理模块", tags = "工单处理管理模块")
public class RtuOrderProcessController extends BladeController {
	private final IRtuOrderProcessService rtuOrderProcessService;
	private final IRtuCheckOrderService checkOrderService;
	private final IUserService userService;
	private final IBaseInfoDictService dictService;
	private final IDeptRegionService deptRegionService;
	private final IRtuBaseInfoService rtuBaseInfoService;
	@Resource
	private OssBuilder ossBuilder;
	/**
	 * 分页
	 */
	@GetMapping("/list")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "id", value = "工单ID", paramType = "query", dataType = "long")
	})
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "不分页", notes = "传入checkOrderInfoDTO")
	public R<List<OrderProcessInfoVO>> list(CheckOrderInfoDTO checkOrderInfoDTO) {
		List<OrderProcessInfoVO> list = rtuOrderProcessService.selectList(checkOrderInfoDTO);
		CheckOrderInfoEntity checkOrderInfoEntity = checkOrderService.getById(checkOrderInfoDTO.getId());
		for (OrderProcessInfoVO v : list) {
			v.setTaskCreateTime(checkOrderInfoEntity.getCreateTime());
			RtuOrderProcessWrapper.build().entityVO(v);
		}
		return R.data(list);
	}

	/**
	 * 多表联合查询自定义分页
	 */
	@GetMapping("/page")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "id", value = "工单ID", paramType = "query", dataType = "long")
	})
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "分页", notes = "传入checkOrderInfoDTO")
	public R<IPage<OrderProcessInfoVO>> page(CheckOrderInfoDTO checkOrderInfoDTO, Query query) {
		IPage<OrderProcessInfoVO> pages = rtuOrderProcessService.selectPage(Condition.getPage(query), checkOrderInfoDTO);
		List<OrderProcessInfoVO> list = pages.getRecords();
		for (OrderProcessInfoVO v : list) {
			RtuOrderProcessWrapper.build().entityVO(v);
		}
		return R.data(pages);
	}


	/**
	 * 查询当天填报的工单信息
	 *
	 * @return
	 */
	@GetMapping("/today/list")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "分页")
	public R<List<OrderProcessInfoVO>> todayList(@ApiIgnore OrderProcessInfoDTO processInfoDTO) {
		BladeUser user = AuthUtil.getUser();
		if (BusinessConstant.ROLE_SYS_ADMIN.equals(user.getRoleName())) {
			processInfoDTO.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())) {
			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);
			if (null == deptRegionEntity){
				return R.data(null);
			}
			processInfoDTO.setAdCode(deptRegionEntity.getAdcd());
		}

		Date date = new Date();
		String dt = Func.formatDateTime(date);
		processInfoDTO.setCreateTime(Func.parse(dt, ConcurrentDateFormat.of("yyyy-MM-dd")));
		List<OrderProcessInfoVO> list = rtuOrderProcessService.selectTodayProcessList(processInfoDTO);
		for (OrderProcessInfoVO vo : list) {
			RtuOrderProcessWrapper.build().entityVO(vo);
		}
		return R.data(list);
	}


	/**
	 * 多表联合查询自定义分页
	 */
	@GetMapping("/today/page")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "id", value = "工单ID", paramType = "query", dataType = "long")
	})
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "分页", notes = "传入checkOrderInfoDTO")
	public R<IPage<OrderProcessInfoVO>> todayPage(@ApiIgnore OrderProcessInfoDTO orderProcessInfoDTO, Query query) {
		BladeUser user = AuthUtil.getUser();
		if (BusinessConstant.ROLE_SYS_ADMIN.equals(user.getRoleName())) {
			orderProcessInfoDTO.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())) {
			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);
			orderProcessInfoDTO.setAdCode(deptRegionEntity.getAdcd());
		}

		Date date = new Date();
		String dt = Func.formatDateTime(date);
		orderProcessInfoDTO.setCreateTime(Func.parse(dt, ConcurrentDateFormat.of("yyyy-MM-dd")));

		IPage<OrderProcessInfoVO> pages = rtuOrderProcessService.selectTodayProcessPage(Condition.getPage(query), orderProcessInfoDTO);
		List<OrderProcessInfoVO> list = pages.getRecords();
		for (OrderProcessInfoVO v : list) {
			RtuOrderProcessWrapper.build().entityVO(v);
		}
		return R.data(pages);
	}


	/**
	 * 详情
	 */
	@GetMapping("/detail")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "id", value = "填报ID", paramType = "query", dataType = "long"),
	})
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入orderProcessInfoEntity")
	public R<OrderProcessInfoVO> detail(OrderProcessInfoEntity orderProcessInfoEntity) {

		OrderProcessInfoEntity detail = rtuOrderProcessService.getById(orderProcessInfoEntity.getId());

		OrderProcessInfoVO vo = RtuOrderProcessWrapper.build().entityVO(detail);
		CheckOrderInfoEntity checkOrderInfoEntity = checkOrderService.getById(vo.getOrderId());
		if (checkOrderInfoEntity.getOrderConfirmUser() != null) {
			User user = userService.getById(checkOrderInfoEntity.getOrderConfirmUser());
			vo.setOrderConfirmUserName(user.getRealName());
		}
		DictBiz biz = DictBizCache.getById(checkOrderInfoEntity.getOrderFromKey());
		vo.setOrderFromText(biz.getDictValue());
		return R.data(vo);
	}


	/**
	 * 新增
	 */
	@PostMapping("/save")
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "新增", notes = "传入orderProcessInfoEntity")
	public R save(@RequestBody OrderProcessInfoEntity orderProcessInfoEntity) {
		CheckOrderInfoEntity checkOrderInfoEntity = checkOrderService.getById(orderProcessInfoEntity.getOrderId());

		DictInfoEntity dictInfoEntity = dictService.getDict(DictBusinessConstant.ORDER_STATUS_CODE, OrderStatusEnum.STATUS_PROCESS.getCode());
		checkOrderInfoEntity.setOrderStatusKey(dictInfoEntity.getId());
		checkOrderInfoEntity.setOrderDesc(orderProcessInfoEntity.getProcessDesc());
		checkOrderService.updateOrderStatus(checkOrderInfoEntity);

		orderProcessInfoEntity.setOrderStatusKey(checkOrderInfoEntity.getOrderStatusKey());
		rtuOrderProcessService.save(orderProcessInfoEntity);
		//更新更换信息
		LambdaQueryWrapper<RtuInfoEntity> rtuWrapper = Wrappers.<RtuInfoEntity>query().lambda();
		rtuWrapper.eq(RtuInfoEntity::getIsDeleted, 0);
		rtuWrapper.eq(RtuInfoEntity::getRtuCode, checkOrderInfoEntity.getRtuCode());
		RtuInfoEntity rtuInfoEntity = rtuBaseInfoService.getOne(rtuWrapper);
		if (orderProcessInfoEntity.getRtuReplace() != null && orderProcessInfoEntity.getRtuReplace() == 1) {
			rtuInfoEntity.setRtuReplaceDate(orderProcessInfoEntity.getCreateTime());
			rtuInfoEntity.setRtuBrand(orderProcessInfoEntity.getRtuBrand());
			rtuInfoEntity.setRtuModel(orderProcessInfoEntity.getRtuModel());
		}
		if (orderProcessInfoEntity.getRainSensorReplace() != null && orderProcessInfoEntity.getRainSensorReplace() == 1) {
			rtuInfoEntity.setRainSensorReplaceDate(orderProcessInfoEntity.getCreateTime());
			rtuInfoEntity.setRainSensorBrand(orderProcessInfoEntity.getRainSensorBrand());
			rtuInfoEntity.setRainSensorModel(orderProcessInfoEntity.getRainSensorModel());
		}
		if (orderProcessInfoEntity.getWaterSensorReplace() != null && orderProcessInfoEntity.getWaterSensorReplace() == 1) {
			rtuInfoEntity.setWaterSensorReplaceDate(orderProcessInfoEntity.getCreateTime());
			rtuInfoEntity.setWaterSensorBrand(orderProcessInfoEntity.getWaterSensorBrand());
			rtuInfoEntity.setWaterSensorModel(orderProcessInfoEntity.getWaterSensorModel());
		}
		if (orderProcessInfoEntity.getGroundSensorReplace() != null && orderProcessInfoEntity.getGroundSensorReplace() == 1) {
			rtuInfoEntity.setGroundSensorReplaceDate(orderProcessInfoEntity.getCreateTime());
			rtuInfoEntity.setGroundSensorBrand(orderProcessInfoEntity.getGroundSensorBrand());
			rtuInfoEntity.setGroundSensorModel(orderProcessInfoEntity.getGroundSensorModel());
		}
		if (orderProcessInfoEntity.getBatteryReplace() != null && orderProcessInfoEntity.getBatteryReplace() == 1) {
			rtuInfoEntity.setBatteryReplaceDate(orderProcessInfoEntity.getCreateTime());
		}
		rtuBaseInfoService.updateById(rtuInfoEntity);
		return R.status(true);
	}

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

	/**
	 * 新增或修改
	 */
	@PostMapping("/submit")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "新增或修改", notes = "传入orderProcessInfoEntity")
	public R submit(@RequestBody OrderProcessInfoEntity orderProcessInfoEntity) {
		return R.status(rtuOrderProcessService.saveOrUpdate(orderProcessInfoEntity));
	}

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


	/**
	 * 维修任务-无信号上报信息列表,分页
	 */
	@GetMapping("/nonetworksignal/page")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "rtuName", value = "测站名称", paramType = "query", dataType = "string"),
		@ApiImplicitParam(name = "rtuCode", value = "测站编码", paramType = "query", dataType = "string"),
	})
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "分页", notes = "传入OrderProcessInfoDTO")
	public R<IPage<OrderProcessInfoVO>> page(OrderProcessInfoDTO orderProcessInfoDTO, Query query) {
		IPage<OrderProcessInfoVO> pages = rtuOrderProcessService.selectNoNetworkSignalPage(Condition.getPage(query), orderProcessInfoDTO);
		List<OrderProcessInfoVO> list = pages.getRecords();
		for (OrderProcessInfoVO v : list) {
			RtuOrderProcessWrapper.build().entityVO(v);
		}
		return R.data(pages);
	}

	/**
	 * 维修任务上报-无信号上报图片补交关闭
	 *
	 * @param orderProcessInfoEntity
	 * @return
	 */
	@PostMapping("/nonetworksignal/close")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "id", value = "记录ID", paramType = "query", dataType = "long"),
	})
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "图片补交关闭操作", notes = "传入实体类OrderProcessInfoEntity")
	public R noNetworkSignalPhotoSubmitClose(@RequestBody OrderProcessInfoEntity orderProcessInfoEntity) {
		if (orderProcessInfoEntity.getId() == null) {
			return R.fail("参数错误!");
		}
		OrderProcessInfoEntity entity = rtuOrderProcessService.getById(orderProcessInfoEntity.getId());
		if (null == entity) {
			return R.status(false);
		}
		entity.setPhotoSupplementSubmitStatus(1);

		rtuOrderProcessService.updateById(entity);
		return R.success("操作成功！");
	}

	@ApiLog("图片提交")
	@PostMapping(value = "/nonetworksignal/putPhoto")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "图片提交", notes = "")
	public R putFile(MultipartFile file) {
		BladeFile bladeFile = ossBuilder.template().putFile(file);
		return R.data(bladeFile);
	}

	/**
	 * 修改
	 */
	@PostMapping("/nonetworksignal/photo/update")
	@ApiOperationSupport(order = 5)
	@ApiOperation(value = "修改", notes = "传入OrderProcessInfoEntity")
	public R nonetworksignalPhotoUpdate(@RequestBody OrderProcessInfoEntity orderProcessInfoEntity) {
		OrderProcessInfoEntity entity = rtuOrderProcessService.getById(orderProcessInfoEntity.getId());
		entity.setBaseBeforePhoto1Take(orderProcessInfoEntity.getBaseBeforePhoto1Take());
		entity.setBaseBeforePhoto1Url(orderProcessInfoEntity.getBaseBeforePhoto1Url());
		entity.setBaseBeforePhoto2Take(orderProcessInfoEntity.getBaseBeforePhoto2Take());
		entity.setBaseBeforePhoto2Url(orderProcessInfoEntity.getBaseBeforePhoto2Url());
		entity.setBaseAfterPhoto1Take(orderProcessInfoEntity.getBaseAfterPhoto1Take());
		entity.setBaseAfterPhoto1Url(orderProcessInfoEntity.getBaseAfterPhoto1Url());
		entity.setBaseAfterPhoto2Take(orderProcessInfoEntity.getBaseAfterPhoto2Take());
		entity.setBaseAfterPhoto2Url(orderProcessInfoEntity.getBaseAfterPhoto2Url());
		entity.setRtuPhotoTake(orderProcessInfoEntity.getRtuPhotoTake());
		entity.setRtuPhotoUrl(orderProcessInfoEntity.getRtuPhotoUrl());
		entity.setRainSensorPhotoTake(orderProcessInfoEntity.getRainSensorPhotoTake());
		entity.setRainSensorPhotoUrl(orderProcessInfoEntity.getRainSensorPhotoUrl());
		entity.setWaterSensorPhotoTake(orderProcessInfoEntity.getWaterSensorPhotoTake());
		entity.setWaterSensorPhotoUrl(orderProcessInfoEntity.getWaterSensorPhotoUrl());
		entity.setGroundSensorPhotoTake(orderProcessInfoEntity.getGroundSensorPhotoTake());
		entity.setGroundSensorPhotoUrl(orderProcessInfoEntity.getGroundSensorPhotoUrl());
		entity.setBatteryPhotoTake(orderProcessInfoEntity.getBatteryPhotoTake());
		entity.setBatteryPhotoUrl(orderProcessInfoEntity.getBatteryPhotoUrl());
		entity.setSunPhotoTake(orderProcessInfoEntity.getSunPhotoTake());
		entity.setSunPhotoUrl(orderProcessInfoEntity.getSunPhotoUrl());
		return R.status(rtuOrderProcessService.updateById(entity));
	}
}
