package com.neusoft.smart.pos.trade.service;


import com.neusoft.smart.pos.constants.DictionaryConstant;
import com.neusoft.smart.pos.framework.task.TaskExecutor;
import com.neusoft.smart.pos.trade.persistent.domain.BillSettlementTask;
import com.neusoft.smart.pos.trade.repository.BillSettlementTaskRepository;
import com.neusoft.smart.pos.trade.task.BillTask;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

@Service("billTaskScheduleService")
public class BillTaskScheduleService {
	
	@Autowired
	private TaskExecutor taskExecutor;
	
	@Autowired
	private BillSettlementTaskRepository billSettlementTaskRepository;
	
//	public static Map<String,BillTask> billTaskMap = new HashMap<>();
	
	/**
	 * 账单生成任务执行方法
	 * @param orgId
	 * @param shopIds
	 * @param billNumber
	 */
	public BillSettlementTask executeGenerateBillTask(Integer orgId, List<Integer> shopIds, String billNumber) {
		BillSettlementTask billSettlementTask = new BillSettlementTask();
		String taskNumber = orgId+"_"+billNumber;
		
		//1.查询任务信息是否已经存在，如果存在则不在执行
		BillSettlementTask billSettlementTaskTemp = billSettlementTaskRepository.queryBillSettlementTask(orgId,billNumber);
		if(null != billSettlementTaskTemp){
			return billSettlementTaskTemp;
		}
		
		//2.存储任务信息
		billSettlementTask.setBillNumber(billNumber);
		billSettlementTask.setTaskNumber(taskNumber);
		billSettlementTask.setOrgId(orgId);
		billSettlementTask.setStartTime(new Date());
		billSettlementTask.setTaskStatus(DictionaryConstant.BILL_TASK_STATUS_1.getCode());
		billSettlementTaskRepository.saveBillSettlementTask(billSettlementTask);
		
		//3.调用执行任务
		BillTask billTask = new BillTask();
		billTask.setOrgId(orgId);
		billTask.setShopIds(shopIds);
		billTask.setBillNumber(billNumber);
		taskExecutor.getExecutorService().submit(billTask);
//		billTaskMap.put(taskNumber,billTask);
		return billSettlementTask;
	}
	
	/**
	 * 结算任务信息查询方法
	 * @param orgId
	 * @param billNumber
	 * @return
	 */
	public BillSettlementTask queryBillSettlementTask(Integer orgId,String billNumber){
		return billSettlementTaskRepository.queryBillSettlementTask(orgId,billNumber);
	}
	
	/**
	 * 结算任务信息查询方法
	 * @param orgId
	 * @param billNumber
	 * @return
	 */
	public void updateBillSettlementTaskStatus(Integer orgId,String billNumber){
		BillSettlementTask billSettlementTask = new BillSettlementTask();
		billSettlementTask.setTaskStatus(DictionaryConstant.BILL_TASK_STATUS_2.getCode());
		billSettlementTask.setEndTime(new Date());
		billSettlementTaskRepository.updateBillSettlementTask(billSettlementTask,orgId,billNumber);
	}
}
