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

import com.uas.platform.b2b.core.util.StringUtil;
import com.uas.platform.b2b.dao.EnterpriseDao;
import com.uas.platform.b2b.dao.MakeAcceptDao;
import com.uas.platform.b2b.dao.MakeOrderDao;
import com.uas.platform.b2b.dao.MakeReturnDao;
import com.uas.platform.b2b.erp.exception.ExceptionNote;
import com.uas.platform.b2b.erp.model.MakeProdInOut;
import com.uas.platform.b2b.erp.service.MakeProdInOutService;
import com.uas.platform.b2b.model.*;
import com.uas.platform.b2b.service.NotExistOrderService;
import com.uas.platform.b2b.support.SystemSession;
import com.uas.platform.core.model.Constant;
import org.apache.axis.utils.StringUtils;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

/**
 * 委外验收单
 *
 * @author hejq
 * @date 2018-07-03 10:39
 */
@Service
public class MakeProdInOutServiceImpl implements MakeProdInOutService {
	@Autowired
	private MakeAcceptDao makeAcceptDao;

	@Autowired
	private EnterpriseDao enterprisedao;

	@Autowired
	private MakeOrderDao makeOrderDao;

	@Autowired
	private MakeReturnDao makeReturnDao;

	@Autowired
	private NotExistOrderService orderService;

	/**
	 * 将ERP委外验收单，转为平台的客户委外验收单
	 * 
	 * @param prodInOuts
	 * @return
	 */
	@Override
	public List<MakeAcceptItem> convertProdInOuts(List<MakeProdInOut> prodInOuts) {
		List<MakeAcceptItem> acceptItems = new ArrayList<MakeAcceptItem>();
		long enUU = SystemSession.getUser().getEnterprise().getUu();
		for (MakeProdInOut prodInOut : prodInOuts) {
			MakeAccept accept = prodInOut.convent();
			List<MakeAccept> accept2 = makeAcceptDao.findByEnUUAndCode(enUU, accept.getCode());
			Enterprise ventor = enterprisedao.findEnterpriseByUu(accept.getVendUU());
			// 判断委外验收单和供应商UU是否存在
			if (accept2.size() == 0 && ventor != null) {
				List<NotExistOrders> ordersList = new ArrayList<>();
				String sign = "";
				for (Iterator<MakeAcceptItem> it = accept.getAcceptItems().iterator(); it.hasNext();) {
					MakeAcceptItem item = it.next();
					List<MakeOrder> makeOrders = makeOrderDao.findByEnUUAndCode(enUU, item.getOrder().getCode());
					// 验收对应的委外加工单存在
					if (makeOrders.size() > 0) {
						// 对应的加工单set进去
						item.setOrder(makeOrders.get(0));
						item.setOrderId(makeOrders.get(0).getId());
						// 设置主记录
						item.setAccept(accept);
						item.setErpDate(new Date());
						acceptItems.add(item);
					} else {
						if (StringUtils.isEmpty(sign)) {
							sign = StringUtil.uuid();
						}
						ordersList.add(new NotExistOrders(enUU, item.getOrder().getCode(),
                                com.uas.platform.b2b.temporary.model.OrderType.makeMain.name(), Constant.NO, sign));
					}
				}
				if (!CollectionUtils.isEmpty(ordersList)) {
                    orderService.batchSave(ordersList, ExceptionNote.MAKE_NOTFOUND.getPhrase(), sign);
                }
			}
		}
		return acceptItems;
	}

	@Override
	public List<MakeAccept> convertNonPostingProdInOuts(List<MakeProdInOut> prodInOuts) {
		List<MakeAccept> accepts = new ArrayList<MakeAccept>();
		if (!CollectionUtils.isEmpty(prodInOuts)) {
			Long enUU = SystemSession.getUser().getEnterprise().getUu();
			for (MakeProdInOut prodInOut : prodInOuts) {
				List<MakeAccept> existAccepts = makeAcceptDao.findByEnUUAndCode(enUU, prodInOut.getPi_inoutno());
				if (existAccepts.size() > 0) {
					accepts.add(existAccepts.get(0));
				}
			}
		}
		return accepts;
	}

