/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.warehouse.materialrequisition.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.service.CrudService;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.modules.warehouse.materialrequisition.entity.MaterialRequisition;
import com.jeeplus.modules.warehouse.materialrequisition.mapper.MaterialRequisitionMapper;
import com.jeeplus.modules.warehouse.materialrequisition.entity.MaterialRequisitionInfo;
import com.jeeplus.modules.warehouse.materialrequisition.mapper.MaterialRequisitionInfoMapper;

/**
 * 物资领用Service
 * @author zhanglt
 * @version 2023-02-13
 */
@Service
@Transactional(readOnly = true)
public class MaterialRequisitionService extends CrudService<MaterialRequisitionMapper, MaterialRequisition> {

	@Autowired
	private MaterialRequisitionInfoMapper materialRequisitionInfoMapper;
	
	public MaterialRequisition get(String id) {
		MaterialRequisition materialRequisition = super.get(id);
		materialRequisition.setMaterialRequisitionInfoList(materialRequisitionInfoMapper.findList(new MaterialRequisitionInfo(materialRequisition)));
		return materialRequisition;
	}
	
	public List<MaterialRequisition> findList(MaterialRequisition materialRequisition) {
		return super.findList(materialRequisition);
	}
	
	public Page<MaterialRequisition> findPage(Page<MaterialRequisition> page, MaterialRequisition materialRequisition) {
		return super.findPage(page, materialRequisition);
	}
	
	@Transactional(readOnly = false)
	public void save(MaterialRequisition materialRequisition) {
		super.save(materialRequisition);
		for (MaterialRequisitionInfo materialRequisitionInfo : materialRequisition.getMaterialRequisitionInfoList()){
			materialRequisitionInfo.setMaterialRequisition(materialRequisition);
			if (materialRequisitionInfo.getId() == null){
				continue;
			}
			if (MaterialRequisitionInfo.DEL_FLAG_NORMAL.equals(materialRequisitionInfo.getDelFlag())){
				if (StringUtils.isBlank(materialRequisitionInfo.getId())){
					materialRequisitionInfo.preInsert();
					materialRequisitionInfoMapper.insert(materialRequisitionInfo);
				}else{
					materialRequisitionInfo.preUpdate();
					materialRequisitionInfoMapper.update(materialRequisitionInfo);
				}
			}else{
				materialRequisitionInfoMapper.delete(materialRequisitionInfo);
			}
		}
	}
	
	@Transactional(readOnly = false)
	public void delete(MaterialRequisition materialRequisition) {
		super.delete(materialRequisition);
		materialRequisitionInfoMapper.delete(new MaterialRequisitionInfo(materialRequisition));
	}
	
}