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

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springblade.constant.BusinessConstant;
import org.springblade.constant.DictBusinessConstant;
import org.springblade.core.mp.base.BaseServiceImpl;
import org.springblade.enums.OrderCloseEnum;
import org.springblade.enums.OrderConfirmEnum;
import org.springblade.enums.OrderFromEnum;
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.region.entity.RegionInfoEntity;
import org.springblade.modules.baseinfo.region.service.IBaseRegionService;
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.mapper.RtuCheckOrderMapper;
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.process.entity.OrderProcessInfoEntity;
import org.springblade.modules.business.check.process.service.IRtuOrderProcessService;
import org.springblade.modules.business.warning.entity.RtuWarningInfoEntity;
import org.springblade.modules.system.entity.Dept;
import org.springblade.modules.system.entity.Role;
import org.springblade.modules.system.entity.User;
import org.springblade.modules.system.service.IDeptService;
import org.springblade.modules.system.service.IRoleService;
import org.springblade.modules.system.service.IUserService;
import org.springframework.stereotype.Service;

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：认为有必要的其他信息
 */
@Service
public class RtuCheckOrderServiceImpl extends BaseServiceImpl<RtuCheckOrderMapper, CheckOrderInfoEntity> implements IRtuCheckOrderService {
	@Resource
	private IBaseInfoDictService baseInfoDictService;

	@Resource
	private IRtuBaseInfoService rtuBaseInfoService;

	@Resource
	private IUserService userService;

	@Resource
	private IRtuOrderProcessService rtuOrderProcessService;

	@Resource
	private IBaseRegionService baseInfoRegionService;

	@Resource
	private IDeptRegionService deptRegionService;

	@Resource
	private IDeptService deptService;

	@Resource
	private IRoleService roleService;

	@Override
	public List<CheckOrderInfoVO> allOrders(CheckOrderInfoDTO checkOrderInfoDTO) {
		return baseMapper.allOrders(checkOrderInfoDTO);
	}

	@Override
	public IPage<CheckOrderInfoVO> selectPage(IPage<CheckOrderInfoVO> page, CheckOrderInfoDTO checkOrderInfoDTO) {
		return page.setRecords(baseMapper.selectPage(page, checkOrderInfoDTO));
	}

	@Override
	public IPage<CheckOrderInfoVO> selectWarnPage(IPage<CheckOrderInfoVO> page, CheckOrderInfoDTO checkOrderInfoDTO) {
		return page.setRecords(baseMapper.selectWarnPage(page, checkOrderInfoDTO));
	}

	@Override
	public IPage<CheckOrderInfoVO> selectMyPage(IPage<CheckOrderInfoVO> page, CheckOrderInfoDTO checkOrderInfoDTO) {
		return page.setRecords(baseMapper.selectMyPage(page, checkOrderInfoDTO));
	}

	@Override
	public List<CheckOrderInfoVO> selectTodoList(CheckOrderInfoDTO checkOrderInfoDTO) {
		return baseMapper.selectTodoList(checkOrderInfoDTO);
	}

	@Override
	public IPage<CheckOrderInfoVO> selectConfirmDelayPage(IPage<CheckOrderInfoVO> page, CheckOrderInfoDTO checkOrderInfoDTO) {
		return page.setRecords(baseMapper.selectConfirmDelayPage(page, checkOrderInfoDTO));
	}

	@Override
	public Long unconfirmOrderCount(CheckOrderInfoDTO checkOrderInfoDTO) {
		return baseMapper.unconfirmOrderCount(checkOrderInfoDTO);
	}

	@Override
	public List<CheckOrderInfoVO> unconfirmOrderList(CheckOrderInfoDTO checkOrderInfoDTO) {

		return baseMapper.unconfirmOrderList(checkOrderInfoDTO);
	}

	@Override
	public boolean updateOrderStatus(CheckOrderInfoEntity orderInfoEntity) {

		LambdaUpdateWrapper<CheckOrderInfoEntity> updateWrapper = Wrappers.<CheckOrderInfoEntity>update().lambda();
		updateWrapper.eq(CheckOrderInfoEntity::getId, orderInfoEntity.getId());
		updateWrapper.set(CheckOrderInfoEntity::getOrderStatusKey, orderInfoEntity.getOrderStatusKey());
		updateWrapper.set(CheckOrderInfoEntity::getOrderDesc, orderInfoEntity.getOrderDesc());
		updateWrapper.set(CheckOrderInfoEntity::getUpdateTime, new Date());
		this.update(updateWrapper);

		return false;
	}

