package com.dk.mdm.service.ivt;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.dk.common.exception.BaseBusinessException;
import com.dk.common.infrastructure.annotaiton.Pagination;
import com.dk.common.infrastructure.constant.Constant;
import com.dk.common.infrastructure.enums.ErrorCodeEnum;
import com.dk.common.model.pojo.PageList;
import com.dk.common.response.ResponseCodeEnum;
import com.dk.common.response.ResponseResultUtil;
import com.dk.common.response.ResponseResultVO;
import com.dk.mdm.infrastructure.convert.ivt.TransferConvert;
import com.dk.mdm.infrastructure.convert.ivt.TransferItemConvert;
import com.dk.mdm.mapper.ivt.InboundItemMapper;
import com.dk.mdm.mapper.ivt.OutboundItemMapper;
import com.dk.mdm.mapper.ivt.TransferItemMapper;
import com.dk.mdm.model.pojo.ivt.*;
import com.dk.mdm.mapper.ivt.TransferMapper;
import com.dk.common.service.BaseService;
import com.dk.common.mapper.BaseMapper;
import com.dk.mdm.model.pojo.mac.RecPay;
import com.dk.mdm.model.pojo.mac.RecPayItem;
import com.dk.mdm.model.pojo.sale.Order;
import com.dk.mdm.model.query.ivt.CheckItemQuery;
import com.dk.mdm.model.query.ivt.TransferItemQuery;
import com.dk.mdm.model.query.ivt.TransferQuery;
import com.dk.mdm.model.response.ivt.*;
import com.dk.mdm.model.response.ivt.InboundItemResponse;
import com.dk.mdm.model.response.ivt.InventoryResponse;
import com.dk.mdm.model.response.ivt.OutboundItemResponse;
import com.dk.mdm.model.response.ivt.TransferResponse;
import com.dk.mdm.model.vo.ivt.*;
import com.dk.mdm.service.common.CommonService;
import com.dk.mdm.service.ivt.inbound.InboundCheckService;
import com.dk.mdm.service.ivt.inbound.InboundItemService;
import com.dk.mdm.service.ivt.outbound.OutboundCheckService;
import com.dk.mdm.service.ivt.outbound.OutboundItemService;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Transactional
public class TransferService extends BaseService<Transfer> {

	@Override
	public BaseMapper<Transfer> getRepository() {
		return transferMapper;
	}

	@Autowired
	private TransferMapper transferMapper;

	@Autowired
	private TransferItemMapper transferItemMapper;

	@Autowired
	private TransferConvert transferConvert;

	@Autowired
	private TransferItemConvert transferItemConvert;

	@Autowired
	private CommonService commonService;

	@Autowired
	private InboundCheckService inboundCheckService;

	@Autowired
	private OutboundCheckService outboundCheckService;

	@Autowired
	private InboundItemService inboundItemService;

	@Autowired
	private OutboundItemService outboundItemService;

	@Autowired
	private InboundItemMapper inboundItemMapper;

	/**
	 * @desc   : 重写主键
	 * @author : 宋扬
	 * @date   : 2023/3/27 10:39
	 */
	@Override
	public String getPrimaryKey() {
		return "transfer_id";
	}

	/**
	 * @desc   : 查询一览信息
	 * @author : 宋扬
	 * @date   : 2024/4/2 9:24
	 */
	@Pagination
	public ResponseResultVO<PageList<TransferResponse>> selectByCond(TransferQuery transferQuery) {
		return super.mergeListWithCount(transferQuery, transferMapper.selectByCond(transferQuery),
				transferMapper.countByCond(transferQuery));
	}

