/**
 * 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.fitting.service.impl;

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.StringUtil;
import org.springblade.modules.fitting.constant.FittingConstant;
import org.springblade.modules.fitting.pojo.dto.OperationOrderMaterialDTO;
import org.springblade.modules.fitting.pojo.entity.OperationOrderMaterialEntity;
import org.springblade.modules.fitting.pojo.vo.AddOrderFittingUseVo;
import org.springblade.modules.fitting.pojo.vo.OperationOrderMaterialVO;
import org.springblade.modules.fitting.excel.OperationOrderMaterialExcel;
import org.springblade.modules.fitting.mapper.OperationOrderMaterialMapper;
import org.springblade.modules.fitting.pojo.vo.OrderUseFittingDetailVo;
import org.springblade.modules.fitting.service.IOperationOrderMaterialService;
import org.springblade.modules.material.pojo.dto.MaterialDTO;
import org.springblade.modules.material.pojo.entity.MaterialEngineerEntity;
import org.springblade.modules.material.pojo.entity.MaterialEntity;
import org.springblade.modules.material.service.impl.MaterialEngineerServiceImpl;
import org.springblade.modules.material.service.impl.MaterialOutboundServiceImpl;
import org.springblade.modules.material.service.impl.MaterialServiceImpl;
import org.springblade.modules.operation.pojo.vo.OperationSiteEmployeeVO;
import org.springblade.modules.operation.service.IOperationSiteEmployeeService;
import org.springblade.modules.operation.service.impl.OperationSiteEmployeeServiceImpl;
import org.springblade.modules.order.constant.OrderConstants;
import org.springblade.modules.order.pojo.entity.OperationOrderEntity;
import org.springblade.modules.order.service.impl.OperationOrderServiceImpl;
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.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 工单备件使用表 服务实现类
 *
 * @author BladeX
 * @since 2024-08-27
 */
@Service
public class OperationOrderMaterialServiceImpl extends ServiceImpl<OperationOrderMaterialMapper, OperationOrderMaterialEntity> implements IOperationOrderMaterialService {

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

	@Autowired
	private OperationOrderServiceImpl orderService;

	@Autowired
	private MaterialServiceImpl materialService;

	@Autowired
	private MaterialEngineerServiceImpl engineerService;

	@Autowired
	private OperationSiteEmployeeServiceImpl siteEmployeeService;

	@Autowired
	private MaterialOutboundServiceImpl materialOutboundService;

	@Override
	public IPage<OperationOrderMaterialVO> selectOperationOrderMaterialPage(IPage<OperationOrderMaterialVO> page, OperationOrderMaterialVO operationOrderMaterial) {
		return page.setRecords(baseMapper.selectOperationOrderMaterialPage(page, operationOrderMaterial));
	}


	@Override
	public List<OperationOrderMaterialExcel> exportOperationOrderMaterial(Wrapper<OperationOrderMaterialEntity> queryWrapper) {
		List<OperationOrderMaterialExcel> operationOrderMaterialList = baseMapper.exportOperationOrderMaterial(queryWrapper);
		return operationOrderMaterialList;
	}

	//获取工单使用的备件
	@Override
	public List<OperationOrderMaterialDTO> getOrderUserdFitting(String orderId) {
		List<OperationOrderMaterialDTO> useFitting=baseMapper.getOrderUserdFitting(orderId);
		return useFitting;
	}

	@Override
	public List<OperationOrderMaterialDTO> getOrderApplyFitting(String orderId) {
		List<OperationOrderMaterialDTO> applyFitting=baseMapper.getOrderApplyFitting(orderId);
		return applyFitting;
	}

	//删除使用的物料--1、工单待审核、审核驳回时，可删除使用物料；
	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean deleteUserFitting(String id) {
		BladeUser user = AuthUtil.getUser();
		OperationOrderMaterialEntity materialEntity=getById(id);
		//判断工单状态
		OperationOrderEntity orderEntity= orderService.getById(materialEntity.getOrderId());
		if(!OrderConstants.ORDER_STATUS_SERVICE.equals(orderEntity.getStatus()) && !OrderConstants.ORDER_STATUS_CALL.equals(orderEntity.getStatus())){
              throw new ServiceException("工单待审核、审核驳回时，可删除使用物料");
		}
		Date date=new Date();
		LambdaUpdateWrapper<OperationOrderMaterialEntity> updateWrapper=new LambdaUpdateWrapper<>();
		updateWrapper.eq(OperationOrderMaterialEntity::getId,id);
		updateWrapper.set(OperationOrderMaterialEntity::getStatus, FittingConstant.STATUS_DELETE);
		updateWrapper.set(OperationOrderMaterialEntity::getUpdateName,user.getNickName());
		updateWrapper.set(OperationOrderMaterialEntity::getUpdateTime,date);
		if("1".equals(materialEntity.getMaterialFrom())){  //甲供物料
			//返回库存
			MaterialEngineerEntity engineerEntity=engineerService.getEngineerStock(materialEntity.getEmpUserId(),materialEntity.getMaterialId());
			engineerEntity.setStock(engineerEntity.getStock()+materialEntity.getUserAmount());
			engineerEntity.setUpdateTime(date);
			engineerEntity.setUpdateUser(user.getUserId());
			engineerService.updateById(engineerEntity);
			MaterialEntity material=materialService.getById(materialEntity.getMaterialId());
			//生成入库记录
			materialOutboundService.saveEmpMaterialInVsOut(materialEntity,material,"1",user,FittingConstant.KEEP_FORM_ORDER_DELETE,orderEntity.getId());
		}
		return update(updateWrapper);
	}

