/**
 * 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.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang.time.DateUtils;
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.StringUtil;
import org.springblade.modules.operation.mapper.OperationSiteEmployeeMapper;
import org.springblade.modules.operation.pojo.entity.OperationSiteEntity;
import org.springblade.modules.operation.pojo.vo.OperationEmpVo;
import org.springblade.modules.operation.service.impl.OperationSiteServiceImpl;
import org.springblade.modules.order.constant.OrderConstants;
import org.springblade.modules.order.pojo.entity.OperationOrderDispatchEntity;
import org.springblade.modules.order.pojo.entity.OperationOrderEntity;
import org.springblade.modules.order.pojo.entity.OperationOrderOperationInfoEntity;
import org.springblade.modules.order.pojo.vo.OperationOrderDispatchVO;
import org.springblade.modules.order.mapper.OperationOrderDispatchMapper;
import org.springblade.modules.order.service.IOperationOrderDispatchService;
import org.springblade.modules.order.utils.Target;
import org.springblade.modules.order.utils.WebPageFunUtils;
import org.springframework.beans.factory.annotation.Autowired;
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 java.util.Date;
import java.util.List;

/**
 * 工单平台派工表 服务实现类
 *
 * @author lzp
 * @since 2024-06-20
 */
@Service
public class OperationOrderDispatchServiceImpl extends ServiceImpl<OperationOrderDispatchMapper, OperationOrderDispatchEntity> implements IOperationOrderDispatchService {
	Logger logger= LoggerFactory.getLogger(getClass());

	@Autowired
	OperationOrderServiceImpl orderService;
	@Autowired
	OperationSiteServiceImpl siteService;
	@Autowired
	OperationOrderOperationInfoServiceImpl infoService;

	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean dispatchOrderSite(String orderId, String siteId) {
		BladeUser blUser = AuthUtil.getUser();
		Date time = new Date();
		OperationSiteEntity site = siteService.getById(siteId);
		OperationOrderEntity order = orderService.getById(orderId);
		if(!OrderConstants.ORDER_STATUS_DIS.equals(order.getStatus())){
			throw new ServiceException("当前状态发生改变，请刷新在试");
		}
	/*	if(StringUtil.isBlank(order.getServiceType())){
			throw new ServiceException("服务类型为空，请先维护服务类型");
		}*/
		order.setSiteId(siteId);
		order.setSiteName(site.getName());
		order.setUpdateName(blUser.getNickName());
		order.setDispatchTime(time);
		order.setStatus(OrderConstants.ORDER_STATUS_SERVICE);
		order.setSiteStatus(OrderConstants.DISPATCH_STATUS_YJD);
		if(order.getWarningStartDay()==null){
			order.setWarningStartDay(DateUtils.addDays(time,3));
		}
		if(!orderService.updateById(order)){
			return false;
		}
		OperationOrderDispatchEntity dis = new OperationOrderDispatchEntity();
		dis.setOrderId(orderId);
		dis.setDispatchTime(time);
		dis.setStatus(OrderConstants.DISPATCH_STATUS_DJD);
		dis.setSiteId(siteId);
		dis.setSiteName(site.getName());
		//更新过程信息
		Target ta = new Target();
		ta.setD(DateUtil.formatDateTime(time));
		ta.setP(blUser.getNickName());
		ta.setC("平台人员："+blUser.getNickName() + "派工至"+site.getName()+"服务商");
		OperationOrderOperationInfoEntity info = infoService.findInfoByOrderId(order.getId());
		if(info== null){
			info = new OperationOrderOperationInfoEntity();
		}
		ta.setT(Target.DISPATCH_ORDER);
		if(StringUtil.isBlank(info.getId())){
			info.setOrderId(order.getId());
		}
		if(StringUtil.isNotBlank(order.getSiteId())){
			info.setSiteId(order.getSiteId());
		}
		String str = WebPageFunUtils.appendOrderProcessDetail(ta, info.getProcessDetail());
		info.setProcessDetail(str);
		if(!infoService.updateById(info)){
			return false;
		}
		return save(dis);
	}

	@Override
	public OperationOrderDispatchEntity findOrderDisByOrderId(String orderId) {
		return baseMapper.findOrderDisByOrderId(orderId);
	}


	//服务商接单
	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean receiveOrder(String orderIds) {
		BladeUser user = AuthUtil.getUser();
		Date time = new Date();
		logger.info(">>>>>>>>>>>>>>>>>接单 receiveOrder:orderIds:{}", orderIds);
		String[] ids = orderIds.split(",");
		Date date = new Date();
		for (String id : ids) {
			OperationOrderEntity order = orderService.getById(id);
			if (!OrderConstants.SITE_STATUS_GET.equals(order.getSiteStatus()) || !OrderConstants.ORDER_STATUS_SERVICE.equals(order.getStatus())) {
				//该工单已不在待接单状态，无法接工单
				throw new ServiceException("该工单已不在待接单状态，无法接工单!");
			}
			order.setSiteStatus(OrderConstants.SITE_STATUS_DIS);
			order.setLatestProcess("工单已被 " + user.getNickName()+"接单");
			order.setLatestProcessTime(date);
			order.setProcessTime(date);
			order.setUpdateName(user.getNickName());

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

			OperationOrderDispatchEntity ordis = getById(id);
			if (ordis != null) {
				ordis.setStatus(OrderConstants.SITE_STATUS_DIS);
				ordis.setProcessTime(date);
				if(!saveOrUpdate(ordis)) {
					throw  new ServiceException("修改派单表失败！");
				}
			}

			Target ta = new Target();
			ta.setD(DateUtil.formatDateTime(time));
			ta.setP(user.getNickName());
			ta.setC("服务商工单已被 "+user.getNickName() + "接单 ");
			ta.setT(Target.NEW_ORDER);


			OperationOrderOperationInfoEntity info = infoService.findInfoByOrderId(order.getId());
			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;
			}
		}
		return true;
	}


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

}
