package nc.ui.obm.ebankpaylog.actions;

import java.awt.Event;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Vector;

import javax.swing.Action;
import javax.swing.KeyStroke;

import nc.bs.framework.common.NCLocator;
import nc.itf.obm.ebankpaylog.IBusilogService;
import nc.itf.obm.payroll.IUpdateStateMaintain;
import nc.ui.obm.ebankpaylog.model.PayLogBillManageModel;
import nc.ui.obm.ebankpaylog.model.PayLogBillModelManager;
import nc.ui.uif2.NCAction;
import nc.ui.uif2.ShowStatusBarMsgUtil;
import nc.ui.uif2.UIState;
import nc.vo.obm.BillObmStateVO;
import nc.vo.obm.ebankpaylog.EBankPayLogAggVO;
import nc.vo.obm.ebankpaylog.EBankPayLogHVO;
import nc.vo.obm.ebankpaylog.EBankPayLogVO;
import nc.vo.obm.log.ObmLog;
import nc.vo.obm.ml.MLObm;
import nc.vo.obm.obmvo.PayStateQueryVO;
/**
 *  
 * 指令状态下载UI端动作响应.
 *
 * @author  yinyan
 * @version 1.0 2011/1/14
 * @since   NC6.0
 */
public class LogStateDownloadAction extends NCAction {
 
	/**serialVersionUID*/
	private static final long serialVersionUID = 1L;
	/**
	 * UI端数据模型
	 */
	private PayLogBillManageModel model = null;

	private PayLogBillModelManager dataManager;
	
	public LogStateDownloadAction() {
		super();
		setCode("EbankLogDownloadStateAction");
		setBtnName(MLObm.getStr00134()/*"状态下载"*/); 
		putValue(Action.SHORT_DESCRIPTION,getBtnName()+"(Ctrl+J)");
		putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke((int)'J', Event.CTRL_MASK));
	}
	@Override
	public void doAction(ActionEvent e) throws Exception {
		Integer[] selectrows = getModel().getSelectedOperaRows();
		if (selectrows == null || selectrows.length == 0) {
			throw new Exception(MLObm.getStr00135()/*"下载状态前请先选择记录"*/);
		}
		EBankPayLogAggVO[] selectvos = new EBankPayLogAggVO[selectrows.length];
		for (int i = 0; i < selectrows.length; i++) {
			selectvos[i] = (EBankPayLogAggVO) getModel().getData().get(selectrows[i]);
		}
		ShowStatusBarMsgUtil.showStatusBarMsg(MLObm.getStr00136()/*"正在发送状态下载指令..."*/,getModel().getContext());
		if (selectvos != null && selectvos.length > 0) {
		     String userid=getModel().getContext().getPk_loginUser();
		     try {
		    	Collection<BillObmStateVO> downvos=new ArrayList<BillObmStateVO>();
		    	for(EBankPayLogAggVO aggvo:selectvos){
		    	  BillObmStateVO[] retvos= serviceDoDownload(aggvo,userid);	
		    	  if(retvos!=null){
		    		  for(BillObmStateVO vo:retvos){
		    			  downvos.add(vo);
		    		  }
		    	  }
		    	}
		        if(downvos==null||downvos.size()==0){ 
		        	ShowStatusBarMsgUtil.showStatusBarMsg(MLObm.getStr00137()/*"没有返回任何数据"*/,getModel().getContext());
		        }else{
		        	model.updateUILogDataFromDB(selectvos);
		        	StringBuffer errMsg=new StringBuffer();
		        	Exception ex=null;
		        	IUpdateStateMaintain maintian = NCLocator.getInstance().lookup(IUpdateStateMaintain.class);
		        	for(BillObmStateVO vo:downvos){
		        	  ex=vo.getInterruptException();
		        	  if(ex!=null){
			        	 errMsg.append(MLObm.getStr00138(new String[]{vo.getYurref()})+ex.getMessage()).append("\n"); 
		        	  }else {
							String sql = "update ebank_paylog_h set obmdef1='已下载' where pk_ebank_paylog_h = (select pk_ebank_paylog_h"
									+ " from ebank_paylog where yurref = '"+vo.getYurref()+"' and useflag <> - 1 and dr = 0) and dr = 0";
							maintian.updateState(sql);
						}
		        	}
		        	if(ex!=null){
		        		throw new Exception(errMsg.toString());
		        	} 
		        	ShowStatusBarMsgUtil.showStatusBarMsg(MLObm.getStr00140()/*"指令状态下载完成"*/,getModel().getContext());
		        }
			 } catch (Exception ex) {
			    ObmLog.error(ex.getMessage(), this.getClass(), "doAction");
			    throw ex;
			 } 
		}		
	} 
	/**
	 * 
	 * 向后台提交操作
	 * @param headlogvos
	 * @param userObject
	 * @throws Exception
	 */
	private BillObmStateVO[]  serviceDoDownload(EBankPayLogAggVO aggvo,String userid) throws Exception {
//		IOnlinePayment logsev=(IOnlinePayment)NCLocator.
//        getInstance().lookup(IOnlinePayment.class.getName());
		IBusilogService logsev=(IBusilogService)NCLocator.
                            getInstance().lookup(IBusilogService.class.getName());
		EBankPayLogHVO headvo=(EBankPayLogHVO)aggvo.getParent();
		PayStateQueryVO statequery=new PayStateQueryVO();
	    statequery.setPayFunc("zfcx");
	    statequery.setUseid(userid);
	    statequery.setPk_corp(headvo.getPk_org());
	    statequery.setSrcsystem(headvo.getSrcsystem()); 
	    statequery.setSrcbilltype(headvo.getSrcbilltype());
	    statequery.setSrcbillcode(headvo.getSrcbillcode());
	    EBankPayLogVO[] logvos=(EBankPayLogVO[])aggvo.getChildrenVO();
	    Collection<String> yurrefs=new Vector<String>();
		for(EBankPayLogVO vo:logvos){
			if(vo.getYurref()!=null){
				yurrefs.add(vo.getYurref());
			}
		}
		statequery.setYurrefs(yurrefs.toArray(new String[0]));
		BillObmStateVO[] ret= logsev.queryPayState(statequery,aggvo);
        return ret;
	}
	/**
	 * 
	 * 取选中的记录
	 * @return
	 * @throws Exception
	 * @since NC6.0
	 */
    private EBankPayLogAggVO[] getSelectVO() throws Exception {
	   Integer[] selectrows=getModel().getSelectedOperaRows();
	   if (selectrows == null|| selectrows.length ==0) {
			throw new Exception(MLObm.getStr00141()/*"下载状态前请先选择记录"*/);
	   }
	   EBankPayLogAggVO[] selectvos =new EBankPayLogAggVO[selectrows.length];	
	   for(int i=0;i<selectrows.length;i++){
		   selectvos[i]=(EBankPayLogAggVO)getModel().getData().get(selectrows[i]);  
	   }
	   return selectvos;
    }
	@Override
	protected boolean isActionEnable() { 
		boolean enabled=false;
		if(model!=null){
		  enabled=model.getUiState()==UIState.NOT_EDIT
            &&model.getSelectedData()!=null;
		}
		return enabled;
	}
	public PayLogBillManageModel getModel() {
		return model;
	}
	public void setModel(PayLogBillManageModel model) {
		this.model = model; 
		if(this.model!=null){
			this.model.addAppEventListener(this);
		}
	}
	public PayLogBillModelManager getDataManager() {
		return dataManager;
	}
	public void setDataManager(PayLogBillModelManager dataManager) {
		this.dataManager = dataManager;
	}
}
