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

import com.uas.platform.b2b.dao.PurchaseNoticeDao;
import com.uas.platform.b2b.dao.PurchaseOrderItemDao;
import com.uas.platform.b2b.dao.SaleSendItemDao;
import com.uas.platform.b2b.dao.SaleSendItemVerifyDao;
import com.uas.platform.b2b.erp.model.AcceptNotify;
import com.uas.platform.b2b.erp.model.AcceptNotifyConfirm;
import com.uas.platform.b2b.erp.model.AcceptNotifyVerify;
import com.uas.platform.b2b.erp.model.PurchaseNotify;
import com.uas.platform.b2b.erp.service.PurchaseNotifyService;
import com.uas.platform.b2b.model.*;
import com.uas.platform.b2b.support.SystemSession;
import com.uas.platform.core.model.Status;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;

@Service
public class PurchaseNotifyServiceImpl implements PurchaseNotifyService {

	@Autowired
	private PurchaseOrderItemDao purchaseOrderItemDao;
	@Autowired
	private PurchaseNoticeDao purchaseNoticeDao;
	@Autowired
	private SaleSendItemDao saleSendItemDao;
	@Autowired
	private SaleSendItemVerifyDao saleSendItemVerifyDao;

	@Override
	public List<PurchaseNotice> convertPurchaseNotify(List<PurchaseNotify> notifies) {
		List<PurchaseNotice> notices = new ArrayList<PurchaseNotice>();
		for (PurchaseNotify notify : notifies) {
			PurchaseNotice notice = notify.convert();
			List<PurchaseNotice> existNotices = purchaseNoticeDao.findByEnUUAndSourceId(notice.getEnUU(),
					notice.getSourceId());
			if (CollectionUtils.isEmpty(existNotices)) {// sourceId不存在新增保存
				List<Long> idList = purchaseOrderItemDao.findIdByEnUUAndOrderCodeAndNumber(notice.getEnUU(),
                        notice.getOrderItem().getOrder().getCode(), notice.getOrderItem().getNumber());
				if (!CollectionUtils.isEmpty(idList)) {
					notice.setOrderItemId(idList.get(0));
					notices.add(notice);
				}
			} else {// 对现有的单据，修改
				PurchaseNotice existNotice = existNotices.get(0);
				SimpleDateFormat dateFormat = new SimpleDateFormat("MM月dd日");
				String dateString = dateFormat.format(new Date());
				String remark = "";
				if (StringUtils.hasText(existNotice.getRemark())) {
					remark = existNotice.getRemark() + "； ";
				}
				existNotice.setSendStatus((short) Status.NOT_UPLOAD.value());// 对卖家传输状态 // 待上传
				if (existNotice.getQty() != null && !existNotice.getQty().equals(notice.getQty())) {
					if (existNotice.getEndQty() > notice.getQty()) {
						// 已发货数大于新的需求数，修改平台上的需求数为已发货数，将已发货数量传回买家ERP修改发货提醒的数量
						existNotice.setRemark(remark + dateString + "修改需求数量，" + existNotice.getQty() + " -> "
								+ existNotice.getEndQty());
						existNotice.setQty(existNotice.getEndQty());// 需求数量
						existNotice.setStatus((short) Status.REPLIED.value());// 状态  已回复
						notices.add(existNotice);
					} else {
						// 已发货数小于或等于新的需求数，修改平台上的需求数为新的需求数
						existNotice.setRemark(
								remark + dateString + "修改需求数量，" + existNotice.getQty() + " -> " + notice.getQty());
						existNotice.setQty(notice.getQty());// 需求数量
						existNotice.setDelivery(notice.getDelivery());// 交期
						notices.add(existNotice);

					}
				} else {
					String existDeliveryStr = "空";
					String deliveryStr = "空";
					if (existNotice.getDelivery() != null) {
						existDeliveryStr = dateFormat.format(existNotice.getDelivery());
					}
					if (notice.getDelivery() != null) {
						deliveryStr = dateFormat.format(notice.getDelivery());
					}
					if (!existDeliveryStr.equals(deliveryStr)) {
						existNotice.setRemark(remark + dateString + "修改交期，" + existDeliveryStr + " -> " + deliveryStr);
					}
					existNotice.setDelivery(notice.getDelivery());// 交期
					notices.add(existNotice);
				}
			}
		}
		return notices;
	}

