package org.springblade.modules.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.Query;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
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.order.constant.OrderConstants;
import org.springblade.modules.order.mapper.OperationOrderLetterMapper;
import org.springblade.modules.order.pojo.dto.OrderLetterDTO;
import org.springblade.modules.order.pojo.entity.OperationOrderEntity;
import org.springblade.modules.order.pojo.entity.OperationOrderLetterEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@Service
public class OperationOrderLetterService extends ServiceImpl<OperationOrderLetterMapper, OperationOrderLetterEntity> {

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

	@Autowired
	private OperationOrderServiceImpl orderService;


	/**
	 * 上传/修改 公函
	 * 开发说明：仅可对最新一条记录进行编辑和删除；历史公函记录，仅可修改扣款金额；公函重新上传后，清空再次预警时间和扣款金额，需再次填写；删除提示：是否确认删除公函信息？
	 */
	@Transactional(rollbackFor = Exception.class)
	public boolean saveLetter(OrderLetterDTO letterDTO){
        logger.info("saveLetter  id:{}",letterDTO.getId());
		OperationOrderLetterEntity letterEntity;
		BladeUser user = AuthUtil.getUser();
		OperationOrderEntity order = orderService.getById(letterDTO.getOrderId());
		if(order==null){
			throw new ServiceException("未找到工单信息！");
		}
        if(StringUtil.isBlank(letterDTO.getId())){
        	 letterEntity=new OperationOrderLetterEntity();
        	 letterEntity.setOrderId(letterDTO.getOrderId());
        	 letterEntity.setCreateTime(new Date());
        	 letterEntity.setCreateName(user.getNickName());
        	 letterEntity.setStatus(OrderConstants.STATUS_USE);
			 letterEntity.setWarningDay(letterDTO.getWarningDay());
			 letterEntity.setDeductionAmount(letterDTO.getDeductionAmount());
			 letterEntity.setLetterPath(letterDTO.getLetterPath());
			 letterEntity.setLetterFileName(letterDTO.getLetterFileName());

			int count=order.getExtensionCount()==null?1:order.getExtensionCount()+1;
			BigDecimal deductionAmount=order.getDeductionTotalAmount()==null?BigDecimal.ZERO:order.getDeductionTotalAmount();
			LambdaUpdateWrapper<OperationOrderEntity> updateWrapper=new LambdaUpdateWrapper<>();
			updateWrapper.eq(OperationOrderEntity::getId,letterDTO.getOrderId());
			updateWrapper.set(OperationOrderEntity::getExtensionCount,count);
			updateWrapper.set(OperationOrderEntity::getWarningStartDay,letterDTO.getWarningDay());
			updateWrapper.set(OperationOrderEntity::getDeductionTotalAmount,deductionAmount.add(letterEntity.getDeductionAmount()));
			orderService.update(updateWrapper);
		}else{
        	letterEntity=getById(letterDTO.getId());

			LambdaUpdateWrapper<OperationOrderEntity> updateWrapper=new LambdaUpdateWrapper<>();
			updateWrapper.eq(OperationOrderEntity::getId,letterDTO.getOrderId());
			updateWrapper.set(OperationOrderEntity::getDeductionTotalAmount,order.getDeductionTotalAmount().subtract(letterEntity.getDeductionAmount()).add(letterDTO.getDeductionAmount()));
        	//判断是否是最新一次的记录
            String latestId= baseMapper.ifLatestRecord(letterDTO.getOrderId());
            if(letterDTO.getId().equals(latestId)){
            	letterEntity.setWarningDay(letterDTO.getWarningDay());
            	letterEntity.setLetterPath(letterDTO.getLetterPath());
				letterEntity.setLetterFileName(letterDTO.getLetterFileName());
            	if(order.getWarningStartDay().compareTo(letterDTO.getWarningDay())!=0){
					updateWrapper.set(OperationOrderEntity::getWarningStartDay,letterDTO.getWarningDay());

				}
			}
			orderService.update(updateWrapper);

			letterEntity.setDeductionAmount(letterDTO.getDeductionAmount());
            letterEntity.setUpdateTime(new Date());
            letterEntity.setUpdateName(user.getNickName());
		}
		return saveOrUpdate(letterEntity);
	}

	/**
	 * 删除公函
	 */
	@Transactional(rollbackFor = Exception.class)
	public boolean deleteLetter(String id){
       logger.info(">>deleteLetter id:{}",id);
		OperationOrderLetterEntity letterEntity= getById(id);
		//判断是否是最新一次的记录
		String latestId= baseMapper.ifLatestRecord(letterEntity.getOrderId());
		if(!id.equals(latestId)){
			throw new ServiceException("非最后一次记录，不能删除！");
		}
		OperationOrderEntity order = orderService.getById(letterEntity.getOrderId());
		Date warningTime;
		//获取上一次的公函记录，修改预警时间
		OperationOrderLetterEntity latestLetter= baseMapper.getLatestLetter(id);
		if(latestLetter==null){
			warningTime= DateUtils.addDays(order.getDispatchTime(),3);
		}else{
			warningTime=letterEntity.getWarningDay();
		}
		LambdaUpdateWrapper<OperationOrderEntity> updateWrapper=new LambdaUpdateWrapper<>();
		updateWrapper.eq(OperationOrderEntity::getId,letterEntity.getOrderId());
		updateWrapper.set(OperationOrderEntity::getWarningStartDay,warningTime);
		updateWrapper.set(OperationOrderEntity::getExtensionCount,order.getExtensionCount()-1);
		updateWrapper.set(OperationOrderEntity::getDeductionTotalAmount,order.getDeductionTotalAmount().subtract(letterEntity.getDeductionAmount()));
		orderService.update(updateWrapper);

		letterEntity.setStatus(OrderConstants.STATUS_DELETE);
		letterEntity.setUpdateTime(new Date());
		BladeUser user = AuthUtil.getUser();
		letterEntity.setUpdateName(user.getNickName());
		return updateById(letterEntity);
	}

	public List<OperationOrderLetterEntity> getOrderLetterList(String orderId){
		LambdaQueryWrapper<OperationOrderLetterEntity> queryWrapper=new LambdaQueryWrapper<>();
		queryWrapper.eq(OperationOrderLetterEntity::getOrderId,orderId);
		queryWrapper.eq(OperationOrderLetterEntity::getStatus,OrderConstants.STATUS_USE);
		queryWrapper.orderByAsc(OperationOrderLetterEntity::getCreateTime);
		return list(queryWrapper);
	}

}
