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

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.uas.platform.b2b.dao.SaleQuotationDao;
import com.uas.platform.b2b.dao.SaleQuotationItemDao;
import com.uas.platform.b2b.model.SaleQuotation;
import com.uas.platform.b2b.model.SaleQuotationItem;
import com.uas.platform.b2b.service.SaleQuotationService;
import com.uas.platform.b2b.support.SystemSession;
import com.uas.platform.b2b.support.XingePusher;
import com.uas.platform.core.model.Status;

@Service
public class SaleQuotationServiceImpl implements SaleQuotationService {

	@Autowired
	private SaleQuotationItemDao saleQuotationItemDao;

	@Autowired
	private SaleQuotationDao saleQuotationDao;

	@Override
	public void save(List<SaleQuotationItem> items) {
		List<SaleQuotationItem> newItems = saleQuotationItemDao.save(items);
		//主动报价单消息推送通知客户联系人
		Set<Long> quotationIds = new HashSet<Long>();
		for(SaleQuotationItem item : newItems) {
			if(!quotationIds.contains(item.getQuotation().getId())){
				XingePusher.pushSingleAccountAndroid(item.getQuotation().getCustUserUU().toString(), "新增供应商主动报价", "单号:"
						+ item.getQuotation().getCode(), null);
				XingePusher.pushSingleAccountIOS(item.getQuotation().getCustUserUU().toString(), "新增供应商主动报价 - " + "单号:"
						+ item.getQuotation().getCode());
				quotationIds.add(item.getQuotation().getId());
			}
			
		}
	}

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

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

	@Override
	public void onReplyDecide(List<SaleQuotationItem> quotationItems) {
		saleQuotationItemDao.save(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);
			}
		}
	}

}