	/**
	 * 将平台的发货提醒封装成ERP系统的发货提醒
	 *
	 * @param noticeList 平台发货提醒
	 * @return
	 */
	@Override
	public List<PurchaseNotify> convertPurchaseNotice(List<PurchaseNotice> noticeList) {
		List<PurchaseNotify> notifyList = new ArrayList<>();
		for (PurchaseNotice notice : noticeList) {
            notifyList.add(new PurchaseNotify(notice));
		}
		return notifyList;
	}


	@Override
	public List<List<PurchaseNotice>> convertEDIPurchaseNotify(List<PurchaseNotify> notifies, Long enUU) {
		List<List<PurchaseNotice>> allNotices = new ArrayList<List<PurchaseNotice>>();
		List<PurchaseNotice> notices = new ArrayList<PurchaseNotice>();
		List<PurchaseNotice> oppNotices = new ArrayList<PurchaseNotice>();
		for (PurchaseNotify notify : notifies) {
			PurchaseNotice notice = notify.convertEDI(enUU);
			List<PurchaseNotice> existNotices = purchaseNoticeDao.findByEnUUAndSourceId(enUU,
					notice.getSourceId());
			if (CollectionUtils.isEmpty(existNotices)) {// sourceId不存在新增保存
				List<PurchaseOrderItem> orderItems = purchaseOrderItemDao.findByEnUUAndOrderCodeAndNumber(
						notice.getEnUU(), notice.getOrderItem().getOrder().getCode(),
						notice.getOrderItem().getNumber());
				if (!CollectionUtils.isEmpty(orderItems)) {
					notice.setOrderItem(orderItems.get(0));
					notice.setOrderItemId(notice.getOrderItem().getId());
					notices.add(notice);
				}
			} else {// 对现有的单据，修改
				PurchaseNotice existNotice = existNotices.get(0);
				SimpleDateFormat dateFormat = new SimpleDateFormat("MM月dd日");
				String dateString = dateFormat.format(new Date());
				String remark = "";
				if (StringUtils.hasText(existNotice.getRemark())) {
					remark = existNotice.getRemark() + "； ";
				}
				existNotice.setSendStatus((short) Status.NOT_UPLOAD.value());// 对卖家传输状态
				// 待上传
				if (existNotice.getQty() != null && !existNotice.getQty().equals(notice.getQty())) {
					if (existNotice.getEndQty() > notice.getQty()) {
						// 已发货数大于新的需求数，修改平台上的需求数为已发货数，将已发货数量传回买家ERP修改发货提醒的数量
						existNotice.setRemark(remark + dateString + "修改需求数量，" + existNotice.getQty() + " -> "
								+ existNotice.getEndQty());
						existNotice.setQty(existNotice.getEndQty());// 需求数量
						existNotice.setStatus((short) Status.REPLIED.value());// 状态
						// 已回复
						oppNotices.add(existNotice);
						notices.add(existNotice);
					} else {
						// 已发货数小于或等于新的需求数，修改平台上的需求数为新的需求数
						existNotice.setRemark(
								remark + dateString + "修改需求数量，" + existNotice.getQty() + " -> " + notice.getQty());
						existNotice.setQty(notice.getQty());// 需求数量
						existNotice.setDelivery(notice.getDelivery());// 交期
						notices.add(existNotice);
					}
				} else {
					String existDeliveryStr = "空";
					String deliveryStr = "空";
					if (existNotice.getDelivery() != null) {
						existDeliveryStr = dateFormat.format(existNotice.getDelivery());
					}
					if (notice.getDelivery() != null) {
						deliveryStr = dateFormat.format(notice.getDelivery());
					}
					if (!existDeliveryStr.equals(deliveryStr)) {
						existNotice.setRemark(remark + dateString + "修改交期，" + existDeliveryStr + " -> " + deliveryStr);
					}
					existNotice.setDelivery(notice.getDelivery());// 交期
					notices.add(existNotice);
				}
			}
		}
		allNotices.add(notices);
		allNotices.add(oppNotices);
		return allNotices;
	}

	@Override
	public List<AcceptNotify> convertSaleSend(List<SaleSend> sends) {
		List<AcceptNotify> accepts = new ArrayList<AcceptNotify>();
		for (SaleSend send : sends) {
            accepts.add(new AcceptNotify(send));
        }
		return accepts;
	}

