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

import com.uas.platform.b2b.dao.PurchaseBadOutDao;
import com.uas.platform.b2b.dao.PurchaseBadOutItemDao;
import com.uas.platform.b2b.model.PurchaseBadOut;
import com.uas.platform.b2b.model.PurchaseBadOutItem;
import com.uas.platform.b2b.model.SearchFilter;
import com.uas.platform.b2b.search.SearchService;
import com.uas.platform.b2b.service.PurchaseBadOutService;
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 PurchaseBadOutServiceImpl implements PurchaseBadOutService {

	@Autowired
	private PurchaseBadOutDao purchaseBadOutDao;

	@Autowired
	private PurchaseBadOutItemDao purchaseBadOutItemDao;

	@Autowired
	private SearchService searchService;

	@Override
	public void save(List<PurchaseBadOutItem> badOutItems) {
		purchaseBadOutItemDao.save(badOutItems);
	}

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

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

	@Override
	public Page<PurchaseBadOut> findAllByPageInfo(final PageInfo pageInfo, final String keyword,
			final SearchFilter filter) {
		return purchaseBadOutDao.findAll(new Specification<PurchaseBadOut>() {

			@Override
            public Predicate toPredicate(Root<PurchaseBadOut> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
				if (filter != null) {
					if (!CollectionUtils.isEmpty(filter.getDistribute())) {
                        pageInfo.expression(PredicateUtils.in("enUU", filter.getDistribute(), false));
                    }
					if (filter.getFromDate() != null) {
                        pageInfo.expression(PredicateUtils.gte("date", new Date(filter.getFromDate()), false));
                    }
					if (filter.getEndDate() != null) {
						pageInfo.expression(PredicateUtils.lte("date", new Date(filter.getEndDate()), false));
					}
				}
				if (StringUtils.hasText(keyword)) {
					List<Object> lists = new ArrayList<>();
					PageParams pageParams = new PageParams();
					ModelMap map = new ModelMap();
					map.put("po_venduu", SystemSession.getUser().getEnterprise().getUu());
					pageParams.setFilters(map);
					for (PurchaseBadOut list : searchService.searchPurchaseBadOutIds(keyword, pageParams).getContent()) {
						lists.add(list.getId());
					}
					pageInfo.expression(PredicateUtils.in("id", lists, false));
				}

				return query.where(pageInfo.getPredicates(root, query, builder)).getRestriction();
			}
		}, pageInfo);
	}

	@Override
	public PurchaseBadOut findById(Long id) {
		return purchaseBadOutDao.findOne(id);
	}

	@Override
	public void nonPosting(List<PurchaseBadOut> badOuts) {
		for (PurchaseBadOut badOut : badOuts) {
			if (badOut.getSendStatus() == Status.DOWNLOADED.value()) {
				// 已传输到供应商ERP，修改单据反过账状态
				badOut.setNonPosting(Constant.YES);
				purchaseBadOutDao.save(badOut);
			} else {
				// 未传输到供应商ERP，直接删除平台上的单据
				purchaseBadOutDao.delete(badOut);
			}
		}
	}

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

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