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

import com.uas.platform.b2b.dao.MakeOrderDao;
import com.uas.platform.b2b.dao.MakeReturnDao;
import com.uas.platform.b2b.dao.MakeReturnItemDao;
import com.uas.platform.b2b.erp.model.OrderDetailPrice;
import com.uas.platform.b2b.erp.model.ProdInOutRefreshPrice;
import com.uas.platform.b2b.erp.service.MakeService;
import com.uas.platform.b2b.model.MakeOrder;
import com.uas.platform.b2b.model.MakeReturn;
import com.uas.platform.b2b.model.MakeReturnItem;
import com.uas.platform.b2b.model.OrderType;
import com.uas.platform.b2b.search.SearchService;
import com.uas.platform.b2b.service.MakeReturnService;
import com.uas.platform.b2b.support.SystemSession;
import com.uas.platform.core.model.Constant;
import com.uas.platform.core.model.PageInfo;
import com.uas.platform.core.model.Status;
import com.uas.platform.core.persistence.criteria.PredicateUtils;
import com.uas.search.b2b.model.PageParams;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class MakeReturnServiceImpl implements MakeReturnService {

	@Autowired
	private MakeReturnItemDao makeReturnItemDao;

	@Autowired
	private MakeReturnDao makeReturnDao;

	@Autowired
	private MakeOrderDao makeOrderDao;

	@Autowired
	private SearchService searchService;

	@Autowired
    private MakeService makeService;

	@Override
	public void save(List<MakeReturnItem> returnItems) {
		returnItems = makeReturnItemDao.save(returnItems);
		// 关联订单的验退数量
		for (MakeReturnItem returnItem : returnItems) {
			MakeOrder makeOrders = returnItem.getOrder();
			List<MakeOrder> orders = makeOrderDao.findByEnUUAndCode(makeOrders.getEnUU(), makeOrders.getCode());
			if (orders.size() > 0) {
				MakeOrder order = orders.get(0);
				order.setReturnsqty((order.getReturnsqty() == null ? 0 : order.getReturnsqty()) + returnItem.getQty());
				makeOrderDao.save(order);
			}
		}
	}

	@Override
	public List<MakeReturn> findNotUpload() {
		return makeReturnDao.findByVendUUAndSendStatus(SystemSession.getUser().getEnterprise().getUu(),
				(short) Status.NOT_UPLOAD.value());
	}

	@Override
	public void onUploadSuccess(String[] idArray) {
		for (String id : idArray) {
			MakeReturn return1 = makeReturnDao.findOne(Long.parseLong(id));
			if (return1 != null) {
				return1.setSendStatus((short) Status.DOWNLOADED.value());
				makeReturnDao.save(return1);
			}
		}
	}

	@Override
	public List<MakeReturn> getNonPosting() {
		return makeReturnDao.findByVendUUAndNonPosting(SystemSession.getUser().getEnterprise().getUu(), Constant.YES);
	}

	@Override
	public void onNonPostingUploadSuccess(String[] idArray) {
		for (String id : idArray) {
			MakeReturn makeReturn = makeReturnDao.findOne(Long.parseLong(id));
			if (makeReturn != null) {
				makeReturnDao.delete(makeReturn);
			}
		}
	}

	@Override
	public void nonPosting(List<MakeReturn> makeReturns) {
		if (!CollectionUtils.isEmpty(makeReturns)) {
			for (MakeReturn makeReturn : makeReturns) {
				if (makeReturn.getSendStatus() == Status.DOWNLOADED.value()) {
					// 已传输到供应商ERP，修改单据反过账状态
					makeReturn.setNonPosting(Constant.YES);
					makeReturnDao.save(makeReturn);
				} else {
					// 未传输到供应商ERP，直接删除平台上的单据
					makeReturnDao.delete(makeReturn);
				}
				// 关联订单的验退数量
				if (!CollectionUtils.isEmpty(makeReturn.getReturnItems())) {
					for (MakeReturnItem returnItem : makeReturn.getReturnItems()) {
						List<MakeOrder> orders = makeOrderDao.findByEnUUAndCode(returnItem.getOrder().getEnUU(),
								returnItem.getOrder().getCode());
						if (orders.size() > 0) {
							MakeOrder order = orders.get(0);
							// 已接受数未空或小于本次验退单数目，设为0
							if (order.getReturnsqty() == null || order.getReturnsqty() < returnItem.getQty()) {
								order.setReturnsqty((double) 0);
							} else {// 否则减去本次的验收数量
								order.setReturnsqty(order.getReturnsqty() - returnItem.getQty());
							}
							makeOrderDao.save(order);
						}
					}
				}

			}
		}
	}

	@Override
	public Page<MakeReturn> findAllByPageInfo(final PageInfo pageInfo, final String keyword, final Long fromDate,
			final Long endDate) {
		if (StringUtils.hasText(keyword)) {
			List<Object> lists = new ArrayList<>();
			PageParams pageParams = new PageParams();
			ModelMap map = new ModelMap();
			map.put("mr_venduu", SystemSession.getUser().getEnterprise().getUu());
			pageParams.setFilters(map);
			for (MakeReturn list : searchService.searchMakeReturnIds(keyword, pageParams).getContent()) {
				lists.add(list.getId());
			}
			pageInfo.expression(PredicateUtils.in("id", lists, false));
		}
		if (fromDate != null) {
            pageInfo.expression(PredicateUtils.gte("date", new Date(fromDate), false));
        }
		if (endDate != null) {
            pageInfo.expression(PredicateUtils.lte("date", new Date(endDate), false));
        }
		Page<MakeReturn> pageOrders = makeReturnDao.findAll(new Specification<MakeReturn>() {
			@Override
            public Predicate toPredicate(Root<MakeReturn> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
				return query.where(pageInfo.getPredicates(root, query, builder)).getRestriction();
			}
		}, pageInfo);
		return pageOrders;
	}

	@Override
	public MakeReturn findById(Long id) {
		return makeReturnDao.findOne(id);
	}

	@Override
	public List<MakeReturnItem> convertPirceForProdIn(List<ProdInOutRefreshPrice> prodInOuts) {
		List<MakeReturnItem> items = new ArrayList<MakeReturnItem>();
        List<OrderDetailPrice> detailPriceList = new ArrayList<>();
		if (!CollectionUtils.isEmpty(prodInOuts)) {
			for (ProdInOutRefreshPrice prod : prodInOuts) {
				MakeReturnItem returnItem = makeReturnItemDao.findByEnUUAndCodeAndNumber(
						SystemSession.getUser().getEnterprise().getUu(), prod.getPbu_inoutno(), prod.getPbu_pdno());
				if (null != returnItem) {
					returnItem.setOrderPrice(prod.getPbu_orderprice());
					returnItem.setTaxrate(prod.getPbu_taxrate());
					items.add(returnItem);
					if (null != returnItem.getOrderId()) {
						detailPriceList.add(new OrderDetailPrice(returnItem.getOrderId(), returnItem.getOrderPrice(), returnItem.getTaxrate()));
					}
				}
			}
		}
        if (!CollectionUtils.isEmpty(detailPriceList)) {
            makeService.refreshPrice(detailPriceList, OrderType.makereturn.name());
        }
		return items;
	}
}
