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.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import com.uas.platform.b2b.dao.PurchaseInquiryDao;
import com.uas.platform.b2b.dao.PurchaseInquiryItemDao;
import com.uas.platform.b2b.dao.PurchaseInquiryReplyDao;
import com.uas.platform.b2b.erp.model.QuotationDown;
import com.uas.platform.b2b.erp.model.QuotationDownDetail;
import com.uas.platform.b2b.model.Attach;
import com.uas.platform.b2b.model.PurchaseInquiry;
import com.uas.platform.b2b.model.PurchaseInquiryItem;
import com.uas.platform.b2b.model.PurchaseInquiryReply;
import com.uas.platform.b2b.service.PurchaseInquiryService;
import com.uas.platform.b2b.support.SystemSession;
import com.uas.platform.b2b.support.XingePusher;
import com.uas.platform.core.exception.IllegalStatusException;
import com.uas.platform.core.model.Constant;
import com.uas.platform.core.model.PageInfo;
import com.uas.platform.core.model.Status;

@Service
public class PurchaseInquiryServiceImpl implements PurchaseInquiryService {

	@Autowired
	private PurchaseInquiryReplyDao purchaseInquiryReplyDao;

	@Autowired
	private PurchaseInquiryItemDao purchaseInquiryItemDao;

	@Autowired
	private PurchaseInquiryDao purchaseInquiryDao;

	@Override
	public void save(List<PurchaseInquiryItem> inquiryItems) {
		purchaseInquiryItemDao.save(inquiryItems);
		// 将询价信息推送通知供应商联系人UU号
		for (PurchaseInquiryItem item : inquiryItems) {
			PurchaseInquiry inquiry = item.getInquiry();
			if (item.getVendUserUU() != null) {
				// Android
				XingePusher.pushSingleAccountAndroid(item.getVendUserUU().toString(), "新增一条客户询价-", "单号:" + inquiry.getCode() + ",客户:"
						+ inquiry.getEnterprise().getEnName(), "com.sas.mobile.activity.PurchaseChangeActivity");
				// IOS
				XingePusher.pushSingleAccountIOS(item.getVendUserUU().toString(), "新增一条客户询价-" + "单号:" + inquiry.getCode() + ",客户:"
						+ inquiry.getEnterprise().getEnName());
			}
		}
	}

	@Override
	public List<PurchaseInquiryItem> findNotUploadReply() {
		return purchaseInquiryItemDao.findByEnUUAndBackStatus(SystemSession.getUser().getEnterprise().getUu(),
				(short) Status.NOT_UPLOAD.value());
	}

	@Override
	public void onReplyUploadSuccess(String[] idArray) {
		for (String id : idArray) {
			PurchaseInquiryItem item = purchaseInquiryItemDao.findOne(Long.parseLong(id));
			if (item != null) {
				item.setBackStatus((short) Status.DOWNLOADED.value());
				purchaseInquiryItemDao.save(item);
			}
		}
	}

	@Override
	public void onReplyDecide(List<PurchaseInquiryItem> inquiryItems) {
		purchaseInquiryItemDao.save(inquiryItems);
		// 将客户处理报价结果推送通知供应商联系人UU号
		for (PurchaseInquiryItem item : inquiryItems) {
			PurchaseInquiry inquiry = item.getInquiry();
			String tittle = (item.getAgreed() == Constant.YES) ? "客户同意了您的报价" : "客户不同意您的报价";
			if (item.getVendUserUU() != null) {
				// Android
				XingePusher.pushSingleAccountAndroid(item.getVendUserUU().toString(), tittle, "物料:" + item.getProduct().getTitle() + ",客户:"
						+ inquiry.getEnterprise().getEnName(), "com.sas.mobile.activity.PurchaseChangeActivity");
				// IOS
				XingePusher.pushSingleAccountIOS(item.getVendUserUU().toString(), tittle + "物料:" + item.getProduct().getTitle() + ",客户:"
						+ inquiry.getEnterprise().getEnName());
			}
		}
	}

	@Override
	public List<PurchaseInquiryItem> findNotUploadInquiry() {
		return purchaseInquiryItemDao.findByVendUUAndSendStatus(SystemSession.getUser().getEnterprise().getUu(),
				(short) Status.NOT_UPLOAD.value());
	}

	@Override
	public void onQuotationDownSuccess(String[] idArray) {
		for (String id : idArray) {
			PurchaseInquiryItem item = purchaseInquiryItemDao.findOne(Long.parseLong(id));
			if (item != null) {
				item.setSendStatus((short) Status.DOWNLOADED.value());
				purchaseInquiryItemDao.save(item);
			}
		}
	}

	@Override
	public void reply(List<QuotationDown> downs) {
		for (QuotationDown down : downs) {
			PurchaseInquiryItem item = purchaseInquiryItemDao.findOne(down.getB2b_id_id());
			if (item != null) {
				item.setMinOrderQty(down.getQu_minbuyqty());
				item.setMinPackQty(down.getQu_minqty());
				item.setVendFromDate(down.getQu_fromdate());
				item.setVendToDate(down.getQu_todate());
				item.setStatus((short) Status.REPLIED.value());
				item.setBackStatus((short) Status.NOT_UPLOAD.value());
				item.setReplySendStatus((short) Status.DOWNLOADED.value());
				item.setRemark(String.valueOf(System.currentTimeMillis()));
				if (!CollectionUtils.isEmpty(down.getDetails())) {
					purchaseInquiryReplyDao.delete(item.getReplies());
					Set<PurchaseInquiryReply> replies = new HashSet<PurchaseInquiryReply>();
					for (QuotationDownDetail detail : down.getDetails()) {
						replies.add(detail.convert());
					}
					item.setReplies(replies);
				}
				Long userUU = item.getUserUU();
				if (userUU == null) {
					userUU = item.getInquiry().getRecorderUU();
				}
				if (userUU != null) {
					// 消息推送
					if (userUU != null && userUU != 0) {
						// Android
						XingePusher.pushSingleAccountAndroid(userUU.toString(), "询价单回复",
								"单号:" + item.getInquiry().getCode() + ",第" + item.getNumber() + "行", "");
						// IOS
						XingePusher.pushSingleAccountIOS(userUU.toString(),
								"询价单回复" + "单号:" + item.getInquiry().getCode() + ",第" + item.getNumber() + "行");
					}
				}
				purchaseInquiryItemDao.save(item);
			}
		}
	}

