/**
 * BladeX Commercial License Agreement
 * Copyright (c) 2018-2099, https://bladex.cn. All rights reserved.
 * <p>
 * Use of this software is governed by the Commercial License Agreement
 * obtained after purchasing a license from BladeX.
 * <p>
 * 1. This software is for development use only under a valid license
 * from BladeX.
 * <p>
 * 2. Redistribution of this software's source code to any third party
 * without a commercial license is strictly prohibited.
 * <p>
 * 3. Licensees may copyright their own code but cannot use segments
 * from this software for such purposes. Copyright of this software
 * remains with BladeX.
 * <p>
 * Using this software signifies agreement to this License, and the software
 * must not be used for illegal purposes.
 * <p>
 * THIS SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY. The author is
 * not liable for any claims arising from secondary or illegal development.
 * <p>
 * Author: Chill Zhuang (bladejava@qq.com)
 */
package org.springblade.modules.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.utils.DateUtil;
import org.springblade.core.tool.utils.Func;
import org.springblade.core.tool.utils.StringUtil;
import org.springblade.modules.fitting.pojo.entity.OperationOrderMaterialEntity;
import org.springblade.modules.fitting.pojo.entity.PlatformFittingApplyEntity;
import org.springblade.modules.fitting.service.impl.OperationOrderMaterialServiceImpl;
import org.springblade.modules.fitting.service.impl.PlatformFittingApplyServiceImpl;
import org.springblade.modules.nh.pojo.entity.DeviceEntity;
import org.springblade.modules.operation.mapper.OperationSiteEmployeeMapper;
import org.springblade.modules.operation.pojo.vo.OperationEmpVo;
import org.springblade.modules.order.constant.OrderConstants;
import org.springblade.modules.order.mapper.OperationOrderSiteDispatchMapper;
import org.springblade.modules.order.pojo.entity.OperationOrderEntity;
import org.springblade.modules.order.pojo.entity.OperationOrderOperationInfoEntity;
import org.springblade.modules.order.pojo.entity.OperationOrderSiteDispatchEntity;
import org.springblade.modules.order.pojo.vo.OperationOrderSiteDispatchVO;
import org.springblade.modules.order.excel.OperationOrderSiteDispatchExcel;
import org.springblade.modules.order.service.IOperationOrderSiteDispatchService;
import org.springblade.modules.order.utils.Target;
import org.springblade.modules.order.utils.WebPageFunUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.commons.util.IdUtils;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springblade.core.mp.base.BaseServiceImpl;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 服务商派工表 服务实现类
 *
 * @author hx
 * @since 2024-06-21
 */
@Service
public class OperationOrderSiteDispatchServiceImpl extends ServiceImpl<OperationOrderSiteDispatchMapper, OperationOrderSiteDispatchEntity> implements IOperationOrderSiteDispatchService {

	Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	OperationSiteEmployeeMapper employeeMapper;

	@Autowired
	OperationOrderServiceImpl orderService;

	@Autowired
	OperationOrderOperationInfoServiceImpl infoService;
	@Autowired
	PlatformFittingApplyServiceImpl applyService;

	@Autowired
	OperationOrderMaterialServiceImpl materialService;


