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

import java.util.List;
import java.util.Objects;

import com.jeeplus.modules.warehouse.code.util.CodeUtil;
import com.jeeplus.modules.warehouse.code.util.StaticNumSeq;
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.outbound.entity.Outbound;
import com.jeeplus.modules.warehouse.outbound.mapper.OutboundMapper;
import com.jeeplus.modules.warehouse.outbound.entity.OutboundInfo;
import com.jeeplus.modules.warehouse.outbound.mapper.OutboundInfoMapper;

/**
 * 出库信息Service
 * @author zhanglt
 * @version 2023-02-14
 */
@Service
@Transactional(readOnly = true)
public class OutboundService extends CrudService<OutboundMapper, Outbound> {

	@Autowired
	private OutboundInfoMapper outboundInfoMapper;
	
	public Outbound get(String id) {
		Outbound outbound = super.get(id);
		outbound.setOutboundInfoList(outboundInfoMapper.findList(new OutboundInfo(outbound)));
		return outbound;
	}
	
	public List<Outbound> findList(Outbound outbound) {
		return super.findList(outbound);
	}
	
	public Page<Outbound> findPage(Page<Outbound> page, Outbound outbound) {
		return super.findPage(page, outbound);
	}
	
	@Transactional(readOnly = false)
	public void save(Outbound outbound) {
		if(outbound.getNumber() == null || Objects.equals(outbound.getNumber(), "")){
			outbound.setNumber(this.createCKDH());
		}
		super.save(outbound);
		for (OutboundInfo outboundInfo : outbound.getOutboundInfoList()){
			if (outboundInfo.getId() == null){
				continue;
			}
			if (OutboundInfo.DEL_FLAG_NORMAL.equals(outboundInfo.getDelFlag())){
				if (StringUtils.isBlank(outboundInfo.getId())){
					outboundInfo.setOutbound(outbound);
					outboundInfo.preInsert();
					outboundInfoMapper.insert(outboundInfo);
				}else{
					outboundInfo.setOutbound(outbound);

					outboundInfo.preUpdate();
					outboundInfoMapper.update(outboundInfo);
				}
			}else{
				outboundInfoMapper.delete(outboundInfo);
			}
		}
	}
	@Transactional(readOnly = false)
	public String createCKDH() {
		String ckdh = CodeUtil.code("CKDH", StaticNumSeq.CKDH);
		return ckdh;
	}
	@Transactional(readOnly = false)
	public void delete(Outbound outbound) {
		super.delete(outbound);
		outboundInfoMapper.delete(new OutboundInfo(outbound));
	}
	
}