package com.dk.mdm.service.ivt.inbound;

import com.dk.common.infrastructure.annotaiton.Pagination;
import com.dk.common.infrastructure.constant.Constant;
import com.dk.common.model.pojo.PageList;
import com.dk.common.response.ResponseResultUtil;
import com.dk.common.response.ResponseResultVO;
import com.dk.mdm.infrastructure.convert.ivt.InboundItemConvert;
import com.dk.mdm.mapper.ivt.*;
import com.dk.mdm.model.pojo.ivt.*;
import com.dk.common.service.BaseService;
import com.dk.common.mapper.BaseMapper;
import com.dk.mdm.model.query.ivt.InboundItemQuery;
import com.dk.mdm.model.query.ivt.InventoryBatchQuery;
import com.dk.mdm.model.query.ivt.OutboundItemCostQuery;
import com.dk.mdm.model.query.ivt.OutboundItemQuery;
import com.dk.mdm.model.response.ivt.InboundItemResponse;
import com.dk.mdm.model.response.ivt.InventoryBatchResponse;
import com.dk.mdm.model.response.ivt.InventoryResponse;
import com.dk.mdm.model.response.ivt.OutboundItemCostResponse;
import com.dk.mdm.model.vo.ivt.InboundItemVO;
import com.dk.mdm.model.vo.ivt.InboundVO;
import com.dk.mdm.service.common.CommonService;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

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

@Service
@Transactional
public class InboundItemService extends BaseService<InboundItem> {

	@Override
	public BaseMapper<InboundItem> getRepository() {
		return inboundItemMapper;
	}

	@Autowired
	private InboundItemMapper inboundItemMapper;

	@Autowired
	private InboundItemConvert inboundItemConvert;

	@Autowired
	private CommonService commonService;

	@Autowired
	private InventoryBatchMapper inventoryBatchMapper;

	@Autowired
	private OutboundItemCostMapper outboundItemCostMapper;

	@Autowired
	private OutboundItemMapper outboundItemMapper;

	@Autowired
	private InventoryMapper inventoryMapper;

	/**
	 * @desc   : 条件查询 (采购入库用)
	 * @author : 常皓宁
	 * @date   : 2024/3/13 14:36
	 */
	@Pagination
	public ResponseResultVO<PageList<InboundItemResponse>> selectByCond(InboundItemQuery inboundItemQuery) {
		return super.mergeListWithCount(inboundItemQuery, inboundItemMapper.selectByCond(inboundItemQuery), inboundItemMapper.countByCond(inboundItemQuery));
	}


	/**
	 * @desc : 新建入库单明细
	 * @author : 王英杰
	 * @date : 2024/3/6 10:36
	 */
	@Transactional(
			rollbackFor = {Exception.class}
	)
	public ResponseResultVO<?> insert(InboundItemVO inboundItemVO) {
		//实体转换
		InboundItem inboundItem = inboundItemConvert.convertToPo(inboundItemVO);


		//新建
		inboundItemMapper.insert(inboundItem);


		return ResponseResultUtil.success();
	}

	/**
	 * @desc   : 条件查询 (入库成本核对用)
	 * @author : 常皓宁
	 * @date   : 2024/3/13 14:36
	 */
	@Pagination
	public ResponseResultVO<PageList<InboundItemResponse>> selectCostCheck(InboundItemQuery inboundItemQuery) {
		return super.mergeListWithCount(inboundItemQuery, inboundItemMapper.selectCostCheck(inboundItemQuery), inboundItemMapper.countByCond(inboundItemQuery));
	}

