/**
 * 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.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.api.R;
import org.springblade.core.tool.utils.StringUtil;
import org.springblade.modules.fitting.constant.FittingConstant;
import org.springblade.modules.fitting.pojo.dto.BhMaterialDTO;
import org.springblade.modules.fitting.pojo.dto.ApplyDto;
import org.springblade.modules.fitting.pojo.entity.PlatformFittingApplyEntity;
import org.springblade.modules.fitting.pojo.vo.*;
import org.springblade.modules.fitting.excel.PlatformFittingApplyExcel;
import org.springblade.modules.fitting.mapper.PlatformFittingApplyMapper;
import org.springblade.modules.fitting.service.IPlatformFittingApplyService;
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.pojo.entity.MaterialOperationEntity;
import org.springblade.modules.material.service.IMaterialService;
import org.springblade.modules.material.service.impl.*;
import org.springblade.modules.material.pojo.entity.MaterialEntity;
import org.springblade.modules.material.service.impl.MaterialServiceImpl;
import org.springblade.modules.operation.mapper.OperationSiteEmployeeMapper;
import org.springblade.modules.operation.pojo.entity.OperationSiteEmployeeEntity;
import org.springblade.modules.operation.pojo.entity.OperationSiteEntity;
import org.springblade.modules.operation.pojo.vo.EmpAuthVo;
import org.springblade.modules.operation.service.impl.OperationSiteServiceImpl;
import org.springblade.modules.order.constant.OrderConstants;
import org.springblade.modules.order.mapper.OperationOrderMapper;
import org.springblade.modules.order.pojo.entity.OperationOrderEntity;
import org.springblade.modules.order.service.impl.OperationOrderServiceImpl;
import org.springblade.modules.order.utils.PlantformUtils;
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.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 服务商向平台备件申请领用记录表 服务实现类
 *
 * @author lzp
 * @since 2024-08-24
 */
@Service
public class PlatformFittingApplyServiceImpl extends ServiceImpl<PlatformFittingApplyMapper, PlatformFittingApplyEntity> implements IPlatformFittingApplyService {

	Logger logger= LoggerFactory.getLogger(getClass());
	@Autowired
	PlatformFittingApplyMsgServiceImpl msgService;

	@Autowired
	OperationSiteServiceImpl siteService;

	@Autowired
	OperationSiteEmployeeMapper employeeMapper;

	@Autowired
	MaterialServiceImpl materialService;

	@Autowired
	OperationOrderMapper operationOrderMapper;

	@Autowired
	MaterialOutboundServiceImpl outboundService;

	@Autowired
	MaterialOperationServiceImpl operationService;

	@Autowired
	MaterialEngineerServiceImpl engineerService;

	@Override
	public FittingApplyDetailVo getFittingApplyDetailById(String id) {
		FittingApplyDetailVo vo= baseMapper.getFittingApplyDetailById(id);
		//计算物料的当前库存
		MaterialStockVo stock;
		if("1".equals(vo.getApplicantType())){  //1.工程师
            stock= baseMapper.getEmpMaterialStock(vo.getApplicantId(),vo.getFittingId());
		}else{  //运营商
            stock= baseMapper.getOperationStock(vo.getSiteId(),vo.getFittingId());
		}
		if(stock==null){
			vo.setCurrentStock(0);
		}else{
			vo.setCurrentStock(stock.getStock());
		}
		return vo;
	}

	@Override
	public List<String> getMaterialSpecList(String materialType) {
		return baseMapper.getMaterialSpecList(materialType);
	}

	@Override
	public IPage<PlatformFittingApplyEntity> selectPlatformFittingApplyPage(IPage<PlatformFittingApplyEntity> page, PlatformFittingApplyVO platformFittingApply) {
		BladeUser user = AuthUtil.getUser();
		//3.服务商 4.平台员工 5.服务商人员
		if ("3".equals(user.getDeptId())) {  //服务商
			OperationSiteEntity site = siteService.findSiteByUserId(user.getUserId());
			platformFittingApply.setSiteId(site.getId());
		} else if ("5".equals(user.getDeptId())) {  //服务商人员
			EmpAuthVo authVo=employeeMapper.findEmpAuthByUserId(user.getUserId());
			if(authVo!=null){
				platformFittingApply.setSiteId(authVo.getSiteId());
			}
		}else if("6".equals(user.getDeptId())){
			platformFittingApply.setApplicantId(user.getUserId().toString());
		}

		return page.setRecords(baseMapper.selectPlatformFittingApplyPage(page, platformFittingApply));
	}