	@Override
	public List<SaleSendItem> convertAcceptNotify(List<AcceptNotify> accepts) {
		List<SaleSendItem> sendItems = new ArrayList<SaleSendItem>();
		for (AcceptNotify accept : accepts) {
			SaleSend send = accept.convert();
			Set<SaleSendItem> items = send.getSendItems();
			if (!CollectionUtils.isEmpty(items)) {
				for (SaleSendItem item : items) {
					item.setSend(send);
					PurchaseNotice notice = item.getNotice();
					List<PurchaseNotice> notices = purchaseNoticeDao.findByEnUUAndSourceId(notice.getEnUU(),
							notice.getSourceId());
					if (!CollectionUtils.isEmpty(notices)) {
						item.setNotice(notices.get(0));
						item.setNoticeId(item.getNotice().getId());
						sendItems.add(item);
					}
				}
			}
		}
		return sendItems;
	}

	@Override
	public List<SaleSendItem> convertAcceptNotifyDetail(List<AcceptNotifyConfirm> confirms) {
		List<SaleSendItem> sendItems = new ArrayList<SaleSendItem>();
		for (AcceptNotifyConfirm confirm : confirms) {
			List<SaleSendItem> items = saleSendItemDao.findBySendAndNumber(confirm.getB2b_ss_id(),
					confirm.getAnd_detno());
			if (items.size() > 0) {
				SaleSendItem item = items.get(0);
				item.modify(item.getQty(), confirm.getAnd_inqty());
				sendItems.add(item);
			}
		}
		return sendItems;
	}

	/**
	 * 转收料单，增加客户收料数量
	 */
	@Override
	public List<SaleSendItemVerify> convertAcceptNotifyVerify(List<AcceptNotifyVerify> verifies) {
		List<SaleSendItemVerify> sendItemVerifies = new ArrayList<SaleSendItemVerify>();
		for (AcceptNotifyVerify verify : verifies) {
			List<SaleSendItemVerify> verifies2 = saleSendItemVerifyDao
					.findByCustUUAndSourceId(SystemSession.getUser().getEnterprise().getUu(), verify.getVad_id());
			if (verifies2.size() == 0) {
				SaleSendItemVerify sendItemVerify = verify.convert();
				List<SaleSendItem> items = saleSendItemDao.findBySendAndNumber(verify.getB2b_ss_id(),
						verify.getAnd_detno());
				if (items.size() > 0) {
					sendItemVerify.setSendItemId(items.get(0).getId());
					sendItemVerifies.add(sendItemVerify);
				}
			}
		}
		return sendItemVerifies;
	}

	/**
	 * 收料单反审核，减少客户收料数量
	 */
	@Override
	public List<SaleSendItemVerify> convertAcceptUnauditVerify(List<AcceptNotifyVerify> verifies) {
		List<SaleSendItemVerify> sendItemVerifies = new ArrayList<SaleSendItemVerify>();
		for (AcceptNotifyVerify verify : verifies) {
			List<SaleSendItemVerify> itemVerifies = saleSendItemVerifyDao
					.findByCustUUAndSourceId(SystemSession.getUser().getEnterprise().getUu(), verify.getVad_id());
			if (itemVerifies.size() > 0) {
				sendItemVerifies.add(itemVerifies.get(0));
			}
		}
		return sendItemVerifies;
	}

	/**
	 * 通过上传的送货提醒id查询平台对应的id
	 *
	 * @param notifyList 送货提醒
	 * @return
	 */
	@Override
	public List<PurchaseNotify> getB2bId(List<PurchaseNotify> notifyList) {
	    for (PurchaseNotify notify : notifyList) {
            List<PurchaseNotice> noticeList = purchaseNoticeDao.findByEnUUAndSourceId(SystemSession.getUser().getEnterprise().getUu(), notify.getPn_id());
            if (!CollectionUtils.isEmpty(noticeList)) {
                notify.setPn_b2bid(noticeList.get(0).getId());
            }
        }
		return notifyList;
	}

	/**
	 * 通过已经保存的notice获取notify的b2bId
	 * @param notices
	 * @return
	 */
	@Override
	public List<PurchaseNotify> getB2bIdByNotices(List<PurchaseNotice> notices) {
		List<PurchaseNotify> purchaseNotifies = new ArrayList<PurchaseNotify>();
		if (CollectionUtils.isNotEmpty(notices)) {
			for (PurchaseNotice notice : notices) {
				PurchaseNotify purchaseNotify = new PurchaseNotify();
				purchaseNotify.setPn_b2bid(notice.getId());
				purchaseNotify.setPn_id(notice.getSourceId());
				purchaseNotify.setVe_uu(notice.getVendUU());
				purchaseNotifies.add(purchaseNotify);
			}
		}
		return purchaseNotifies;
	}
}
