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

import com.uas.platform.b2b.dao.PurchaseBadInDao;
import com.uas.platform.b2b.dao.PurchaseBadInItemDao;
import com.uas.platform.b2b.model.PurchaseBadIn;
import com.uas.platform.b2b.model.PurchaseBadInItem;
import com.uas.platform.b2b.model.SearchFilter;
import com.uas.platform.b2b.search.SearchService;
import com.uas.platform.b2b.service.PurchaseBadInService;
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 PurchaseBadInServiceImpl implements PurchaseBadInService {

	@Autowired
	private PurchaseBadInItemDao purchaseBadInItemDao;

	@Autowired
	private PurchaseBadInDao purchaseBadInDao;

	@Autowired
	private SearchService searchService;

	@Override
	public void save(List<PurchaseBadInItem> badInItems) {
		purchaseBadInItemDao.save(badInItems);
	}

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

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

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

			@Override
            public Predicate toPredicate(Root<PurchaseBadIn> 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("pb_venduu", SystemSession.getUser().getEnterprise().getUu());
					pageParams.setFilters(map);
					for (PurchaseBadIn list : searchService.searchPurchaseBadInIds(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 PurchaseBadIn findById(Long id) {
		return purchaseBadInDao.findOne(id);
	}

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

	}

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

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