	/**
	 * @desc   : 新建调整单
	 * @author : 宋扬
	 * @date   : 2024/3/27 11:08
	 */
	@Transactional(rollbackFor = {Exception.class})
	public ResponseResultVO<?> insert(TransferVO transferVO) {
		// 转化实体
		Transfer transfer = transferConvert.convertToPo(transferVO);
		Map<String, Object> codeMap = commonService.getUniqueNoteCode(Constant.docNameConstant.Transfer.getName(), true);

		//判断调整类型 仓库调整
		if(transferVO.getTransferType().equals(Constant.transferType.CHECK_TYPE_WH.getName())){
			// 插入仓库调整单的实体
			transfer.setTransferId(codeMap.get("outId").toString()).setTransferNo(codeMap.get("outNote").toString())
					.setTransferDate(LocalDate.now()).setStaffId(transferVO.getStaffId()).setOrgId(transferVO.getOrgId())
					.setTransferType(transferVO.getTransferType()).setMakeStaff(transferVO.getMakeStaff())
					.setMakeTime(LocalDateTime.now()).setRemarks(transferVO.getRemarks());
			/*.setOWhId(transferVO.getOWhId()).setWhId(transferVO.getWhId());*/

		}else{
			// 插入非标号调整单的实体
			transfer.setTransferId(codeMap.get("outId").toString()).setTransferNo(codeMap.get("outNote").toString())
					.setTransferDate(LocalDate.now()).setStaffId(transferVO.getStaffId()).setOrgId(transferVO.getOrgId())
					.setTransferType(transferVO.getTransferType()).setMakeStaff(transferVO.getMakeStaff())
					.setMakeTime(LocalDateTime.now()).setRemarks(transferVO.getRemarks());
			/*.setONonStdCode(transferVO.getONonStdCode()).setNonStdCode(transferVO.getNonStdCode());*/
		}
		// 先插调整单主表数据
		super.insert(transfer);
		// 因为需要获取目标inv_id,所以必须先调用入库接口。
		// 定义入库Map
		Map<String, Object> inboundMap= new HashMap<>();
		// 定义出库Map
		Map<String, Object> outboundCheckMap= new HashMap<>();
		if (transferVO.getItemList() != null && transferVO.getItemList().size() > 0){
			// 计算总调整量
			BigDecimal transferQtySum = transferVO.getItemList().stream().map(TransferItemVO::getTransferQty).reduce(BigDecimal.ZERO, BigDecimal::add)
					.setScale(6, BigDecimal.ROUND_HALF_UP);
			// 获取入库表实体
			InboundVO inboundVO = new InboundVO();
			List<InboundItemVO> inboundItemVOList=new ArrayList<>();
			// 获取出库表实体
			OutboundVO outboundVO = new OutboundVO();
			List<OutboundItemVO> outboundItemVOList=new ArrayList<>();
			// 仓库调整
			if(transferVO.getTransferType().equals(Constant.transferType.CHECK_TYPE_WH.getName())) {
				// 赋值出库实体
				outboundVO.setOrgId(transferVO.getOrgId()).setStaffId(transferVO.getStaffId())
						.setMakeStaff(transferVO.getMakeStaff()).setOutingQty(transferQtySum)
						.setFromId(transfer.getTransferId()).setFromNo(transfer.getTransferNo())
						.setMakeTime(LocalDateTime.now()).setOutDate(LocalDate.now())
						.setOutingAmt(BigDecimal.ZERO).setOutType(Constant.OutType.REMOVE.getName());
				// 获取出库明细实体
				for (TransferItemVO transferItemVO : transferVO.getItemList()) {
					// 赋值出库明细信息。
					OutboundItemVO outboundItemVO =new OutboundItemVO();
					outboundItemVO.setItemIndex(transferItemVO.getItemIndex()).setSkuId(transferItemVO.getSkuId())
							.setOutingQty(transferItemVO.getTransferQty()).setFromId(transfer.getTransferId())
							.setOutingAmt(BigDecimal.ZERO).setPriceOut(BigDecimal.ZERO).setInvId(transferItemVO.getOInvId())
							.setWhId(transferItemVO.getOWhId()).setNonStdCode(transferItemVO.getONonStdCode());
					outboundItemVOList.add(outboundItemVO);
				}

				// 赋值出库接口参数 总表和明细
				outboundCheckMap.put("total",outboundVO);
				outboundCheckMap.put("detail",outboundItemVOList);
				// 调用盘点出库接口
				OutboundVO outboundTransferVO = outboundCheckService.otherOutboundInsert(outboundCheckMap);

				// 赋值入库实体
				inboundVO.setOrgId(transferVO.getOrgId()).setStaffId(transferVO.getStaffId())
						.setMakeStaff(transferVO.getMakeStaff()).setIntoingQty(transferQtySum)
						.setFromId(transfer.getTransferId()).setFromNo(transfer.getTransferNo())
						.setMakeTime(LocalDateTime.now()).setIntoDate(LocalDate.now()).setWhId(transferVO.getWhId())
						.setFlgAutoHandle(true).setIntoingAmt(BigDecimal.ZERO)
						.setIntoType(Constant.IntoType.REMOVE.getName());

				// 获取入库明细实体
				for (TransferItemVO transferItemVO : transferVO.getItemList()) {
					// 赋值入库明细实体
					InboundItemVO inboundItemVO=new InboundItemVO();
					inboundItemVO.setItemIndex(transferItemVO.getItemIndex()).setSkuId(transferItemVO.getSkuId())
							.setIntoingQty(transferItemVO.getTransferQty()).setFromId(transfer.getTransferId())
							.setIntoingAmt(BigDecimal.ZERO).setPriceInto(BigDecimal.ZERO).setOutId(outboundTransferVO.getOutId())
							.setWhId(transferItemVO.getWhId()).setNonStdCode(transferItemVO.getONonStdCode());
					inboundItemVOList.add(inboundItemVO);
				}

				// 赋值入库接口参数 总表和明细
				inboundMap.put("total", inboundVO);
				inboundMap.put("detail", inboundItemVOList);
				// 调用入库接口
				InboundVO inboundTransferVO = inboundCheckService.checkInboundInsert(inboundMap);
				// 如果库存接口返回成功，则插入调整单明细数据
				if (transferVO.getItemList() != null && transferVO.getItemList().size() > 0) {
					for (TransferItemVO transferItemVO : transferVO.getItemList()) {
						// 转换库存调整单明细
						TransferItem transferItem = transferItemConvert.convertToPo(transferItemVO);
						// 在入库接口中获取入库明细数据
						inboundItemVOList = inboundTransferVO.getItemList().stream()
								.filter(it -> it.getItemIndex().equals(transferItemVO.getItemIndex())).collect(Collectors.toList());
						// 查询入库明细，取InvId值
						InboundItemResponse inboundItemResponse = inboundItemMapper.selectById(inboundItemVOList.get(0).getItemId());
						// 获取调整主表uuidhe
						transferItem.setTransferId(transfer.getTransferId()).setTransferDate(LocalDate.now())
								.setInvId(inboundItemResponse.getInvId()).setNonStdCode(transferItemVO.getONonStdCode());
						// 插入调整单明细数据
						transferItemMapper.insert(transferItem);
						// 赋值入库明细值 并修改入库明细from_item_id值
						InboundItem inboundItem= new InboundItem();
						inboundItem.setFromItemId(transferItem.getItemId()).setItemId(transferItemVO.getItemId());
						inboundItemService.updateByUuid(inboundItem);

						// 在出库接口中获取入库明细数据
						outboundItemVOList = outboundTransferVO.getItemList().stream()
								.filter(it -> it.getItemIndex().equals(transferItemVO.getItemIndex())).collect(Collectors.toList());

						// 赋值出库明细值 并修改出库明细from_item_id值
						OutboundItem outboundItem= new OutboundItem();
						outboundItem.setFromItemId(transferItem.getItemId()).setItemId(outboundItemVOList.get(0).getItemId());
						outboundItemService.updateByUuid(outboundItem);
					}
				}
			}
			// 非标号调整
			else{
				// 赋值出库实体
				outboundVO.setOrgId(transferVO.getOrgId()).setStaffId(transferVO.getStaffId())
						.setMakeStaff(transferVO.getMakeStaff()).setOutingQty(transferQtySum)
						.setFromId(transfer.getTransferId()).setFromNo(transfer.getTransferNo())
						.setMakeTime(LocalDateTime.now()).setOutDate(LocalDate.now())
						.setOutingAmt(BigDecimal.ZERO).setOutType(Constant.OutType.REMOVE.getName());
				// 获取出库明细实体
				for (TransferItemVO transferItemVO : transferVO.getItemList()) {
					// 赋值出库明细信息。
					OutboundItemVO outboundItemVO =new OutboundItemVO();
					outboundItemVO.setItemIndex(transferItemVO.getItemIndex()).setSkuId(transferItemVO.getSkuId())
							.setOutingQty(transferItemVO.getTransferQty()).setFromId(transfer.getTransferId())
							.setOutingAmt(BigDecimal.ZERO).setPriceOut(BigDecimal.ZERO).setInvId(transferItemVO.getOInvId())
							.setWhId(transferItemVO.getOWhId()).setNonStdCode(transferItemVO.getONonStdCode());
					outboundItemVOList.add(outboundItemVO);
				}
				// 赋值出库接口参数 总表和明细
				outboundCheckMap.put("total",outboundVO);
				outboundCheckMap.put("detail",outboundItemVOList);
				// 调用盘点出库接口
				OutboundVO outboundTransferVO = outboundCheckService.otherOutboundInsert(outboundCheckMap);

				// 赋值入库实体
				inboundVO.setOrgId(transferVO.getOrgId()).setStaffId(transferVO.getStaffId())
						.setMakeStaff(transferVO.getMakeStaff()).setIntoingQty(transferQtySum)
						.setFromId(transfer.getTransferId()).setFromNo(transfer.getTransferNo())
						.setMakeTime(LocalDateTime.now()).setIntoDate(LocalDate.now()).setWhId(transferVO.getOWhId())
						.setFlgAutoHandle(true).setIntoingAmt(BigDecimal.ZERO)
						.setIntoType(Constant.IntoType.REMOVE.getName());

				// 获取入库明细实体
				for (TransferItemVO transferItemVO : transferVO.getItemList()) {
					// 赋值入库明细实体
					InboundItemVO inboundItemVO=new InboundItemVO();
					inboundItemVO.setItemIndex(transferItemVO.getItemIndex()).setSkuId(transferItemVO.getSkuId())
							.setIntoingQty(transferItemVO.getTransferQty()).setFromId(transfer.getTransferId())
							.setIntoingAmt(BigDecimal.ZERO).setPriceInto(BigDecimal.ZERO).setOutId(outboundTransferVO.getOutId())
							.setWhId(transferItemVO.getOWhId()).setNonStdCode(transferItemVO.getNonStdCode());
					inboundItemVOList.add(inboundItemVO);
				}
				// 赋值入库接口参数 总表和明细
				inboundMap.put("total", inboundVO);
				inboundMap.put("detail", inboundItemVOList);
				// 调用入库接口
				InboundVO inboundTransferVO = inboundCheckService.checkInboundInsert(inboundMap);
				// 如果库存接口返回成功，则插入调整单明细数据
				if (transferVO.getItemList() != null && transferVO.getItemList().size() > 0) {
					for (TransferItemVO transferItemVO : transferVO.getItemList()) {
						// 转换库存调整单明细
						TransferItem transferItem = transferItemConvert.convertToPo(transferItemVO);
						// 在入库接口中获取入库明细数据
						inboundItemVOList = inboundTransferVO.getItemList().stream()
								.filter(it -> it.getItemIndex().equals(transferItemVO.getItemIndex())).collect(Collectors.toList());
						// 查询入库明细，取InvId值
						InboundItemResponse inboundItemResponse = inboundItemMapper.selectById(inboundItemVOList.get(0).getItemId());
						// 获取调整主表uuid
						transferItem.setTransferId(transfer.getTransferId()).setTransferDate(LocalDate.now())
								.setInvId(inboundItemResponse.getInvId()).setWhId(transferItemVO.getOWhId());
						// 插入调整单明细数据
						transferItemMapper.insert(transferItem);
						// 赋值入库明细值 并修改入库明细from_item_id值
						InboundItem inboundItem= new InboundItem();
						inboundItem.setFromItemId(transferItem.getItemId()).setItemId(inboundItemVOList.get(0).getItemId());
						inboundItemService.updateByUuid(inboundItem);

						// 在出库接口中获取入库明细数据
						outboundItemVOList = outboundTransferVO.getItemList().stream()
								.filter(it -> it.getItemIndex().equals(transferItemVO.getItemIndex())).collect(Collectors.toList());
						// 赋值出库明细值 并修改出库明细from_item_id值
						OutboundItem outboundItem= new OutboundItem();
						outboundItem.setFromItemId(transferItem.getItemId()).setItemId(outboundItemVOList.get(0).getItemId());
						outboundItemService.updateByUuid(outboundItem);
					}

				}
			}
		}
		return ResponseResultUtil.success();
	}

