package com.swfarm.biz.ebay.job;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;

import com.swfarm.biz.chain.bo.CustomerOrder;
import com.swfarm.biz.chain.bo.Semaphore;
import com.swfarm.biz.chain.srv.ChainQueryService;
import com.swfarm.biz.chain.srv.ChainService;
import com.swfarm.biz.ebay.bo.EbayAccount;
import com.swfarm.biz.ebay.srv.EbayQueryService;
import com.swfarm.biz.ebay.srv.EbayService;
import com.swfarm.biz.ebay.srv.SynchronizationService;
import com.swfarm.biz.oa.bo.ImportResultVoucher;
import com.swfarm.biz.oa.bo.ImportResultVoucherItem;
import com.swfarm.biz.oa.bo.User;
import com.swfarm.biz.oa.srv.SysConfigService;
import com.swfarm.biz.oa.srv.UserService;
import com.swfarm.biz.warehouse.srv.WarehouseService;
import com.swfarm.pub.framework.Env;
import com.swfarm.pub.utils.SpringUtils;

public class SynchronizeTransactionStatusTask extends QuartzJobBean {
	Logger logger = Logger.getLogger(SynchronizeTransactionStatusTask.class);

	private EbayService ebayService;

	private ChainService chainService;

	private ChainQueryService chainQueryService;

	private WarehouseService warehouseService;

	private UserService userService;

	private SynchronizationService synchronizationService;

	private List accounts = new ArrayList();

	public void setEbayService(EbayService ebayService) {
		this.ebayService = ebayService;
	}

	public void setChainService(ChainService chainService) {
		this.chainService = chainService;
	}

	public void setChainQueryService(ChainQueryService chainQueryService) {
		this.chainQueryService = chainQueryService;
	}

