/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.warehouse.ledger.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.ledger.entity.Ledger;
import com.jeeplus.modules.warehouse.ledger.mapper.LedgerMapper;
import com.jeeplus.modules.warehouse.ledger.entity.LedgerInfo;
import com.jeeplus.modules.warehouse.ledger.mapper.LedgerInfoMapper;

/**
 * 台账信息Service
 * @author huyi
 * @version 2023-02-13
 */
@Service
@Transactional(readOnly = true)
public class LedgerService extends CrudService<LedgerMapper, Ledger> {

	@Autowired
	private LedgerInfoMapper ledgerInfoMapper;
	
	public Ledger get(String id) {
		Ledger ledger = super.get(id);
		ledger.setLedgerInfoList(ledgerInfoMapper.findList(new LedgerInfo(ledger)));
		return ledger;
	}
	
	public List<Ledger> findList(Ledger ledger) {
		return super.findList(ledger);
	}
	
	public Page<Ledger> findPage(Page<Ledger> page, Ledger ledger) {
		return super.findPage(page, ledger);
	}
	
	@Transactional(readOnly = false)
	public void save(Ledger ledger) {
		super.save(ledger);
		for (LedgerInfo ledgerInfo : ledger.getLedgerInfoList()){
			if (ledgerInfo.getId() == null){
				continue;
			}
			if (LedgerInfo.DEL_FLAG_NORMAL.equals(ledgerInfo.getDelFlag())){
				if (StringUtils.isBlank(ledgerInfo.getId())){
					ledgerInfo.setLedger(ledger);
					ledgerInfo.preInsert();
					ledgerInfoMapper.insert(ledgerInfo);
				}else{
					ledgerInfo.preUpdate();
					ledgerInfoMapper.update(ledgerInfo);
				}
			}else{
				ledgerInfoMapper.delete(ledgerInfo);
			}
		}
	}
	
	@Transactional(readOnly = false)
	public void delete(Ledger ledger) {
		super.delete(ledger);
		ledgerInfoMapper.delete(new LedgerInfo(ledger));
	}
	
}