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

import com.uas.platform.b2b.core.util.ContextUtils;
import com.uas.platform.b2b.dao.*;
import com.uas.platform.b2b.erp.model.Inquiry;
import com.uas.platform.b2b.event.SaleQuotationDecideReleaseEvent;
import com.uas.platform.b2b.event.SaleQuotationInvalidReleaseEvent;
import com.uas.platform.b2b.model.*;
import com.uas.platform.b2b.ps.service.PersonalProductService;
import com.uas.platform.b2b.service.SaleQuotationService;
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.SPage;
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.util.CollectionUtils;

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 SaleQuotationServiceImpl implements SaleQuotationService {

	@Autowired
	private SaleQuotationItemDao saleQuotationItemDao;

	@Autowired
	private SaleQuotationDao saleQuotationDao;

	@Autowired
	private SaleQuotationDoneDao saleQuotationDoneDao;

	@Autowired
    private PersonalProductService personalProductService;

	@Override
	public void save(List<SaleQuotationItem> items) {
		saleQuotationItemDao.save(items);
	}

	@Override
	public List<SaleQuotation> findNotUploadQuotation() {
		return saleQuotationDao.findByCustUUAndSendStatus(SystemSession.getUser().getEnterprise().getUu(),
				(short) Status.NOT_UPLOAD.value());
	}

	@Override
	public void onQuotationUploadSuccess(String[] idArray) {
		List <SaleQuotation> saveList = new ArrayList<>();
		for (String id : idArray) {
			SaleQuotation quotation = saleQuotationDao.findOne(Long.parseLong(id));
			if (quotation != null) {
				quotation.setSendStatus((short) Status.DOWNLOADED.value());
				saveList.add(quotation);
			}
		}
		saleQuotationDao.save(saveList);
	}

	@Override
	public void onReplyDecide(List<SaleQuotationItem> quotationItems) {
		if (!CollectionUtils.isEmpty(quotationItems)) {
			saleQuotationItemDao.save(quotationItems);
			saleQuotationDao.save(quotationItems.get(0).getQuotation());
			ContextUtils.publishEvent(new SaleQuotationDecideReleaseEvent(quotationItems));
		}
	}

	@Override
	public List<SaleQuotationItem> findNotUploadQuotationDecide() {
		return saleQuotationItemDao.findByEnUUAndDecideStatus(SystemSession.getUser().getEnterprise().getUu(),
				(short) Status.NOT_UPLOAD.value());
	}

	@Override
	public void onQuotationDecideDownSuccess(String[] idArray) {
		for (String id : idArray) {
			SaleQuotationItem quotationItem = saleQuotationItemDao.findOne(Long.parseLong(id));
			if (quotationItem != null) {
				quotationItem.setDecideStatus((short) Status.DOWNLOADED.value());
				saleQuotationItemDao.save(quotationItem);
			}
		}
	}

	@Override
	public SaleQuotationItem save(SaleQuotationItem item) {
		if(item.getQuotation().getStatus() == Status.SUBMITTED.value()) {// 已提交
			item.getQuotation().setSendStatus((short) Status.NOT_UPLOAD.value());
			item.getQuotation().setBackStatus((short) Status.NOT_UPLOAD.value());
		}
		item.getQuotation().setDate(new Date());
		item.getQuotation().setEnUU(SystemSession.getUser().getEnterprise().getUu());
		item.getQuotation().setUserUU(SystemSession.getUser().getUserUU());
		item.setNumber((short) 1);
		SaleQuotationItem newItem = saleQuotationItemDao.save(item);
		List<SaleQuotationItem> list = new ArrayList<SaleQuotationItem>();
		list.add(newItem);
        // 更新我的物料库信息
		personalProductService.covertPersonalProduct(item.getProductId(), "主动报价");
		return newItem;
	}

	@Override
	public List<SaleQuotation> findNotBackQuotation() {
		return saleQuotationDao.findByEnUUAndStatusAndBackStatus(SystemSession.getUser().getEnterprise().getUu(),
				(short) Status.SUBMITTED.value(), (short) Status.NOT_UPLOAD.value());
	}

	@Override
	public void onQuotationBackSuccess(String[] idArray) {
		for (String id : idArray) {
			SaleQuotation quotation = saleQuotationDao.findOne(Long.parseLong(id));
			if (quotation != null) {
				quotation.setBackStatus((short) Status.DOWNLOADED.value());
				saleQuotationDao.save(quotation);
			}
		}
	}

	@Override
	public void onReplyInvalid(List<Inquiry> inquiries) {
		List<SaleQuotation> saveQuotations = new ArrayList<>();
		for (Inquiry inquiry : inquiries) {
			if (inquiry.getB2b_qu_id() != null) {
				SaleQuotation quotation = saleQuotationDao.findOne(inquiry.getB2b_qu_id());
				quotation.setStatus((short)Status.DISABLED.value());
				quotation.setOverdue(Constant.YES);// 设置成失效状态
				quotation.setInvalidSendStatus((short) Status.NOT_UPLOAD.value()); // 获取作废信息时，更新SAAS作废上传状态为待上传
				saveQuotations.add(quotation);
			}
		}
		ContextUtils.publishEvent(new SaleQuotationInvalidReleaseEvent(saveQuotations));
		saleQuotationDao.save(saveQuotations);
	}

	@Override
	public List<SaleQuotation> findNotUploadQuotationReplyInvalid() {
		return saleQuotationDao.findByEnUUAndInvalidSendStatus(SystemSession.getUser().getEnterprise().getUu(),
				(short) Status.NOT_UPLOAD.value());
	}

	@Override
	public void onReplyInvalidDownSuccess(String[] ids) {
		List<SaleQuotation> saveQuotations = new ArrayList<>();
		for (String id : ids) {
			SaleQuotation quotation = saleQuotationDao.findOne(Long.parseLong(id));
			if (quotation != null) {
				quotation.setInvalidSendStatus((short) Status.DOWNLOADED.value());
				saveQuotations.add(quotation);
			}
		}
		saleQuotationDao.save(saveQuotations);
	}

	@Override
	public void check(Long[] ids) {
		for (Long id : ids) {
			SaleQuotation quotation = saleQuotationDao.findOne(id);
			if (quotation != null) {
				quotation.setStatus((short) Status.UNAUDIT.value());
				saleQuotationDao.save(quotation);
			}
		}
	}

	@Override
	public void recheck(Long[] ids) {
		for (Long id : ids) {
			SaleQuotation quotation = saleQuotationDao.findOne(id);
			if (quotation != null) {
				quotation.setStatus((short) Status.INPUTTING.value());
				saleQuotationDao.save(quotation);
			}
		}
	}

	@Override
	public SPage<SaleQuotationDone> findDoneByPageInfo(final PageInfo pageInfo, SearchFilter filter) {
		SPage<SaleQuotationDone> quos = new SPage<SaleQuotationDone>();
		if (filter != null) {
			if (!CollectionUtils.isEmpty(filter.getDistribute())) {
                pageInfo.expression(PredicateUtils.in("custUU", 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));
            }
		}
		Page<SaleQuotationDone> quotations = saleQuotationDoneDao.findAll(new Specification<SaleQuotationDone>() {
			@Override
            public Predicate toPredicate(Root<SaleQuotationDone> root, CriteriaQuery<?> query,
                                         CriteriaBuilder builder) {
				return query.where(pageInfo.getPredicates(root, query, builder)).getRestriction();
			}
		}, pageInfo);
		quos.setContent(quotations.getContent());
		quos.setPage(quotations.getNumber());
		quos.setSize(quotations.getSize());
		quos.setTotalElement(quotations.getTotalElements());
		quos.setTotalPage(quotations.getTotalPages());
		return quos;
	}

}
