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

import java.util.Date;
import java.util.List;

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.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import com.uas.platform.b2b.dao.PurchaseProofingApprovalDao;
import com.uas.platform.b2b.dao.PurchaseProofingDao;
import com.uas.platform.b2b.dao.PurchaseProofingItemDao;
import com.uas.platform.b2b.dao.PurchaseProofingSendDao;
import com.uas.platform.b2b.model.Attach;
import com.uas.platform.b2b.model.PurchaseProofing;
import com.uas.platform.b2b.model.PurchaseProofingApproval;
import com.uas.platform.b2b.model.PurchaseProofingItem;
import com.uas.platform.b2b.model.PurchaseProofingSend;
import com.uas.platform.b2b.service.PurchaseProofingService;
import com.uas.platform.b2b.support.SystemSession;
import com.uas.platform.b2b.support.XingePusher;
import com.uas.platform.core.exception.IllegalOperatorException;
import com.uas.platform.core.model.PageInfo;
import com.uas.platform.core.model.Status;

@Service
public class PurchaseProofingServiceImpl implements PurchaseProofingService{
	
	@Autowired
	private PurchaseProofingItemDao purchaseProofingItemDao;
	
	@Autowired
	private PurchaseProofingDao purchaseProofingDao;
	
	@Autowired
	private PurchaseProofingSendDao purchaseProofingSendDao;
	
	@Autowired
	private PurchaseProofingApprovalDao purchaseProofingApprovalDao;
	
	@Override
	public void save(List<PurchaseProofingItem> proofingItems) {
		purchaseProofingItemDao.save(proofingItems);
		//发送推送消息
		for(PurchaseProofingItem proofingItem : proofingItems) {
			//每个明细发一个
			if(proofingItem.getVendUserUU() != null) {
				XingePusher.pushSingleAccountAndroid(proofingItem.getVendUserUU().toString(), 
						"新增客户的打样申请单", "物料：" + proofingItem.getProofing().getProduct().getTitle(),
						null);
				XingePusher.pushSingleAccountIOS(proofingItem.getVendUserUU().toString(),
						"新增客户的打样申请单" + "  物料：" + proofingItem.getProofing().getProduct().getTitle());
			}
		}
	}

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

	@Override
	public List<PurchaseProofingItem> findNotUploadProofing() {
		return purchaseProofingItemDao.findByVendUUAndSendStatus(SystemSession.getUser().getEnterprise().getUu(), 
				(short) Status.NOT_UPLOAD.value());
	}

	@Override
	public void uploadProofingSuccess(String[] idArray) {
		for(String id : idArray) {
			PurchaseProofingItem proofingItem = purchaseProofingItemDao.findOne(Long.parseLong(id));
			if(proofingItem != null) {
				proofingItem.setSendStatus((short) Status.DOWNLOADED.value());
				purchaseProofingItemDao.save(proofingItem);
			}
		}
	}

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

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

	@Override
	public PurchaseProofingItem findById(Long id) {
		return purchaseProofingItemDao.findOne(id);
	}

	@Override
	public void send(PurchaseProofingSend proofingSend) {
		send(proofingSend, true);
	}

	@Override
	@Transactional
	public void send(List<PurchaseProofingSend> proofingSend) {
		for(PurchaseProofingSend send : proofingSend) {
			send(send, false);
		}
	}
	
