package com.uas.platform.b2b.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.uas.platform.b2b.dao.ApbillAdjustmentDao;
import com.uas.platform.b2b.erp.model.PurchaseAPBill;
import com.uas.platform.b2b.model.ApbillAdjustment;
import com.uas.platform.b2b.service.ApbillAdjustmentService;
import com.uas.platform.b2b.support.SystemSession;
import com.uas.platform.core.model.Constant;
import com.uas.platform.core.model.Status;


@Service
public class ApbillAdjustmentServiceImpl implements ApbillAdjustmentService {

	@Autowired
	private ApbillAdjustmentDao apbillAdjustmentDao;

	@Override
	public void save(List<ApbillAdjustment> apBilladjustments) {
		try {
			apbillAdjustmentDao.save(apBilladjustments);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public List<ApbillAdjustment> convertnonPostAdjustment(List<PurchaseAPBill> apBills) {
		List<ApbillAdjustment> adjusts = new ArrayList<ApbillAdjustment>();
		if (!CollectionUtils.isEmpty(apBills)) {
			Long enUU = SystemSession.getUser().getEnterprise().getUu();
			for (PurchaseAPBill apBill : apBills) {
				List<ApbillAdjustment> list = apbillAdjustmentDao.findByCustuuAndInoutno(enUU, apBill.getAb_code());
				if (!CollectionUtils.isEmpty(list)) {
					for (ApbillAdjustment adjust : list) {
						adjusts.add(adjust);
					}
				}
			}
		}
		return adjusts;
	}

	@Override
	public void nonPosting(List<ApbillAdjustment> adjustments) {
		if (!CollectionUtils.isEmpty(adjustments)) {
			for (ApbillAdjustment adjustment : adjustments) {
				if (adjustment.getSendstatus() != null) {
					// 已传输到供应商ERP，修改单据反过账状态
					if (adjustment.getSendstatus() == Status.DOWNLOADED.value()) {
						adjustment.setNonposting(Constant.YES);
						apbillAdjustmentDao.save(adjustment);
					}
				} else {
					// 未传输到供应商ERP，直接删除平台上的单据
					apbillAdjustmentDao.delete(adjustment);
				}
			}
		}
	}
}
