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

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

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 com.uas.platform.b2b.dao.EnterpriseDao;
import com.uas.platform.b2b.dao.PurchaseOrderChangeDao;
import com.uas.platform.b2b.dao.PurchaseOrderChangeItemDao;
import com.uas.platform.b2b.dao.PurchaseOrderDao;
import com.uas.platform.b2b.dao.PurchaseOrderItemDao;
import com.uas.platform.b2b.erp.model.SaleDownChangeReply;
import com.uas.platform.b2b.model.PurchaseOrder;
import com.uas.platform.b2b.model.PurchaseOrderChange;
import com.uas.platform.b2b.model.PurchaseOrderChangeItem;
import com.uas.platform.b2b.service.PurchaseOrderChangeService;
import com.uas.platform.b2b.support.SystemSession;
import com.uas.platform.b2b.support.XingePusher;
import com.uas.platform.core.model.PageInfo;
import com.uas.platform.core.model.Status;

@Service
public class PurchaseOrderChangeServiceImpl implements PurchaseOrderChangeService {

	@Autowired
	private PurchaseOrderChangeDao purchaseOrderChangeDao;

	@Autowired
	private PurchaseOrderChangeItemDao purchaseOrderChangeItemDao;

	@Autowired
	private EnterpriseDao enterpriseDao;

	@Autowired
	private PurchaseOrderDao purchaseOrderDao;
	@Autowired
	private PurchaseOrderItemDao purchaseOrderItemDao;

	@Override
	public void save(List<PurchaseOrderChangeItem> changeItems) {
		purchaseOrderChangeItemDao.save(changeItems);
		// 将采购变更单信息推送通知供应商联系人UU号
		Set<Long> orderId = new HashSet<Long>();
		for (PurchaseOrderChangeItem orderItem : changeItems) {
			if (!orderId.contains(orderItem.getOrderChange().getId())) {
				PurchaseOrder order = orderItem.getOrderChange().getOrder();
				if (order.getVendUserUU() != null) {
					// Android
					XingePusher.pushSingleAccountAndroid(order.getVendUserUU().toString(), "新增一条客户采购变更单-", "单号:"
							+ orderItem.getOrderChange().getCode() + ",客户:" + order.getEnterprise().getEnName(),
							"com.sas.mobile.activity.PurchaseChangeActivity");
					// IOS
					XingePusher.pushSingleAccountIOS(order.getVendUserUU().toString(), "新增一条客户采购变更单-" + "单号:"
							+ orderItem.getOrderChange().getCode() + ",客户:" + order.getEnterprise().getEnName());
				}
				orderId.add(orderItem.getOrderChange().getId());
				// 买家直接批准变更，无需卖家确认的情况下，直接变更平台的客户采购单
				if (orderItem.getOrderChange().isAgreed())
					changeOrder(orderItem.getOrderChange());
			}
		}
	}

	@Override
	public List<PurchaseOrderChange> findNotUploadReply() {
		return purchaseOrderChangeDao.findByEnUUAndStatusAndBackStatus(SystemSession.getUser().getEnterprise().getUu(),
				(short) Status.REPLIED.value(), (short) Status.NOT_UPLOAD.value());
	}

	@Override
	public void onReplyUploadSuccess(String[] idArray) {
		for (String id : idArray) {
			PurchaseOrderChange change = purchaseOrderChangeDao.findOne(Long.parseLong(id));
			if (change != null) {
				change.setBackStatus((short) Status.DOWNLOADED.value());
				purchaseOrderChangeDao.save(change);
				// 变更信息反馈到客户采购单
				changeOrder(change);
			}
		}
	}

	/**
	 * 变更信息反馈到客户采购单
	 * 
	 * @param change
	 */
	private void changeOrder(PurchaseOrderChange change) {
		purchaseOrderDao.save(change.convert());
		if (!CollectionUtils.isEmpty(change.getOrderChangeItems())) {
			for (PurchaseOrderChangeItem changeItem : change.getOrderChangeItems())
				purchaseOrderItemDao.save(changeItem.convert());
		}
	}