	public void send(PurchaseProofingSend proofingSend, boolean isB2b) {
		if(isB2b) {//平台上的操作
			proofingSend.setDate(new Date());
			//设置传输到买方ERP的状态为未上传
			proofingSend.setSendStatus((short) Status.NOT_UPLOAD.value());
			//设置传输到卖方ERP的状态为未上传
			proofingSend.setBackStatus((short) Status.NOT_UPLOAD.value());
			proofingSend.setRecorder(SystemSession.getUser().getUserName());
		}//从卖方ERP传输过来的单据在类型转换时设置好了状态，所以此处不需要设置
		PurchaseProofingItem proofingItem = purchaseProofingItemDao.findOne(proofingSend.getProofingItem().getId());
		if(proofingItem == null) {
			throw new IllegalOperatorException("不存在的客户打样申请");
		}
		if(proofingItem.getStatus() == Status.SEND.value()) {//状态为已送样
			if(isB2b)//b2B上操作,报错
				throw new IllegalOperatorException("客户打样申请已送样，不可重复送样");
			else //卖方ERP的操作数据上传过来,忽略
				return;
		}
		proofingItem.setStatus((short) Status.SEND.value());
		proofingSend.setProofingItem(proofingItem);
		proofingSend.setSendQty(proofingItem.getQty());
		purchaseProofingSendDao.save(proofingSend);
		purchaseProofingItemDao.save(proofingItem);
		if(proofingItem.getProofing().getUserUU() != null) {
			//推送给客户打样申请申请人||客户管理员账号
			XingePusher.pushSingleAccountAndroid(proofingItem.getProofing().getUserUU().toString(), 
					"供应商给你送样了", "供应商：" + SystemSession.getUser().getEnterprise().getEnName(), null);
			XingePusher.pushSingleAccountIOS(proofingItem.getProofing().getUserUU().toString(), 
					"供应商给你送样了  " + "供应商：" + SystemSession.getUser().getEnterprise().getEnName());
		}
	}

	@Override
	public List<PurchaseProofingSend> findNotBackSampleSend() {
		return purchaseProofingSendDao.findByBackStatusAndProofingItemVendUU((short) Status.NOT_UPLOAD.value(), 
				SystemSession.getUser().getEnterprise().getUu());
	}

	@Override
	public void backSampleSendSuccess(String[] idArray) {
		for(String id : idArray) {
			PurchaseProofingSend proofingSend = purchaseProofingSendDao.findOne(Long.parseLong(id));
			if(proofingSend != null) {
				proofingSend.setBackStatus((short) Status.DOWNLOADED.value());
				purchaseProofingSendDao.save(proofingSend);
			}
		}
	}

	@Override
	public List<PurchaseProofingSend> findNotSendSampleSend() {
		return purchaseProofingSendDao.findBySendStatusAndProofingItemProofingEnUU((short) Status.NOT_UPLOAD.value(), 
				SystemSession.getUser().getEnterprise().getUu());
	}

	@Override
	public void sendSampleSendSuccess(String[] idArray) {
		for(String id : idArray) {
			PurchaseProofingSend proofingSend = purchaseProofingSendDao.findOne(Long.parseLong(id));
			if(proofingSend != null) {
				proofingSend.setSendStatus((short) Status.DOWNLOADED.value());
				purchaseProofingSendDao.save(proofingSend);
			}
		}
	}

	@Override
	public void saveSampleApproval(
			List<PurchaseProofingApproval> proofingApprovals) {
		purchaseProofingApprovalDao.save(proofingApprovals);
		for(PurchaseProofingApproval approval : proofingApprovals) {
			if(approval.getSscode() != null && approval.getVendUU() != null) {
				List<PurchaseProofingSend> sends = purchaseProofingSendDao.findByProofingItemVendUUAndCode(approval.getVendUU(), approval.getSscode());
				if(sends.size() > 0) {
					PurchaseProofingSend send = sends.get(0);
					XingePusher.pushSingleAccountAndroid(send.getProofingItem().getVendUserUU().toString(), "客户返回了送样认定单", 
							"送样单号:" + approval.getSscode(), null);
					XingePusher.pushSingleAccountIOS(send.getProofingItem().getVendUserUU().toString(), 
							"客户返回了送样认定单  " + "送样单号:" + approval.getSscode());
				}
			}
		}
	}

	@Override
	public List<PurchaseProofingApproval> findNotUploadApprovals() {
		return purchaseProofingApprovalDao.findByVendUUAndSendStatus(SystemSession.getUser().getEnterprise().getUu(),
				(short) Status.NOT_UPLOAD.value());
	}

	@Override
	public void uploadApprovalsSuccess(String[] idArray) {
		for(String id : idArray) {
			PurchaseProofingApproval approval = purchaseProofingApprovalDao.findOne(Long.parseLong(id));
			if(approval != null) {
				approval.setSendStatus((short) Status.DOWNLOADED.value());
				purchaseProofingApprovalDao.save(approval);
			}
		}
	}


}