	/**
	 * @desc   : 入库成本核对
	 * @author : 常皓宁
	 * @date   : 2024/4/17 15:26
	 */
	@Transactional(rollbackFor = {Exception.class})
	public ResponseResultVO<?> CostCheckOk(List<InboundItemQuery> inboundItemQuery) {
		for(InboundItemQuery inboundItem : inboundItemQuery){
			//修改入库明细表
			InboundItem inboundItem1 = new InboundItem()
					.setItemId(inboundItem.getItemId())
					.setCostPrice(inboundItem.getCostPrice())
					.setCostAmt(inboundItem.getCostAmt());
			inboundItemMapper.updateCost(inboundItem1);
			//查询存货批次明细
			InventoryBatchResponse inventoryBatchResponse =
					inventoryBatchMapper.selectCostCondition(new InventoryBatchQuery().setFromItemId(inboundItem.getItemId()));
			//查询出库成本
			List<OutboundItemCostResponse> outboundItemCostResponses =
					outboundItemCostMapper.selectCostOutbound(new OutboundItemCostQuery().setBatchId(inventoryBatchResponse.getBatchId()));
			//当出库成本有数据且数量不为0（理论上是没有数据 数量就是0）
			BigDecimal outCostAmtTotal = BigDecimal.ZERO;//总出库成本总和
			if(outboundItemCostResponses.size() > 0){
				for(OutboundItemCostResponse outboundItemCostResponse : outboundItemCostResponses){
					//出库数量不是0
					if(outboundItemCostResponse.getOutQty().compareTo(BigDecimal.ZERO) != 0){
						//出库成本 单独计算后面需要合计
						BigDecimal outCostAmt = inboundItem.getCostPrice().multiply(outboundItemCostResponse.getOutQty());
						//先用出库单价*出库数量计算金额 如果后面有差额 就更最后一条数据
						OutboundItemCostQuery outboundItemCostQuery = new OutboundItemCostQuery()
								.setBatchId(outboundItemCostResponse.getBatchId())
								.setCostPrice(inboundItem.getCostPrice())
								.setCostAmt(outCostAmt);
						//修改出库成本
						outboundItemCostMapper.updateOutboundCost(outboundItemCostQuery);
						//修改出库明细表
						OutboundItemQuery outboundItemQuery = new OutboundItemQuery()
								.setItemId(outboundItemCostResponse.getOutItemId())
								.setCostPrice(inboundItem.getCostPrice())
								.setCostAmt(outCostAmt);
						outboundItemMapper.updateOutCost(outboundItemQuery);

						outCostAmtTotal = outCostAmtTotal.add(outCostAmt);
						//修改存货批次明细
						InventoryBatchQuery inventoryBatchQuery = new InventoryBatchQuery()
								.setBatchId(inventoryBatchResponse.getBatchId())
								.setCostPrice(inboundItem.getCostPrice())
								.setCostAmt(inboundItem.getCostPrice().multiply(inventoryBatchResponse.getInvQty()));
						inventoryBatchMapper.updateInventoryBatchCost(inventoryBatchQuery);
						//修改总单
						this.updateInventory(new InventoryBatchQuery().setInvId(inventoryBatchResponse.getInvId()));
					}
					//出库数量是0
					else if(outboundItemCostResponse.getOutQty().compareTo(BigDecimal.ZERO) == 0){
						InventoryBatchQuery inventoryBatchQuery = new InventoryBatchQuery()
								.setBatchId(inventoryBatchResponse.getBatchId())
								.setCostPrice(inboundItem.getCostPrice())
								.setCostAmt(inboundItem.getCostAmt());
						inventoryBatchMapper.updateInventoryBatchCost(inventoryBatchQuery);
						//修改总单
						this.updateInventory(new InventoryBatchQuery().setInvId(inventoryBatchResponse.getInvId()));
					}
				}
				//出库成本 金额之和 加上 存货批次明细成本金额（存货资产） = 核对金额
				//如果出库成本核对有差额 就更最后一条数据
				BigDecimal batchCostAmt = inboundItem.getCostPrice().multiply(inventoryBatchResponse.getInvQty());//存货资产
				//修改的成本金额总和（存货资产 + 出库成本 金额）
				BigDecimal costAmtTotal = batchCostAmt.add(outCostAmtTotal);
				if(costAmtTotal.compareTo(inboundItem.getCostAmt())!= 0){
					//修改出库成本
					OutboundItemCostQuery updateLastCost = new OutboundItemCostQuery()
							.setBatchId(outboundItemCostResponses.get(outboundItemCostResponses.size() - 1).getBatchId())
							.setCostAmt(inboundItem.getCostAmt().subtract(costAmtTotal));
					outboundItemCostMapper.updateLastCost(updateLastCost);
					//修改出库明细
					OutboundItemQuery outboundItemQuery = new OutboundItemQuery()
							.setItemId(outboundItemCostResponses.get(outboundItemCostResponses.size() - 1).getOutItemId())
							.setCostPrice(inboundItem.getCostPrice())
							.setCostAmt(inboundItem.getCostAmt().subtract(costAmtTotal));
					outboundItemMapper.updateLastCost(outboundItemQuery);
				}
			}
			//当出库成本没有数据 只修改存货批次明细
			else{
				InventoryBatchQuery inventoryBatchQuery = new InventoryBatchQuery()
						.setBatchId(inventoryBatchResponse.getBatchId())
						.setCostPrice(inboundItem.getCostPrice())
						.setCostAmt(inboundItem.getCostAmt());
				inventoryBatchMapper.updateInventoryBatchCost(inventoryBatchQuery);
				//修改总单
				this.updateInventory(new InventoryBatchQuery().setInvId(inventoryBatchResponse.getInvId()));
			}
		}
		return ResponseResultUtil.success();
	}

	/**
	 * @desc   : 修改存货总单信息（入库成本核对）
	 * @author : 常皓宁
	 * @date   : 2024/4/18 15:07
	 */
	@Transactional(rollbackFor = {Exception.class})
	public ResponseResultVO<?> updateInventory(InventoryBatchQuery inventoryBatchQuery) {
		//总单
		InventoryResponse inventoryResponse = inventoryMapper.selectById(inventoryBatchQuery.getInvId());
		//明细
		List<InventoryBatchResponse> inventoryBatchList
				= inventoryBatchMapper.selectByCond(new InventoryBatchQuery().setInvId(inventoryBatchQuery.getInvId()));

		BigDecimal inventoryCostTotal = BigDecimal.ZERO;
		for(InventoryBatchResponse inventoryBatchResponse1 : inventoryBatchList){
			inventoryCostTotal = inventoryCostTotal.add(inventoryBatchResponse1.getCostAmt());
		}
		Inventory inventory = new Inventory()
				.setInvId(inventoryBatchQuery.getInvId())
				.setCostPrice(inventoryCostTotal.divide(inventoryResponse.getInvQty(),BigDecimal.ROUND_HALF_UP))
				.setCostAmt(inventoryCostTotal);
		inventoryMapper.updateCost(inventory);
		return ResponseResultUtil.success(inventoryBatchQuery);
	}

}