	/**
	 * @desc   : 作废
	 * @author : 宋扬
	 * @date   : 2024/4/15 16:28
	 */
	public ResponseResultVO<?> invalid(String id) {
		Transfer transferForUpdate = transferMapper.selectByIdForUpdate(id);
		// 并发校验
		if (!transferForUpdate.getFlgValid()) {
			throw new BaseBusinessException(ResponseCodeEnum.OPERATE_FAIL.getCode(), ErrorCodeEnum.ISFLGVALID_FALSE.getMessage());
		}
		// 作废
		Transfer transferUpdate = new Transfer();
		transferUpdate.setFlgValid(false).setTransferId(id);
		super.updateByUuid(transferUpdate);

		// 调用入库作废接口
		inboundCheckService.inboundRepeal(id);
		// 调用出库作废接口
		outboundCheckService.outboundRepeal(id);
		return ResponseResultUtil.success();
	}


	/**
	 * @desc   : 通过ID获取编辑调整单信息
	 * @author : 王英杰
	 * @date   : 2024/3/28 15:38
	 */
	public ResponseResultVO<?> getTransferForUpdate(String id) {
		Map<String, Object> dataInfo = new HashMap<>();
		TransferResponse transferResponse = transferMapper.selectById(id);
		dataInfo.put("data", transferResponse);
		// 商品明细
		List<TransferItemResponse> transferItem = transferItemMapper.selectByCond(new TransferItemQuery().setTransferId(id));
		dataInfo.put("dataItem", transferItem);
		return ResponseResultUtil.success(dataInfo);
	}

}