	@Override
	public List<PurchaseOrderChange> findNotUploadOrderChange() {
		return purchaseOrderChangeDao.findByVendUUAndSendStatus(SystemSession.getUser().getEnterprise().getUu(),
				(short) Status.NOT_UPLOAD.value());
	}

	@Override
	public void onSaleDownChangeSuccess(String[] idArray) {
		for (String id : idArray) {
			PurchaseOrderChange order = purchaseOrderChangeDao.findOne(Long.parseLong(id));
			if (order != null) {
				order.setSendStatus((short) Status.DOWNLOADED.value());
				purchaseOrderChangeDao.save(order);
			}
		}
	}

	@Override
	public void reply(List<SaleDownChangeReply> replies) {
		for (SaleDownChangeReply reply : replies) {
			PurchaseOrderChange orderChange = purchaseOrderChangeDao.findOne(reply.getB2b_pc_id());
			if (orderChange != null) {
				orderChange.setAgreed(reply.getSc_agreed());
				orderChange.setReplyRemark(reply.getSc_replyremark());
				orderChange.setReplySendStatus((short) Status.DOWNLOADED.value());
				reply(orderChange, false);
			}
		}
	}

	@Override
	public List<PurchaseOrderChange> findNotSendReply() {
		return purchaseOrderChangeDao.findByVendUUAndStatusAndReplySendStatus(SystemSession.getUser().getEnterprise().getUu(),
				(short) Status.REPLIED.value(), (short) Status.NOT_UPLOAD.value());
	}

	@Override
	public void onSaleDownChangeReplySuccess(String[] idArray) {
		for (String id : idArray) {
			PurchaseOrderChange change = purchaseOrderChangeDao.findOne(Long.parseLong(id));
			if (change != null) {
				change.setReplySendStatus((short) Status.DOWNLOADED.value());
				purchaseOrderChangeDao.save(change);
			}
		}
	}

	@Override
	public Page<PurchaseOrderChange> findAllByPageInfo(final PageInfo pageInfo) {
		return purchaseOrderChangeDao.findAll(new Specification<PurchaseOrderChange>() {

			public Predicate toPredicate(Root<PurchaseOrderChange> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
				query.where(pageInfo.getPredicates(root, query, builder));
				return null;
			}
		}, pageInfo);
	}

	@Override
	public void reply(PurchaseOrderChange change) {
		reply(change, true);
	}

	/**
	 * @param change
	 * @param isB2b
	 *            是否在平台操作
	 */
	private void reply(PurchaseOrderChange change, boolean isB2b) {
		PurchaseOrderChange orderChange = purchaseOrderChangeDao.findOne(change.getId());
		orderChange.setStatus((short) Status.REPLIED.value());
		orderChange.setAgreed(change.getAgreed());
		orderChange.setReplyRemark(change.getReplyRemark());
		orderChange.setReplySendStatus(change.getReplySendStatus());
		if (isB2b)
			orderChange.setReplySendStatus((short) Status.NOT_UPLOAD.value());
		purchaseOrderChangeDao.save(orderChange);
		PurchaseOrder order = orderChange.getOrder();
		// 将回复信息推送给采购企业采购员（或管理员）
		if (order.getUserUU() != null) {
			// Android
			XingePusher.pushSingleAccountAndroid(order.getUserUU().toString(), "新增采购变更单回复", "单号:" + order.getCode() + ",供应商:"
					+ enterpriseDao.findOne(order.getVendUU()).getEnName(), "com.sas.mobile.activity.PurchaseChangeActivity");
			// IOS
			XingePusher.pushSingleAccountIOS(order.getUserUU().toString(), "新增采购变更单回复" + "单号:" + order.getCode() + ",供应商:"
					+ enterpriseDao.findOne(order.getVendUU()).getEnName());
		}
	}

	@Override
	public PurchaseOrderChange findById(Long id) {
		return purchaseOrderChangeDao.findOne(id);
	}

	@Override
	public int getOnhandCount() {
		return purchaseOrderChangeDao.getCountByVendUUAndStatus(SystemSession.getUser().getEnterprise().getUu(),
				(short) Status.NOT_REPLY.value());
	}

}