	//保存物料使用
	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean orderFittingUse(AddOrderFittingUseVo fittingUseVo) {
		BladeUser user = AuthUtil.getUser();
		OperationOrderEntity orderEntity= orderService.getById(fittingUseVo.getOrderId());
		if(!OrderConstants.ORDER_STATUS_SERVICE.equals(orderEntity.getStatus()) && !OrderConstants.ORDER_STATUS_CALL.equals(orderEntity.getStatus())){
			throw new ServiceException("工单服务中和待审核，可以添加物料使用！");
		}
		List<OperationOrderMaterialVO> materialVOS=fittingUseVo.getUserMaterila();
		Date date=new Date();
		int i=1;
		Map<String,MaterialEngineerEntity> map=new HashMap<>();
		OperationSiteEmployeeVO employeeVO=siteEmployeeService.getSiteEmployee(orderEntity.getEmployeId());
		logger.info("...orderFittingUse  empId:{},employeeVo:{}",orderEntity.getEmployeId(),employeeVO);
		if(employeeVO==null){
			throw new ServiceException("未找到工单工程师！");
		}
		for(OperationOrderMaterialVO materialVO:materialVOS){
			OperationOrderMaterialEntity orderMaterial=new OperationOrderMaterialEntity();
			orderMaterial.setOrderId(fittingUseVo.getOrderId());
			orderMaterial.setSiteId(orderEntity.getSiteId());
			orderMaterial.setMaterialFrom(fittingUseVo.getMaterialFrom());
			MaterialDTO materialEntity = null;
			if("1".equals(fittingUseVo.getMaterialFrom())){  //物料归属 1物料甲供 2自备物料
				 if(StringUtil.isBlank(materialVO.getMaterialId())){
				 	throw new ServiceException("第"+i+"物料，是甲供物料，物料id不能为空！");
				 }
				 materialEntity=materialService.getMaterialById(materialVO.getMaterialId());
				 if(materialEntity ==null){
					 throw new ServiceException("第"+i+"物料，未找到物料信息！");
				 }
				orderMaterial.setMaterialId(materialVO.getMaterialId());
				orderMaterial.setMaterialName(materialEntity.getName());
				orderMaterial.setMaterialCode(materialEntity.getCode());
				orderMaterial.setMaterialType(materialEntity.getMaterialType());
				orderMaterial.setMaterialSpec(materialEntity.getPower());
				MaterialEngineerEntity engineerEntity;
				if(map.get(materialVO.getMaterialId())!=null){
					engineerEntity=map.get(materialVO.getMaterialId());
				}else {
					//处理物料库存
					engineerEntity=engineerService.getEngineerStock(employeeVO.getUserId().toString(),materialVO.getMaterialId());
				}
				logger.info("orderFittingUse   engineerEntity :{}",engineerEntity);
				if(engineerEntity==null || engineerEntity.getStock()<materialVO.getUserAmount()){
                      throw new ServiceException(materialEntity.getName()+"，该物料库存不足，不能使用！");
				}
				engineerEntity.setStock(engineerEntity.getStock()-materialVO.getUserAmount());
				engineerEntity.setUpdateTime(date);
				engineerEntity.setUpdateUser(user.getUserId());
				map.put(materialVO.getMaterialId(),engineerEntity);
			}else{
				if(StringUtil.isBlank(materialVO.getMaterialType())){
					throw new ServiceException("第"+i+"物料，物料类型不能为空！");
				}
				if(StringUtil.isBlank(materialVO.getMaterialSpec())){
					throw new ServiceException("第"+i+"物料，物料规格不能为空！");
				}
				orderMaterial.setMaterialName(materialVO.getMaterialName());
				orderMaterial.setMaterialCode(materialVO.getMaterialCode());
				orderMaterial.setMaterialType(materialVO.getMaterialType());
				orderMaterial.setMaterialSpec(materialVO.getMaterialSpec());
			}
			orderMaterial.setEmpUserId(employeeVO.getUserId().toString());
			orderMaterial.setMaterialFrom(fittingUseVo.getMaterialFrom());
			orderMaterial.setUserAmount(materialVO.getUserAmount());
			orderMaterial.setCreateTime(date);
			orderMaterial.setCreateBy(user.getUserId().toString());
			orderMaterial.setCreateName(user.getNickName());
			orderMaterial.setStatus(FittingConstant.STATUS_USER);
			if(!save(orderMaterial)){
				throw new ServiceException("保存工单物料使用失败！");
			}
			i++;
			if("1".equals(fittingUseVo.getMaterialFrom())){
				//生成出库记录
				materialOutboundService.saveEmpMaterialInVsOut(orderMaterial,materialEntity,"2",user,FittingConstant.KEEP_FORM_ORDER_USE,orderMaterial.getOrderId());
			}
		}
		//保存库存变动信息
		for(Map.Entry<String, MaterialEngineerEntity> e : map.entrySet()){
              MaterialEngineerEntity engineerEntity=e.getValue();
              if(!engineerService.updateById(engineerEntity)){
              	  throw new ServiceException("保存库存变动信息失败！");
			  }
		}
		return true;
	}

	@Override
	public List<OperationOrderMaterialEntity> getEmpUseFittingList(IPage<OperationOrderMaterialEntity> page ,Map<String, String> params) {
		List<OperationOrderMaterialEntity> list=baseMapper.getEmpUseFittingList(page,params);
		return list;
	}

	@Override
	public OrderUseFittingDetailVo getOrderUseFittingDetail(String id) {
		OrderUseFittingDetailVo detailVo= baseMapper.getOrderUseFittingDetail(id);
		return detailVo;
	}

	@Override
	public OrderUseFittingDetailVo getOrderCanUseFittingDetail(String materialId, String empUserId) {
		OrderUseFittingDetailVo detailVo= baseMapper.getOrderCanUseFittingDetail(materialId,empUserId);
		return detailVo;
	}


}
