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

import com.uas.platform.b2b.dao.PurchaseApCheckDao;
import com.uas.platform.b2b.erp.model.APCheck;
import com.uas.platform.b2b.erp.service.APCheckService;
import com.uas.platform.b2b.model.PurchaseApCheck;
import com.uas.platform.b2b.model.PurchaseApCheckItem;
import com.uas.platform.core.exception.IllegalStatusException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

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

@Service
public class APCheckServiceImpl implements APCheckService {

	@Autowired
	private PurchaseApCheckDao purchaseAPCheckDao;

	@Override
	public List<APCheck> convertApCheck(List<PurchaseApCheck> apCheck) {
		List<APCheck> APChecks = new ArrayList<APCheck>();
		for (PurchaseApCheck order : apCheck) {
            APChecks.add(new APCheck(order));
        }
		return APChecks;
	}

	@Override
	public List<PurchaseApCheckItem> convertAPChecks(List<APCheck> apChecks) {
		List<PurchaseApCheckItem> apCheckItems = new ArrayList<PurchaseApCheckItem>();
		if (!CollectionUtils.isEmpty(apChecks)) {
			for (APCheck apCheck : apChecks) {
				PurchaseApCheck apcheckb2b = purchaseAPCheckDao.findOne(apCheck.getAc_b2bid());
				if (null != apcheckb2b) {// 客户UU正确，否则不保存
					apcheckb2b.setCheckStatus(apCheck.getAc_confirmstatus());
					apcheckb2b.setCustreply(apCheck.getAc_reason());
					apcheckb2b.setReason(apCheck.getAc_reason());
					if (apCheck.getAc_code() != null && apcheckb2b.getStatus() == 203) {
						if (apCheck.getAc_confirmstatus().equals("未对账")) {
							throw new IllegalStatusException("已提交，不能重复提交");
						} else if (apCheck.getAc_confirmstatus().equals("已确认")) {
							for (PurchaseApCheckItem exitItem : apcheckb2b.getItems()) {
								exitItem.setCustCheckQty(exitItem.getCheckQty());
								exitItem.setApCheck(apcheckb2b);
								apCheckItems.add(exitItem);
							}
						} else if (apCheck.getAc_confirmstatus().equals("不同意")) {
							for (PurchaseApCheckItem exitItem : apcheckb2b.getItems()) {
								exitItem.setApCheck(apcheckb2b);
								Double custQty = exitItem.getCustCheckQty() - exitItem.getCheckQty();
                                exitItem.setCustCheckQty(custQty);
								apCheckItems.add(exitItem);
							}
						}
					}
				}
			}
		}
		return apCheckItems;
	}

}