	@Override
	public List<PlatformFittingApplyExcel> exportPlatformFittingApply(Wrapper<PlatformFittingApplyEntity> queryWrapper) {
		List<PlatformFittingApplyExcel> platformFittingApplyList = baseMapper.exportPlatformFittingApply(queryWrapper);
		return platformFittingApplyList;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean toExamine(String id, String remarks, String type,String examineType) {
		BladeUser user = AuthUtil.getUser();
		PlatformFittingApplyEntity entity = getById(id);
		//申请状态：0.待运营商审核  1.待一级审核 2.待二级审核 3.待出库 4.待收件 5.已完成 6.申请已取消 7.审核驳回  默认0
		String mens = "";
		if(FittingConstant.EXAMINE_ONE.equals(type)){
			//一级审核
			if(!FittingConstant.STATUS_APPLY_ONE.equals(entity.getStatus())){
				throw  new ServiceException("单据状态发生改变，请刷新再试");
			}
			if(FittingConstant.EXAMINE_TYPE_ONE.equals(examineType)){
				entity.setStatus(FittingConstant.STATUS_APPLY_TWO);
				mens = "一级审核通过";
			}else{
				entity.setStatus(FittingConstant.STATUS_APPLY_BACK);
				mens = "一级审核驳回";
			}
			entity.setRefuseReason(remarks);
			entity.setAuditorOne(user.getNickName());
			entity.setConfirmTime(new Date());
		}else if(FittingConstant.EXAMINE_TWO.equals(type)){
			//二级审核
			if(!FittingConstant.STATUS_APPLY_TWO.equals(entity.getStatus())){
				throw  new ServiceException("单据状态发生改变，请刷新再试");
			}
			if(FittingConstant.EXAMINE_TYPE_ONE.equals(examineType)){
				entity.setStatus(FittingConstant.STATUS_APPLY_THREE);
				mens = "二级审核通过";
			}else{
				entity.setStatus(FittingConstant.STATUS_APPLY_BACK);
				mens = "二级审核驳回";
			}
			entity.setRefuseReasonTwo(remarks);
			entity.setAuditorTwo(user.getNickName());
			entity.setConfirmTimeTwo(new Date());

		}

		msgService.saveMsg(entity.getId(),entity.getSiteId(),mens,user.getNickName());
		return updateById(entity);
	}

	//新增物料申请
	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean saveFittingApply(AddFittingApplyVo addFittingApplyVo) {
		logger.info(">>>>>>>>>>>>>saveFittingApply  addFittingApplyVo:{},code:{},type:{}",addFittingApplyVo.getMaterialSpec(),addFittingApplyVo.getMaterialCode(),addFittingApplyVo.getFittingVersion() );
		BladeUser user = AuthUtil.getUser();
		PlatformFittingApplyEntity entity =new PlatformFittingApplyEntity();
		logger.info(".....saveFittingApply   departId:{}",user.getDeptId());
		OperationSiteEntity site=null;
		if("3".equals(user.getDeptId()) || "5".equals(user.getDeptId())){   //运营商、运营商员工  申请的时候，必须输入物料代码，物料名称
			if("3".equals(user.getDeptId())){
				site = siteService.findSiteByUserId(user.getUserId());
			}else {
				OperationSiteEmployeeEntity emp = employeeMapper.findByuserId(user.getUserId());
				site = siteService.getById(emp.getSiteId());
			}
			if(StringUtil.isBlank(addFittingApplyVo.getEmpId())){
				throw new ServiceException("工程师不能为空！");
			}
			entity.setSiteId(site.getId());
			entity.setSiteName(site.getName());
			OperationSiteEmployeeEntity emp = employeeMapper.selectById(addFittingApplyVo.getEmpId());
			entity.setApplicantId(emp.getUserId().toString());
			entity.setApplicantName(emp.getName());
			entity.setSubmitType("2");

		}else if("6".equals(user.getDeptId())){//工程师
			OperationSiteEmployeeEntity emp = employeeMapper.findByuserId(user.getUserId());
			site = siteService.getById(emp.getSiteId());
			entity.setSiteId(site.getId());
			entity.setSiteName(site.getName());
			entity.setApplicantId(user.getUserId().toString());
			entity.setApplicantName(user.getNickName());
			entity.setSubmitType("1");
		}
		if(StringUtil.isBlank(addFittingApplyVo.getOrderId())){  //没有缴纳保证金的，只有关联工单可以申请物料，不关联工单不可以申请物料
			if(site!=null && "2".equals(site.getPayTheDeposit())){  //未缴纳保证金
				throw new ServiceException("运营商未缴纳保证金，不能申请物料！");
			}
		}
		if(StringUtil.isNotBlank(addFittingApplyVo.getMaterialCode())){
			MaterialDTO materialEntity=materialService.getMaterialDetailByCode(addFittingApplyVo.getMaterialCode());
			if(materialEntity==null){
				throw new ServiceException("没有匹配到该 "+addFittingApplyVo.getMaterialCode()+" 物料编码的物料！");
			}
			entity.setFittingId(materialEntity.getId().toString());
			entity.setFittingCode(materialEntity.getCode());
			entity.setFittingVersion(materialEntity.getMaterialType());
			entity.setFittingPower(materialEntity.getPower());
			entity.setFittingName(materialEntity.getName());
			entity.setFittingBrand(materialEntity.getBrand());
			entity.setFittingUnit(materialEntity.getUnit());
			entity.setCustomerPrice(BigDecimal.valueOf(materialEntity.getRetailPrice()));
		}else{
			entity.setFittingName(addFittingApplyVo.getMaterialName());
			entity.setFittingVersion(addFittingApplyVo.getFittingVersion());
			entity.setFittingPower(addFittingApplyVo.getMaterialSpec());
		}
		if(StringUtil.isNotBlank(addFittingApplyVo.getOrderId())){
			OperationOrderEntity order = operationOrderMapper.getOrderDetail(addFittingApplyVo.getOrderId());
			entity.setOrderNumber(order.getNumber());
			entity.setPowerStationCode(order.getPowerStationCode());
			entity.setEntryId(order.getEntryId());
			entity.setCustomerName(order.getCustomerName());
		}
		entity.setApplicantType("1");
		String number = PlantformUtils.getFittingApplyNumber();
		entity.setNumber(number);
        entity.setApplyMarks(addFittingApplyVo.getApplyMarks());
        entity.setApplyNum(addFittingApplyVo.getApplyNum());
        entity.setCreateTime(new Date());
		entity.setStatus(FittingConstant.STATUS_APPLY_ZERO);
		entity.setCreator(user.getNickName());

		if (!save(entity)) {
			throw new ServiceException("保存物料申请失败！");
		}
		msgService.saveMsg(entity.getId(),entity.getSiteId(),"新增物料申请",user.getNickName());
		return true;
	}

	//编辑物料申请
	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean editFittingApply(AddFittingApplyVo addFittingApplyVo) {
		logger.info(">>>>>>>>>>>>>editFittingApply id:{}  addFittingApplyVo:{},code:{},type:{}",addFittingApplyVo.getId(),addFittingApplyVo.getMaterialSpec(),addFittingApplyVo.getMaterialCode(),addFittingApplyVo.getFittingVersion() );
		BladeUser user = AuthUtil.getUser();
		PlatformFittingApplyEntity entity = getById(addFittingApplyVo.getId());
		if(!FittingConstant.STATUS_APPLY_BACK.equals(entity.getStatus())){
			throw new ServiceException("物料申请的状态不支持编辑操作！");
		}
		if(StringUtil.isNotBlank(addFittingApplyVo.getMaterialCode())){
			MaterialEntity materialEntity=materialService.getByMaterialCode(addFittingApplyVo.getMaterialCode());
			if(materialEntity==null){
				throw new ServiceException("没有匹配到该 "+addFittingApplyVo.getMaterialCode()+" 物料编码的物料！");
			}
			entity.setFittingId(materialEntity.getId().toString());
			entity.setFittingCode(materialEntity.getCode());
			entity.setFittingName(materialEntity.getName());
			entity.setFittingBrand(materialEntity.getBrand());
			entity.setFittingUnit(materialEntity.getUnit());
			entity.setCustomerPrice(BigDecimal.valueOf(materialEntity.getRetailPrice()));
		}else{
			entity.setFittingName(addFittingApplyVo.getMaterialName());
			entity.setFittingVersion(addFittingApplyVo.getFittingVersion());
			entity.setFittingPower(addFittingApplyVo.getMaterialSpec());
		}
		entity.setFittingVersion(addFittingApplyVo.getFittingVersion());
		entity.setFittingPower(addFittingApplyVo.getMaterialSpec());
		entity.setStatus(FittingConstant.STATUS_APPLY_ZERO);

		entity.setApplyMarks(addFittingApplyVo.getApplyMarks());
		entity.setApplyNum(addFittingApplyVo.getApplyNum());
		entity.setUpdateName(user.getNickName());
		entity.setUpdateTime(new Date());
		msgService.saveMsg(entity.getId(),entity.getSiteId(),"编辑物料申请",user.getNickName());
		return updateById(entity);
	}

	//备货申请
	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean fittingBh(AddBhVo addBhVo) {
		List<OperaAddFittingBatchVo> addFittingApplyVos=addBhVo.getFittingApplyVos();
		BladeUser user = AuthUtil.getUser();
		OperationSiteEntity site;
		if("3".equals(user.getDeptId())){
			site = siteService.findSiteByUserId(user.getUserId());
		}else {
			OperationSiteEmployeeEntity emp = employeeMapper.findByuserId(user.getUserId());
			site = siteService.getById(emp.getSiteId());
		}
		if("2".equals(site.getPayTheDeposit())){  //未缴纳保证金
			throw new ServiceException("运营商未缴纳保证金，不能为自己申请物料！");
		}
		for(OperaAddFittingBatchVo applyVo:addFittingApplyVos){
			PlatformFittingApplyEntity entity =new PlatformFittingApplyEntity();
			entity.setSiteId(site.getId());
			entity.setSiteName(site.getName());
			entity.setApplicantId(user.getUserId().toString());
			entity.setApplicantName(user.getNickName());
			entity.setApplicantType("2");
			entity.setApplyMarks(applyVo.getApplyMarks());
			//根据物料代码 匹配物料信息库里面的物料
			MaterialDTO materialEntity=materialService.getMaterialById(applyVo.getMaterialId());

			entity.setFittingId(materialEntity.getId().toString());
			entity.setFittingCode(materialEntity.getCode());
			entity.setFittingVersion(materialEntity.getMaterialType());
			entity.setFittingName(materialEntity.getName());
			entity.setFittingPower(materialEntity.getPower());
			entity.setFittingBrand(materialEntity.getBrand());
			entity.setFittingUnit(materialEntity.getUnit());
			entity.setApplyNum(applyVo.getApplyNum());
			entity.setCustomerPrice(BigDecimal.valueOf(materialEntity.getRetailPrice()));
			entity.setSubmitType("2");
			entity.setStatus(FittingConstant.STATUS_APPLY_ZERO);
			entity.setCreateTime(new Date());
            entity.setCreator(user.getNickName());
			if (!save(entity)) {
				throw new ServiceException("保存物料申请失败！");
			}
			msgService.saveMsg(entity.getId(),entity.getSiteId(),"新增备货申请",user.getNickName());
		}
		return true;
	}

	//编辑备货申请
	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean editFittingBh(OperaAddFittingBatchVo batchVo) {
		BladeUser user = AuthUtil.getUser();
		PlatformFittingApplyEntity entity = getById(batchVo.getApplyId());
		if(!FittingConstant.STATUS_APPLY_BACK.equals(entity.getStatus())){
			throw  new ServiceException("单据状态发生改变，请刷新再试");
		}
		entity.setApplyNum(batchVo.getApplyNum());
		entity.setUpdateName(user.getNickName());
		entity.setUpdateTime(new Date());
		entity.setStatus(FittingConstant.STATUS_APPLY_ZERO);
		msgService.saveMsg(entity.getId(),entity.getSiteId(),"编辑备货申请", user.getNickName());
		return updateById(entity);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean siteToExamine(SiteToExamineVo vo) {
		PlatformFittingApplyEntity entity = getById(vo.getId());
		if(!FittingConstant.STATUS_APPLY_ZERO.equals(entity.getStatus())){
			throw  new ServiceException("单据状态发生改变，请刷新再试");
		}
		BladeUser user = AuthUtil.getUser();

		String message = "";
		entity.setAuditor(user.getNickName());
		entity.setAuditorId(user.getUserId().toString());
		entity.setUpdateName(user.getNickName());
		entity.setUpdateTime(new Date());
		entity.setConfirmSiteTime(new Date());
		entity.setFactoryMarks(vo.getFactoryMarks());
		if(FittingConstant.EXAMINE_TYPE_ONE.equals(vo.getExamineType())) {
			if(StringUtil.isBlank(vo.getFittingId())){
				throw new ServiceException("物料编码不能为空！");
			}
			MaterialDTO materialEntity=materialService.getMaterialDetailByCode(vo.getFittingCode());
			if(materialEntity==null){
				throw new ServiceException("没有匹配到该 "+vo.getFittingCode()+" 物料编码的物料！");
			}
			entity.setFittingId(materialEntity.getId().toString());
			entity.setFittingCode(vo.getFittingCode());
			entity.setFittingName(materialEntity.getName());
			entity.setIsPlatform(vo.getIsPlatform());
			entity.setFittingBrand(materialEntity.getBrand());
			entity.setFittingUnit(materialEntity.getUnit());
			if (FittingConstant.IS_PLATFORM_ONE.equals(vo.getIsPlatform())) {
				entity.setStatus(FittingConstant.STATUS_APPLY_ONE);
			} else {
				entity.setStatus(FittingConstant.STATUS_APPLY_ENGHT);
			}
			message = "审核通过";
		}else{
			message = "审核驳回";
			entity.setStatus(FittingConstant.STATUS_APPLY_BACK);
		}
		msgService.saveMsg(entity.getId(),entity.getSiteId(),message, user.getNickName());
		return updateById(entity);
	}


	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean sendOutGoods(Map<String, Object> maps) {
		PlatformFittingApplyEntity entity = getById(maps.get("id").toString());
		BladeUser user = AuthUtil.getUser();
		entity.setLogisticsNames(maps.get("name").toString());
		entity.setLogisticsNumber(maps.get("code").toString());
		entity.setStatus(FittingConstant.STATUS_APPLY_FOUR);
		entity.setConfirmor(user.getNickName());
		entity.setConfirmorId(user.getUserId().toString());
		MaterialEntity materialEntity=materialService.getByMaterialCode(entity.getFittingCode());
		if(materialEntity==null){
			throw new ServiceException("没有匹配到该 "+entity.getFittingCode()+" 物料编码的物料！");
		}
		if(materialEntity.getStock()< entity.getApplyNum()){
			throw new ServiceException(entity.getFittingName()+" 物料库存不足！");
		}
		materialEntity.setStock(materialEntity.getStock()-entity.getApplyNum());
		materialEntity.setFreezeAmount(materialEntity.getFreezeAmount()+ entity.getApplyNum());
		materialService.updateById(materialEntity);
		return updateById(entity);
	}


	//申请待审核以及审核驳回时，可删除物料申请；
	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean deleteApplyFitting(String id) {
		logger.info("deleteApplyFitting id:{}",id);
		BladeUser user = AuthUtil.getUser();
		PlatformFittingApplyEntity entity = getById(id);
		if(!FittingConstant.STATUS_APPLY_ZERO.equals(entity.getStatus()) && !FittingConstant.STATUS_APPLY_BACK.equals(entity.getStatus()) ){
               throw new ServiceException("物料申请待审核及审核驳回时，才可删除物料申请；");
		}
		entity.setStatus(FittingConstant.STATUS_APPLY_SIX);
		entity.setUpdateName(user.getNickName());
		entity.setUpdateTime(new Date());
		msgService.saveMsg(entity.getId(),entity.getSiteId(),"删除物料申请",user.getNickName());
		return updateById(entity);
	}

	//备货申请时  根据物料名称 或者代码 获取物料信息
	@Override
	public List<BhMaterialDTO> getMaterialListByCodeOrName(ChooseMaterialListVo conditonVo) {
		BladeUser user = AuthUtil.getUser();
		OperationSiteEntity site;
		if("3".equals(user.getDeptId())){
			site = siteService.findSiteByUserId(user.getUserId());
		}else {
			OperationSiteEmployeeEntity emp = employeeMapper.findByuserId(user.getUserId());
			site = siteService.getById(emp.getSiteId());
		}
		if(site!=null){
			conditonVo.setSiteId(site.getId());
		}
		List<BhMaterialDTO> list=baseMapper.getMaterialListByCodeOrName(conditonVo);
		return list;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean siteSignFor(String id) {
		PlatformFittingApplyEntity entity = getById(id);
		if(!FittingConstant.STATUS_APPLY_FOUR.equals(entity.getStatus())){
			throw  new ServiceException("单据状态发生改变，请刷新再试");
		}
		//applicant_type 申请类型：1.工程师申请 2.运维商备货申请
		if(FittingConstant.EXAMINE_ONE.equals(entity.getApplicantType())){
				entity.setStatus(FittingConstant.STATUS_APPLY_ENGHT);
		}else{
			entity.setStatus(FittingConstant.STATUS_APPLY_FIVE);
		}
		BladeUser user = AuthUtil.getUser();
		entity.setSendTime(new Date());
		entity.setConfirmStorageId(user.getUserId().toString());
		entity.setConfirmStorage(user.getNickName());
		entity.setEndTime(new Date());
		MaterialEntity materialEntity=materialService.getByMaterialCode(entity.getFittingCode());
		materialEntity.setFreezeAmount(materialEntity.getFreezeAmount()-entity.getApplyNum());
		if(materialEntity.getFreezeAmount()<0){
			throw  new ServiceException("物料冻结库存数量不足！");
		}
		OperationSiteEntity site = siteService.getById(entity.getSiteId());

		materialService.updateById(materialEntity);
		//生成平台出库记录
		outboundService.saveMaterialOutbound(entity,materialEntity,"2","0",user,"3","平台",FittingConstant.KEEP_FORM_OUT);
		//运维商添加库存
		MaterialOperationEntity siteMater = operationService.findByMateId(entity.getFittingId(),entity.getSiteId());
		if(siteMater ==null){
				siteMater = new MaterialOperationEntity();
				siteMater.setMaterialId(materialEntity.getId());
				siteMater.setCompanyId(entity.getSiteId());
				siteMater.setOperationId(entity.getSiteId());
				siteMater.setOperationName(entity.getSiteName());
			siteMater.setCode(materialEntity.getCode());
			siteMater.setName(materialEntity.getName());
			siteMater.setType(materialEntity.getType());
			siteMater.setModel(materialEntity.getModel());
			siteMater.setPower(materialEntity.getPower());
			siteMater.setRetailPrice(materialEntity.getRetailPrice());
			siteMater.setDescription(materialEntity.getDescription());
			siteMater.setBrand(materialEntity.getBrand());
			siteMater.setStock(entity.getApplyNum());
			siteMater.setCreateUser(user.getUserId());
			siteMater.setCreateTime(new Date());
			siteMater.setIsDeleted(0);
			siteMater.setFreezeAmount(0);
		}else{
			siteMater.setStock(siteMater.getStock()+entity.getApplyNum());
		}
		if(!updateById(entity)){
			throw new ServiceException("保存申请信息失败！");
		}
		//生成运维上入库记录
		outboundService.saveMaterialOutbound(entity,materialEntity,"1",site.getId(),user,"2",site.getName(),FittingConstant.KEEP_FORM_IN);
		msgService.saveMsg(entity.getId(),site.getId(),"签收", user.getNickName());
		return operationService.saveOrUpdate(siteMater);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean siteOutbound(String id) {
		PlatformFittingApplyEntity entity = getById(id);
		if(!FittingConstant.STATUS_APPLY_ENGHT.equals(entity.getStatus())){
			throw  new ServiceException("单据状态发生改变，请刷新再试");
		}
		BladeUser user = AuthUtil.getUser();
		entity.setStatus(FittingConstant.STATUS_APPLY_NINE);
		entity.setConfirmor(user.getNickName());
		entity.setConfirmorId(user.getUserId().toString());
		entity.setOutFittingTime(new Date());
		if(!updateById(entity)){
			throw  new ServiceException("出库失败！");
		}
		MaterialOperationEntity siteMater = operationService.findByMateId(entity.getFittingId(),entity.getSiteId());
		if(siteMater==null){
			throw  new ServiceException(entity.getFittingName()+"，运营商物料库存不足");
		}

		siteMater.setFreezeAmount(siteMater.getFreezeAmount()+entity.getApplyNum());
		siteMater.setStock(siteMater.getStock()-entity.getApplyNum());
		if(siteMater.getStock()<0){
			throw  new ServiceException(entity.getFittingName()+"，物料库存不足");
		}
		if(!operationService.updateById(siteMater)){
			throw  new ServiceException("出库保存物料信息失败！");
		}
		return true;
	}


	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean empReceiveMate(String id) {
		PlatformFittingApplyEntity entity = getById(id);
		if(!FittingConstant.STATUS_APPLY_NINE.equals(entity.getStatus())){
			throw  new ServiceException("单据状态发生改变，请刷新再试");
		}
		entity.setStatus(FittingConstant.STATUS_APPLY_FIVE);
		BladeUser user = AuthUtil.getUser();
		entity.setSendTime(new Date());
		entity.setConfirmStorageId(user.getUserId().toString());
		entity.setConfirmStorage(user.getNickName());
		entity.setEndTime(new Date());
		MaterialOperationEntity siteStock = operationService.findByMateId(entity.getFittingId(),entity.getSiteId());
		siteStock.setFreezeAmount(siteStock.getFreezeAmount()-entity.getApplyNum());
		if(siteStock.getFreezeAmount()<0){
			throw  new ServiceException("物料冻结库存数量不足！");
		}
		MaterialEntity materialEntity=materialService.getByMaterialCode(entity.getFittingCode());
		boolean fg=operationService.updateById(siteStock);
        if(!fg){
        	throw new ServiceException("保存库存信息失败！");
		}
		OperationSiteEntity site = siteService.getById(entity.getSiteId());
		//生成运维商出库记录
		outboundService.saveMaterialOutbound(entity,materialEntity,"2",site.getId(),user,"2",site.getName(),FittingConstant.KEEP_FORM_OUT);
		//工程师添加库存
		MaterialEngineerEntity empStock = engineerService.getEngineerStock(entity.getApplicantId(),entity.getFittingId());
		if(empStock ==null){
			empStock = new MaterialEngineerEntity();
			empStock.setMaterialId(materialEntity.getId());
			empStock.setOperationId(entity.getSiteId());
			empStock.setOperationName(site.getName());
			empStock.setEngineerId(Long.valueOf(entity.getApplicantId()));
			empStock.setEngineerName(entity.getApplicantName());
			empStock.setCode(materialEntity.getCode());
			empStock.setName(materialEntity.getName());
			empStock.setType(materialEntity.getType());
			empStock.setModel(materialEntity.getModel());
			empStock.setPower(materialEntity.getPower());
			empStock.setDescription(materialEntity.getDescription());
			empStock.setBrand(materialEntity.getBrand());
			empStock.setStock(entity.getApplyNum());
			empStock.setCreateUser(user.getUserId());
			empStock.setCreateTime(new Date());
			empStock.setIsDeleted(0);
		}else{
			empStock.setStock(empStock.getStock()+entity.getApplyNum());
		}
		if(!engineerService.saveOrUpdate(empStock)){
			throw new ServiceException("保存工程师库存信息失败！");
		}
		//生成工程师入库记录
		outboundService.saveMaterialOutbound(entity,materialEntity,"1",site.getId(),user,"1",entity.getApplicantName(),FittingConstant.KEEP_FORM_IN);
		msgService.saveMsg(entity.getId(),site.getId(),"工程师领取", user.getNickName());
		return updateById(entity);

	}

	@Override
	public ApplyDto findHomeFittingCount() {
		BladeUser user = AuthUtil.getUser();
		//3.服务商 4.平台员工 5.服务商人员
		String  appId = user.getUserId().toString();
		return getBaseMapper().findHomeFittingCount(appId);
	}

	@Override
	public List<OperationOrderMaterialVO> auditFittingMatchingMaterial(Map<String, Object> params) {
		List<OperationOrderMaterialVO> list=baseMapper.auditFittingMatchingMaterial(params);
		 return list;
	}


}