	@Override
	public List<MakeReturnItem> convertReturns(List<MakeProdInOut> prodInOuts) {
		List<MakeReturnItem> returnItems = new ArrayList<MakeReturnItem>();
		long enUU = SystemSession.getUser().getEnterprise().getUu();
		for (MakeProdInOut prodInOut : prodInOuts) {
			MakeReturn returnn = prodInOut.conventToReturn();
			List<MakeReturn> returns2 = makeReturnDao.findByEnUUAndCode(enUU, returnn.getCode());
			Enterprise vendor = enterprisedao.findEnterpriseByUu(returnn.getVendUU());
			// 采购验收单不存在，供应商UU号存在对应供应商
			if (returns2.size() == 0 && vendor != null) {
                // 设置明细对应的采购单明细
                List<NotExistOrders> ordersList = new ArrayList<>();
                String sign = "";
				for (Iterator<MakeReturnItem> it = returnn.getReturnItems().iterator(); it.hasNext();) {
					MakeReturnItem returnItem = it.next();
					List<MakeOrder> makeOrders = makeOrderDao.findByEnUUAndCode(enUU, returnItem.getOrder().getCode());
                    // 对应的采购单存在
					if (makeOrders.size() > 0) {
                        // 对应的采购单明细set进去
						returnItem.setOrder(makeOrders.get(0));
						returnItem.setOrderId(makeOrders.get(0).getId());
                        // 设置主记录
						returnItem.setReturn(returnn);
						returnItem.setErpDate(new Date());
						returnItems.add(returnItem);
					} else {
					    if (StringUtils.isEmpty(sign)) {
					        sign = StringUtil.uuid();
                        }
                        ordersList.add(new NotExistOrders(enUU, returnItem.getOrder().getCode(),
                                com.uas.platform.b2b.temporary.model.OrderType.makeMain.name(), Constant.NO, sign));
					}
					if (!CollectionUtils.isEmpty(ordersList)) {
					    orderService.batchSave(ordersList, ExceptionNote.MAKE_NOTFOUND.getPhrase(), sign);
                    }
				}
			}
		}
		return returnItems;
	}

	@Override
	public List<MakeReturn> convertNonPostingReturns(List<MakeProdInOut> prodInOuts) {
		List<MakeReturn> returns = new ArrayList<MakeReturn>();
		if (!CollectionUtils.isEmpty(prodInOuts)) {
			Long enUU = SystemSession.getUser().getEnterprise().getUu();
			for (MakeProdInOut prodInOut : prodInOuts) {
				List<MakeReturn> existReturns = makeReturnDao.findByEnUUAndCode(enUU, prodInOut.getPi_inoutno());
				if (existReturns.size() > 0) {
					returns.add(existReturns.get(0));
				}
			}
		}
		return returns;
	}

	/**
	 * 获取委外验收单对应的B2Bid
	 *
	 * @param prodInOuts erp委外验收单
	 * @return
	 */
	@Override
	public List<MakeProdInOut> getMakeAcceptB2bId(List<MakeProdInOut> prodInOuts) {
		for (MakeProdInOut inOut : prodInOuts) {
			List<MakeAccept> accepts = makeAcceptDao.findByEnUUAndErpId(SystemSession.getUser().getEnterprise().getUu(), inOut.getPi_id());
			if (!CollectionUtils.isEmpty(accepts)) {
                inOut.setPi_b2b_id(accepts.get(0).getId());
			}
		}
		return prodInOuts;
	}

    /**
     * 获取委外验退单对应的B2Bid
     *
     * @param prodInOuts erp委外验退单
     * @return
     */
    @Override
    public List<MakeProdInOut> getMakeReturnB2bId(List<MakeProdInOut> prodInOuts) {
        for (MakeProdInOut inOut : prodInOuts) {
            List<MakeReturn> returns = makeReturnDao.findByEnUUAndErpId(SystemSession.getUser().getEnterprise().getUu(), inOut.getPi_id());
            if (!CollectionUtils.isEmpty(returns)) {
                inOut.setPi_b2b_id(returns.get(0).getId());
            }
        }
        return prodInOuts;
    }
}