	@Override
	public List<CheckOrderCountVO> orderReportCount(CheckOrderInfoDTO checkOrderInfoDTO) {
		return baseMapper.orderReportCount(checkOrderInfoDTO);
	}

	@Override
	public Long orderCount(CheckOrderInfoDTO checkOrderInfoDTO) {
		return baseMapper.orderCount(checkOrderInfoDTO);
	}

	@Override
	public Long unCloseOrderCount(CheckOrderInfoDTO checkOrderInfoDTO) {
		return baseMapper.unCloseOrderCount(checkOrderInfoDTO);
	}

	@Override
	public boolean closeOrder(CheckOrderInfoDTO checkOrderInfoDTO) {
		LambdaQueryWrapper<CheckOrderInfoEntity> wrapper = Wrappers.<CheckOrderInfoEntity>query().lambda();
		wrapper.eq(CheckOrderInfoEntity::getIsDeleted, 0);
		wrapper.eq(CheckOrderInfoEntity::getRtuCode, checkOrderInfoDTO.getRtuCode());
		wrapper.eq(CheckOrderInfoEntity::getOrderClose, OrderCloseEnum.ACTIVE_OPEN.getCode());
		CheckOrderInfoEntity checkOrderInfoEntity = this.getOne(wrapper);
		if (null != checkOrderInfoEntity) {
			DictInfoEntity dictInfoEntity = baseInfoDictService.getDict(DictBusinessConstant.ORDER_STATUS_CODE, OrderStatusEnum.STATUS_CLOSE.getCode());
			//更新工单状态
			checkOrderInfoEntity.setOrderStatusKey(dictInfoEntity.getId());
			checkOrderInfoEntity.setOrderClose(OrderCloseEnum.ACTIVE_CLOSE.getCode());
			checkOrderInfoEntity.setOrderConfirm(OrderConfirmEnum.ACTIVE_CONFIRM.getCode());
			checkOrderInfoEntity.setUpdateUser(BusinessConstant.SYS_ADMIN_ID);
			checkOrderInfoEntity.setUpdateTime(new Date());
			this.updateById(checkOrderInfoEntity);
			//增加工单处理关闭记
			OrderProcessInfoEntity processInfoEntity = new OrderProcessInfoEntity();
			processInfoEntity.setProcessDesc("由系统自动关闭维修任务");
			processInfoEntity.setOrderId(checkOrderInfoEntity.getId());
			processInfoEntity.setOrderStatusKey(dictInfoEntity.getId());
			processInfoEntity.setCreateUser(BusinessConstant.SYS_ADMIN_ID);
			processInfoEntity.setUpdateUser(BusinessConstant.SYS_ADMIN_ID);
			processInfoEntity.setUpdateTime(new Date());
			processInfoEntity.setCreateTime(new Date());
			rtuOrderProcessService.save(processInfoEntity);
		}
		return true;
	}