	//服务商派工
	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean siteDispatchOrder(String orderIds, String empIds) {
		logger.info(">>>>>>>>>>>服务商派工 siteDispatchOrder orderIds:{},empId:{} ", orderIds, empIds);
		String empNames = "";  //erp那边过来的 map里面有值
		String empMobiles = "";
		BladeUser user = AuthUtil.getUser();
		if (StringUtil.isNotBlank(empIds)) {
			OperationEmpVo record = employeeMapper.findByEmpIds(empIds);
			if (record == null) {
				throw new ServiceException("服务商工程师不存在!");
			}
			empNames = record.getEmpName();
			empMobiles = record.getEmpMobile();
		}
		Date date = new Date();
		String[] ids = orderIds.split(",");
		List<OperationOrderSiteDispatchEntity> dispatches = new ArrayList<>();
		//List<OperationOrderEntity> orderList = new ArrayList<>();
		for (String id : ids) {
			OperationOrderEntity order = orderService.getById(id);
			if (!OrderConstants.ORDER_STATUS_SERVICE.equals(order.getStatus())) {
				throw new ServiceException("工单状态不支持派工操作,请刷新!");
			}
			if (!OrderConstants.SITE_STATUS_DIS.equals(order.getSiteStatus())) {   //平台可以跳过服务商接单  直接派工
				throw new ServiceException("工单状态不支持派工操作!");
			}
		/*	if(StringUtil.isBlank(order.getServiceType())){
				throw new ServiceException("服务类型为空，请先维护服务类型");
			}*/
			order.setSiteStatus(OrderConstants.SITE_STATUS_RECEIVE);
			order.setStatus(OrderConstants.ORDER_STATUS_SERVICE);
			order.setSiteDispatchTime(date);
			order.setLatestProcess(user.getNickName() + "派工给" + empNames);
			order.setLatestProcessTime(date);
			order.setEmployeId(empIds);
			order.setEmployeName(empNames);
			order.setEmployeMobile(empMobiles);

			OperationOrderSiteDispatchEntity siteDis = new OperationOrderSiteDispatchEntity();
			siteDis.setOrderId(order.getId());
			siteDis.setSiteId(order.getSiteId());
			siteDis.setEmployeId(empIds);
			siteDis.setEmployeName(empNames);
			siteDis.setDispatchTime(date);
			siteDis.setCreateTime(date);
			siteDis.setCreator(user.getNickName());
			siteDis.setStatus(OrderConstants.SITE_DISPATCH_STATUS_WAIT);
			dispatches.add(siteDis);

			//更新过程信息
			Target ta = new Target();
			ta.setD(DateUtil.formatDateTime(date));
			ta.setP(user.getNickName());
			ta.setC(user.getNickName() + "派工至" + empNames + " 工程师 ");
			ta.setT(Target.Site_DISPATCH);
			OperationOrderOperationInfoEntity info = infoService.findInfoByOrderId(order.getId());
			if(info ==null){
				info = new OperationOrderOperationInfoEntity();
			}
			if (StringUtil.isBlank(info.getId())) {
				info.setOrderId(order.getId());
			}
			String str = WebPageFunUtils.appendOrderProcessDetail(ta, info.getProcessDetail());
			info.setProcessDetail(str);
			if (!infoService.saveOrUpdate(info)) {
				return false;
			}
			Boolean flag1 = orderService.updateById(order);
			if (!flag1) {
				throw new ServiceException("修改工单表失败!");
			}
		}
		Boolean fa = saveBatch(dispatches);
		if (!fa) throw new ServiceException("保存派工失败!");
		return true;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean transferSiteOrder(String orderIds, String empIds) {
		logger.info(">>>>>>>>>>>服务商转派 siteDispatchOrder orderIds:{},empId:{} ", orderIds, empIds);
		String empNames = "";  //erp那边过来的 map里面有值
		String empMobiles = "";
		BladeUser user = AuthUtil.getUser();
		if (StringUtil.isNotBlank(empIds)) {
			OperationEmpVo record = employeeMapper.findByEmpIds(empIds);
			if (record == null) {
				throw new ServiceException("服务商工程师不存在!");
			}
			empNames = record.getEmpName();
			empMobiles = record.getEmpMobile();
		}
		Date date = new Date();
		String[] ids = orderIds.split(",");
		List<OperationOrderSiteDispatchEntity> dispatches = new ArrayList<>();
		for (String id : ids) {
			OperationOrderEntity order = orderService.getById(id);
			if (!OrderConstants.ORDER_STATUS_SERVICE.equals(order.getStatus())) {
				throw new ServiceException("工单状态不支持转派操作,请刷新!");
			}
		/*	if (!OrderConstants.SITE_STATUS_DIS.equals(order.getSiteStatus())) {   //平台可以跳过服务商接单  直接派工
				throw new ServiceException("工单状态不支持派工操作!");
			}*/
			//检查是否有未完成的物料申请
			LambdaQueryWrapper<PlatformFittingApplyEntity> wrapper = new LambdaQueryWrapper();
			wrapper.eq(PlatformFittingApplyEntity::getOrderNumber,order.getNumber()).notIn(PlatformFittingApplyEntity::getStatus, Func.toLongList("5,6"));
			List<PlatformFittingApplyEntity> applIst = applyService.list(wrapper);
			if(!CollectionUtils.isEmpty(applIst)){
				throw new ServiceException("工单有未完成的物料申请,不可转派!");
			}
			LambdaQueryWrapper<OperationOrderMaterialEntity> openwrapper = new LambdaQueryWrapper();
			openwrapper.eq(OperationOrderMaterialEntity::getOrderId,order.getNumber()).eq(OperationOrderMaterialEntity::getStatus, "0");
			List<OperationOrderMaterialEntity> aopenList = materialService.list(openwrapper);
			if(!CollectionUtils.isEmpty(aopenList)){
				throw new ServiceException("工单有使用的物料,不可转派!");
			}

			order.setSiteStatus(OrderConstants.SITE_STATUS_RECEIVE);
			order.setStatus(OrderConstants.ORDER_STATUS_SERVICE);
			order.setSiteDispatchTime(date);
			order.setLatestProcess(user.getNickName() + "派工给" + empNames);
			order.setLatestProcessTime(date);
			order.setEmployeId(empIds);
			order.setEmployeName(empNames);
			order.setEmployeMobile(empMobiles);

			UpdateWrapper<OperationOrderSiteDispatchEntity> oldDis = new UpdateWrapper<>();
			oldDis.lambda().set(OperationOrderSiteDispatchEntity::getStatus,"5").eq(OperationOrderSiteDispatchEntity::getOrderId,order.getId()).ne(OperationOrderSiteDispatchEntity::getStatus,"5");
			if(!this.update(oldDis)){
				throw new ServiceException("转派失败，工单状态不支持转派操作,请刷新!");
			}
			OperationOrderSiteDispatchEntity siteDis = new OperationOrderSiteDispatchEntity();
			siteDis.setOrderId(order.getId());
			siteDis.setSiteId(order.getSiteId());
			siteDis.setEmployeId(empIds);
			siteDis.setEmployeName(empNames);
			siteDis.setDispatchTime(date);
			siteDis.setCreateTime(date);
			siteDis.setCreator(user.getNickName());
			siteDis.setStatus(OrderConstants.SITE_DISPATCH_STATUS_WAIT);
			dispatches.add(siteDis);

			//更新过程信息
			Target ta = new Target();
			ta.setD(DateUtil.formatDateTime(date));
			ta.setP(user.getNickName());
			ta.setC(user.getNickName() + "转派至" + empNames + " 工程师 ");
			ta.setT(Target.Site_DISPATCH);
			OperationOrderOperationInfoEntity info = infoService.findInfoByOrderId(order.getId());
			if(info ==null){
				info = new OperationOrderOperationInfoEntity();
			}
			if (StringUtil.isBlank(info.getId())) {
				info.setOrderId(order.getId());
			}
			String str = WebPageFunUtils.appendOrderProcessDetail(ta, info.getProcessDetail());
			info.setProcessDetail(str);
			if (!infoService.saveOrUpdate(info)) {
				return false;
			}
			Boolean flag1 = orderService.updateById(order);
			if (!flag1) {
				throw new ServiceException("转派工单表失败!");
			}
		}
		Boolean fa = saveBatch(dispatches);
		if (!fa) throw new ServiceException("转派工单表失败!");
		return true;
	}



	//工程师接单
	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean empReceiveOrde(String orderId) {
		logger.info("empReceiveOrde  orderId:{}", orderId);
		BladeUser user = AuthUtil.getUser();
		OperationOrderEntity order = orderService.getById(orderId);
		if (!OrderConstants.SITE_STATUS_RECEIVE.equals(order.getSiteStatus())) {
			throw new ServiceException("工单状态不支持接单操作!");
		}
		Date date = new Date();
		order.setSiteStatus(OrderConstants.SITE_STATUS_SERVICE);
		order.setSiteProcessTime(date);
		order.setLatestProcess("工程师" + user.getNickName() + "接单");
		order.setLatestProcessTime(date);

		//更新过程信息
		Target ta = new Target();
		ta.setD(DateUtil.formatDateTime(date));
		ta.setP(user.getNickName());
		ta.setC(user.getNickName() + "接单 ");
		OperationOrderOperationInfoEntity info = infoService.findInfoByOrderId(order.getId());
		ta.setT(Target.ACCEPT_ORDER);
		if (StringUtil.isBlank(info.getId())) {
			info.setOrderId(order.getId());
		}
		String str = WebPageFunUtils.appendOrderProcessDetail(ta, info.getProcessDetail());
		info.setProcessDetail(str);
		if (!infoService.updateById(info)) {
			return false;
		}

		Boolean flag1 = orderService.updateById(order);
		if (!flag1) {
			throw new ServiceException("修改工单表失败!");
		}

		LambdaUpdateWrapper<OperationOrderSiteDispatchEntity> updateWrapper1 = new LambdaUpdateWrapper<>();
		updateWrapper1.eq(OperationOrderSiteDispatchEntity::getOrderId, orderId)
			.set(OperationOrderSiteDispatchEntity::getProcessTime, date)
			.set(OperationOrderSiteDispatchEntity::getStatus, OrderConstants.DISPATCH_STATUS_YJD);
		return update(updateWrapper1);
	}

	public OperationOrderSiteDispatchEntity getByOrderId(String orderId){
		LambdaQueryWrapper<OperationOrderSiteDispatchEntity> queryWrapper=new LambdaQueryWrapper<>();
		queryWrapper.eq(OperationOrderSiteDispatchEntity::getOrderId,orderId);
		queryWrapper.ne(OperationOrderSiteDispatchEntity::getStatus,OrderConstants.DISPATCH_STATUS_CANCEL);
		return getOne(queryWrapper);
	}

}