	@Override
	public List<PurchaseInquiryItem> findNotUploadInquiryReply() {
		return purchaseInquiryItemDao.findByVendUUAndReplySendStatus(SystemSession.getUser().getEnterprise().getUu(),
				(short) Status.NOT_UPLOAD.value());
	}

	@Override
	public void onReplyDownSuccess(String[] idArray) {
		for (String id : idArray) {
			PurchaseInquiryItem item = purchaseInquiryItemDao.findOne(Long.parseLong(id));
			if (item != null) {
				item.setReplySendStatus((short) Status.DOWNLOADED.value());
				purchaseInquiryItemDao.save(item);
			}
		}
	}

	@Override
	public List<PurchaseInquiryItem> findNotUploadInquiryReplyDecide() {
		return purchaseInquiryItemDao.findByVendUUAndDecideStatus(SystemSession.getUser().getEnterprise().getUu(),
				(short) Status.NOT_UPLOAD.value());
	}

	@Override
	public void onReplyDecideDownSuccess(String[] idArray) {
		for (String id : idArray) {
			PurchaseInquiryItem item = purchaseInquiryItemDao.findOne(Long.parseLong(id));
			if (item != null) {
				item.setDecideStatus((short) Status.DOWNLOADED.value());
				purchaseInquiryItemDao.save(item);
			}
		}
	}

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

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

	@Override
	public PurchaseInquiry findById(Long id) {
		return purchaseInquiryDao.findOne(id);
	}

	@Override
	public PurchaseInquiryItem findItemByItemId(Long itemId) {
		return purchaseInquiryItemDao.findOne(itemId);
	}

	@Override
	public void save(PurchaseInquiryItem inquiryItem) {
		purchaseInquiryItemDao.save(inquiryItem);
	}

	@Override
	public void reply(PurchaseInquiryItem inquiryItem) {
		PurchaseInquiryItem item = purchaseInquiryItemDao.findOne(inquiryItem.getId());
		if (item.getStatus() == Status.REPLIED.value()
				|| (item.getReplySendStatus() != null && item.getReplySendStatus() == Status.DOWNLOADED.value()))
			throw new IllegalStatusException("该询价单已经报价，不允许再次报价");
		inquiryItem.setStatus((short) Status.REPLIED.value());
		inquiryItem.setBackStatus((short) Status.NOT_UPLOAD.value());
		inquiryItem.setReplySendStatus((short) Status.NOT_UPLOAD.value());
		Long userUU = inquiryItem.getUserUU();
		if (userUU == null) {
			userUU = item.getInquiry().getRecorderUU();
		}
		if (userUU != null) {
			// 消息推送
			if (userUU != null && userUU != 0) {
				// Android
				XingePusher.pushSingleAccountAndroid(userUU.toString(), "询价单回复",
						"单号:" + item.getInquiry().getCode() + ",第" + item.getNumber() + "行", "");
				// IOS
				XingePusher.pushSingleAccountIOS(userUU.toString(), "询价单回复" + "单号:" + item.getInquiry().getCode() + ",第" + item.getNumber()
						+ "行");
			}
		}
		purchaseInquiryItemDao.save(inquiryItem);
	}

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

	@Override
	public List<PurchaseInquiryItem> findHistoryByItemId(Long itemId) {
		PurchaseInquiryItem item = purchaseInquiryItemDao.findOne(itemId);
		if (item != null) {
			final PageInfo pageInfo = new PageInfo(1, 3, 1);
			pageInfo.filter("vendUU", SystemSession.getUser().getEnterprise().getUu());
			pageInfo.filter("productId", item.getProductId());
			pageInfo.filter("status", (short) Status.REPLIED.value());
			pageInfo.sorting("inquiry.date", Direction.DESC);
			Page<PurchaseInquiryItem> page = findAllByPageInfo(pageInfo);
			return page.getContent();
		}
		return null;
	}

	@Override
	public void saveAttach(List<Attach> attachs) {
		if (!CollectionUtils.isEmpty(attachs)) {
			long enUU = SystemSession.getUser().getEnterprise().getUu();
			for (Attach attach : attachs) {
				List<PurchaseInquiry> inquiries = purchaseInquiryDao.findByEnUUAndSourceId(enUU, attach.getSourceId());
				if (!CollectionUtils.isEmpty(inquiries)) {
					PurchaseInquiry inquiry = inquiries.get(0);
					String atId = inquiry.getAttach();
					if (!StringUtils.hasText(atId))
						atId = "";
					else
						atId += ",";
					atId += attach.getId();
					inquiry.setAttach(atId);
					purchaseInquiryDao.save(inquiry);
				}
			}
		}
	}
}