	@Override
	public boolean createOrUpdateOrder(RtuWarningInfoEntity rtuWarningInfoEntity) {
		DictInfoEntity dictInfoEntity = baseInfoDictService.getDict(DictBusinessConstant.ORDER_STATUS_CODE, OrderStatusEnum.STATUS_CREATE.getCode());
		DictInfoEntity fromdict = baseInfoDictService.getDict(DictBusinessConstant.ORDER_FROM_CODE, OrderFromEnum.FROM_WARNING.getCode());
		//查询是否已经创建工单
		LambdaQueryWrapper<CheckOrderInfoEntity> wrapper = Wrappers.<CheckOrderInfoEntity>query().lambda();
		wrapper.eq(CheckOrderInfoEntity::getIsDeleted, 0);
		wrapper.eq(CheckOrderInfoEntity::getRtuCode, rtuWarningInfoEntity.getRtuCode());
		wrapper.eq(CheckOrderInfoEntity::getOrderClose, OrderCloseEnum.ACTIVE_OPEN.getCode());
		List<CheckOrderInfoEntity> checkOrderInfoList = this.list(wrapper);
		if (null == checkOrderInfoList || checkOrderInfoList.size() == 0) {
			//创建工单
			CheckOrderInfoEntity checkOrderInfoEntity = new CheckOrderInfoEntity();
			checkOrderInfoEntity.setOrderStatusKey(dictInfoEntity.getId());
			checkOrderInfoEntity.setOrderFromKey(fromdict.getId());
			checkOrderInfoEntity.setOrderDesc(rtuWarningInfoEntity.getWarningDesc());
			checkOrderInfoEntity.setWarnId(rtuWarningInfoEntity.getId());
			checkOrderInfoEntity.setRtuCode(rtuWarningInfoEntity.getRtuCode());
			checkOrderInfoEntity.setOrderClose(OrderCloseEnum.ACTIVE_OPEN.getCode());
			checkOrderInfoEntity.setOrderConfirm(OrderConfirmEnum.ACTIVE_CREATE.getCode());
			LambdaQueryWrapper<RtuInfoEntity> rtuwrapper = Wrappers.<RtuInfoEntity>query().lambda();
			rtuwrapper.eq(RtuInfoEntity::getIsDeleted, 0);
			rtuwrapper.eq(RtuInfoEntity::getRtuCode, rtuWarningInfoEntity.getRtuCode());
			RtuInfoEntity rtuInfoEntity = rtuBaseInfoService.getOne(rtuwrapper);
			LambdaQueryWrapper<RegionInfoEntity> regionWrapper = Wrappers.<RegionInfoEntity>query().lambda();
			regionWrapper.eq(RegionInfoEntity::getIsDeleted, 0);
			regionWrapper.eq(RegionInfoEntity::getAdcd, rtuInfoEntity.getAdCode());
			RegionInfoEntity regionInfoEntity = baseInfoRegionService.getOne(regionWrapper);
			if (regionInfoEntity != null) {
				String ancestors = regionInfoEntity.getAncestors();
				if (null != ancestors && ancestors.length() > 0) {
					String[] ancestorsList = ancestors.split(",");
					String adCode;
					if (ancestorsList.length >= 3) {
						adCode = ancestorsList[2];
					} else {
						adCode = regionInfoEntity.getAdcd();
					}
					if (null != adCode) {
						LambdaQueryWrapper<DeptRegionEntity> drwrapper = Wrappers.<DeptRegionEntity>query().lambda();
						drwrapper.eq(DeptRegionEntity::getIsDeleted, 0);
						drwrapper.eq(DeptRegionEntity::getAdcd, adCode);
						List<DeptRegionEntity> deptRegionEntities = deptRegionService.list(drwrapper);
						if (null != deptRegionEntities && deptRegionEntities.size() > 0) {
							String manageCompany = "";
							for (DeptRegionEntity deptRegionEntity : deptRegionEntities) {
								Dept dept = deptService.getById(deptRegionEntity.getDeptId());
								if (null != dept) {
									if (manageCompany.length() > 0) {
										manageCompany += " / ";
									}
									manageCompany += dept.getDeptName();
									//查找运维公司负责人
									LambdaQueryWrapper<User> userLambdaQueryWrapper = Wrappers.<User>query().lambda();
									userLambdaQueryWrapper.eq(User::getIsDeleted, 0);
									userLambdaQueryWrapper.eq(User::getDeptId, dept.getId());
									List<User> userList = userService.list(userLambdaQueryWrapper);
									for (User u : userList) {
										Role role = roleService.getById(u.getRoleId());
										if (BusinessConstant.ROLE_COMPANY_ADMIN.equals(role.getRoleAlias())) {
											checkOrderInfoEntity.setContactPhone(u.getPhone());
											checkOrderInfoEntity.setContactUser(u.getId());
											break;
										}
									}
								}
							}
						}
					}
				}
			}
			checkOrderInfoEntity.setUpdateUser(BusinessConstant.SYS_ADMIN_ID);
			checkOrderInfoEntity.setCreateUser(BusinessConstant.SYS_ADMIN_ID);
			checkOrderInfoEntity.setUpdateTime(new Date());
			checkOrderInfoEntity.setCreateTime(new Date());
			this.save(checkOrderInfoEntity);
			//增加工单处理创建记录
			OrderProcessInfoEntity processInfoEntity = new OrderProcessInfoEntity();
			processInfoEntity.setOrderId(checkOrderInfoEntity.getId());
			processInfoEntity.setOrderStatusKey(dictInfoEntity.getId());
			processInfoEntity.setProcessDesc(checkOrderInfoEntity.getOrderDesc());
			processInfoEntity.setUpdateUser(BusinessConstant.SYS_ADMIN_ID);
			processInfoEntity.setCreateUser(BusinessConstant.SYS_ADMIN_ID);
			processInfoEntity.setUpdateTime(new Date());
			processInfoEntity.setCreateTime(new Date());
			rtuOrderProcessService.save(processInfoEntity);
		}
		return true;
	}
}