	public void setWarehouseService(WarehouseService warehouseService) {
		this.warehouseService = warehouseService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public void setSynchronizationService(
			SynchronizationService synchronizationService) {
		this.synchronizationService = synchronizationService;
	}

	public void setAccounts(List accounts) {
		this.accounts = accounts;
	}

	public EbayAccount getEbayAccount(String account) {
		EbayAccount ebayAccount = this.ebayService
				.findEbayAccountByName(account);
		return ebayAccount;
	}

	public void pushVirtualAllocateOrderStatus() {
		logger.warn("*********start to synchronize virtual transaction status*********");
		if (CollectionUtils.isEmpty(this.accounts)) {
			this.accounts = new ArrayList();
			EbayQueryService ebayQueryService = (EbayQueryService) SpringUtils.getBean("ebayQueryService");
			List<EbayAccount> ebayAccounts = ebayQueryService.findEbayAccounts();
			for (Iterator iter = ebayAccounts.iterator(); iter.hasNext();) {
				EbayAccount ebayAccount = (EbayAccount) iter.next();
				String accountNumber = ebayAccount.getAccountNumber();
				if (!this.accounts.contains(accountNumber)) {
					this.accounts.add(accountNumber);
				}
			}
		}
		for (Iterator accountIter = this.accounts.iterator(); accountIter
				.hasNext();) {
			String account = (String) accountIter.next();
			EbayAccount ebayAccount = this.getEbayAccount(account);
			if (ebayAccount != null) {
				List customerOrders = this.chainService
						.findNeedUpdateEbayStatusVirtualAllocateOrders(ebayAccount
								.getAccountNumber());
				Map failedCustomerOrders = new HashMap();
				for (Iterator itemIter = customerOrders.iterator(); itemIter
						.hasNext();) {
					CustomerOrder customerOrder = (CustomerOrder) itemIter
							.next();
					if (StringUtils.isNotEmpty(customerOrder
							.getVirtualAllocationProductVoucherNo())) {
						try {
							CustomerOrder updatedCustomerOrder = this.synchronizationService
									.updateCustomerOrderEbayStatus(
											failedCustomerOrders,
											customerOrder.getId(), false, true);
							logger.warn("account number ["
									+ account
									+ "] customer order ["
									+ updatedCustomerOrder.getCustomerOrderNo()
									+ "] status updated ["
									+ updatedCustomerOrder
											.getEbayStatusUpdated() + "]");
						} catch (Exception e) {
							logger.warn(e);
						}
					}
				}
				Long importResultVoucherId = this.saveImportResultVoucher(
						account, failedCustomerOrders);
			}
		}
		logger.warn("**********finish synchronize virtual transaction status**********");
	}

	public void pushTransactionStatus() {
		logger.warn("*********start to synchronize transaction status*********");
		if (CollectionUtils.isEmpty(this.accounts)) {
			this.accounts = new ArrayList();
			EbayQueryService ebayQueryService = (EbayQueryService) SpringUtils.getBean("ebayQueryService");
			List<EbayAccount> ebayAccounts = ebayQueryService.findEbayAccounts();
			for (Iterator iter = ebayAccounts.iterator(); iter.hasNext();) {
				EbayAccount ebayAccount = (EbayAccount) iter.next();
				String accountNumber = ebayAccount.getAccountNumber();
				if (!this.accounts.contains(accountNumber)) {
					this.accounts.add(accountNumber);
				}
			}
		}
		for (Iterator accountIter = this.accounts.iterator(); accountIter
				.hasNext();) {
			String account = (String) accountIter.next();
			EbayAccount ebayAccount = this.getEbayAccount(account);
			if (ebayAccount != null) {
				List customerOrders = this.chainService
						.findNeedUpdateEbayStatusCustomerOrders(ebayAccount
								.getAccountNumber());
				Map failedCustomerOrders = new HashMap();
				for (Iterator itemIter = customerOrders.iterator(); itemIter
						.hasNext();) {
					CustomerOrder customerOrder = (CustomerOrder) itemIter
							.next();
					try {
						CustomerOrder updatedCustomerOrder = this.synchronizationService
								.updateCustomerOrderEbayStatus(
										failedCustomerOrders,
										customerOrder.getId(), false, null);
						logger.warn("account number [" + account
								+ "] customer order ["
								+ updatedCustomerOrder.getCustomerOrderNo()
								+ "] status updated ["
								+ updatedCustomerOrder.getEbayStatusUpdated()
								+ "]");
					} catch (Exception e) {
						logger.warn(e);
					}
				}
				Long importResultVoucherId = this.saveImportResultVoucher(
						account, failedCustomerOrders);
			}
		}
		logger.warn("**********finish synchronize transaction status**********");
	}

	private Long saveImportResultVoucher(String account,
			Map failedCustomerOrders) {
		if (failedCustomerOrders.size() > 0) {
			ImportResultVoucher importResultVoucher = new ImportResultVoucher();
			User executeUser = userService.findUserByUsername("system");
			importResultVoucher.setImportUserId(executeUser.getId());
			importResultVoucher
					.setImportFileName("synchronizetransactionstatus");
			importResultVoucher.setImportType("synchronizetransactionstatus");
			importResultVoucher.setImportDate(new Date());
			for (Iterator iter = failedCustomerOrders.entrySet().iterator(); iter
					.hasNext();) {
				Map.Entry entry = (Map.Entry) iter.next();
				CustomerOrder customerOrder = (CustomerOrder) entry.getKey();
				String errorMsg = (String) entry.getValue();
				ImportResultVoucherItem importResultVoucherItem = new ImportResultVoucherItem();
				importResultVoucherItem.setImportItemIdentifier(customerOrder
						.getAccountNumber()
						+ "-"
						+ customerOrder.getSaleChannelOrderId()
						+ "-"
						+ customerOrder.getShippedTime());
				importResultVoucherItem
						.setImportResult(ImportResultVoucher.IMPORT_RESULT_FAILED);
				importResultVoucherItem.setImportMessage(errorMsg);
				importResultVoucher
						.addImportResultVoucherItem(importResultVoucherItem);
			}
			SysConfigService sysConfigService = (SysConfigService) SpringUtils
					.getBean("sysConfigService");
			sysConfigService.saveImportResultVoucher(importResultVoucher);
			return importResultVoucher.getId();
		} else {
			return null;
		}
	}

	protected void executeInternal(JobExecutionContext jobExecutionContext)
			throws JobExecutionException {
		this.ebayService = (EbayService) SpringUtils.getBean("ebayService");
		this.chainService = (ChainService) SpringUtils.getBean("chainService");
		this.chainQueryService = (ChainQueryService) SpringUtils
				.getBean("chainQueryService");
		this.warehouseService = (WarehouseService) SpringUtils
				.getBean("warehouseService");
		this.userService = (UserService) SpringUtils.getBean("userService");
		this.synchronizationService = (SynchronizationService) SpringUtils
				.getBean("synchronizationService");
		ChainService chainService = (ChainService) SpringUtils.getBean("chainService");
		String jobDetailName = jobExecutionContext.getJobDetail().getName();
		logger.warn("jobDetailName >> " + jobDetailName);
		Semaphore semaphore = chainService
				.findSemaphoreByJobServerPrefixAndJobDetailName(Env.JOB_SERVER_PREFIX, jobDetailName);
		if (semaphore == null) {
			this.pushVirtualAllocateOrderStatus();
			this.pushTransactionStatus();
		}
	}
}
