/**
 * output package name
 */
package com.kingdee.eas.xr.client;

import java.awt.Dialog;
import java.awt.Frame;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.Map;

import javax.swing.SwingUtilities;

import org.apache.log4j.Logger;

import com.kingdee.bos.ctrl.kdf.table.IRow;
import com.kingdee.bos.ctrl.kdf.table.KDTSelectBlock;
import com.kingdee.bos.ctrl.swing.KDDialog;
import com.kingdee.bos.ctrl.swing.KDFrame;
import com.kingdee.bos.dao.IObjectPK;
import com.kingdee.bos.dao.ormapping.ObjectStringPK;
import com.kingdee.bos.dao.ormapping.ObjectUuidPK;
import com.kingdee.bos.metadata.data.SortType;
import com.kingdee.bos.metadata.entity.SorterItemCollection;
import com.kingdee.bos.metadata.entity.SorterItemInfo;
import com.kingdee.bos.ui.face.CoreUIObject;
import com.kingdee.bos.util.BOSUuid;
import com.kingdee.eas.basedata.master.batch.DlgGeneralBatch;
import com.kingdee.eas.basedata.master.batch.GeneralBatchLog;
import com.kingdee.eas.basedata.master.cssp.client.CSUtils;
import com.kingdee.eas.framework.ICoreBase;
import com.kingdee.eas.scm.common.SCMBillException;
import com.kingdee.eas.scm.common.client.SCMClientUtils;
import com.kingdee.eas.util.SysUtil;
import com.kingdee.eas.util.client.EASResource;
import com.kingdee.eas.util.client.MsgBox;
import com.kingdee.eas.xr.IXRBillBase;
import com.kingdee.eas.xr.XRBillBaseInfo;
import com.kingdee.eas.xr.app.XRBillException;
import com.kingdee.eas.xr.app.XRBillStatusEnum;
import com.kingdee.eas.xr.helper.WorkflowXRHelper;

/**
 * output class name
 */
public abstract class XRBillBaseListUI extends AbstractXRBillBaseListUI
{
    private static final Logger logger = CoreUIObject.getLogger(XRBillBaseListUI.class);
    
    /**
     * output class constructor
     */
    public XRBillBaseListUI() throws Exception
    {
        super();
    }

    public void onLoad() throws Exception {
    	super.onLoad();
    	this.mainQuery.getSorter().clear();
	    SorterItemCollection siColl = this.mainQuery.getSorter();
	    siColl.add(new SorterItemInfo("createTime"));
	    SorterItemInfo siInfo = siColl.get(0);
	    siInfo.setSortType(SortType.DESCEND);
	    this.btnMultiSubmit.setIcon(EASResource.getIcon("imgTbtn_submit"));
    	this.btnMultiSubmit.setEnabled(true);
    }
    public void onShow() throws Exception {
    	super.onShow();
    }
    protected void initWorkButton()
    {
        super.initWorkButton();
        btnAudit.setIcon(EASResource.getIcon("imgTbtn_audit"));
        btnUnAudit.setIcon(EASResource.getIcon("imgTbtn_unaudit"));
        btnAudit.setName("审批");
        btnAudit.setText("审批");
        btnAudit.setToolTipText("审批");
        btnUnAudit.setName("反审批");
        btnUnAudit.setText("反审批");
        btnUnAudit.setToolTipText("反审批");
    }
    protected void checkAudit()
    {
        int size = tblMain.getSelectManager().size();
        for(int j = 0; j < size; j++)
        {
            KDTSelectBlock selectBlock = tblMain.getSelectManager().get(j);
            if(selectBlock == null)
                continue;
            int i = selectBlock.getTop();
            for(int num = selectBlock.getEndRow(); i <= num && i >= 0; i++)
            {
                IRow row = tblMain.getRow(i);
                String baseStatus = row.getCell("baseStatus").getValue().toString();
                if(!baseStatus.trim().equalsIgnoreCase(XRBillStatusEnum.SUBMITED.toString()) && !baseStatus.trim().equalsIgnoreCase(XRBillStatusEnum.ALTERING.toString()))
                {
                    MsgBox.showWarning(EASResource.getString("com.kingdee.eas.scm.common.SDSMResource", "check_audit"));
                    SysUtil.abort();
                }
            }

        }

    }

    protected void checkBillBaseStatusCanUnAudit()
    {
        int size = tblMain.getSelectManager().size();
        for(int j = 0; j < size; j++)
        {
            KDTSelectBlock selectBlock = tblMain.getSelectManager().get(j);
            if(selectBlock == null)
                continue;
            int i = selectBlock.getTop();
            for(int num = selectBlock.getEndRow(); i <= num && i >= 0; i++)
            {
                IRow row = tblMain.getRow(i);
                String baseStatus = row.getCell("baseStatus").getValue().toString();
                if(!baseStatus.trim().equalsIgnoreCase(XRBillStatusEnum.AUDITED.toString()))
                {
                    MsgBox.showWarning(EASResource.getString("com.kingdee.eas.scm.common.SDSMResource", "check_unaudit"));
                    SysUtil.abort();
                }
            }

        }

    }

    public void actionAudit_actionPerformed(java.awt.event.ActionEvent e)
        throws Exception
    {
    	checkSelected();
        IObjectPK pks[];
        IXRBillBase ibill = (IXRBillBase)getBizInterface();
        String ids[] = CSUtils.getSelectRowFieldValue(tblMain, "id");
        String ErrorMsg = "";
        for (int i = 0; i < ids.length; i++) {
        	XRBillBaseInfo billInfo = ibill.getXRBillBaseInfo(new ObjectUuidPK(ids[i]));
        	if(WorkflowXRHelper.checkInProInst(ids[i]))
        		if(!"".equals(ErrorMsg.trim()))
        			ErrorMsg += ","+billInfo.getNumber();
        		else
        			ErrorMsg += billInfo.getNumber();
		}
        if(!"".equals(ErrorMsg.trim())){
        	MsgBox.showWarning("所选单据编号为["+ErrorMsg+"]的单据已经有流程正在运行，请重新选择!");
        	SysUtil.abort();
        }
        if(ids.length == 1){
        	XRBillBaseInfo billInfo = ibill.getXRBillBaseInfo(new ObjectUuidPK(ids[0]));
        	if(!billInfo.getStatus().equals(XRBillStatusEnum.SUBMITED)){
		        MsgBox.showWarning(this, EASResource.getString("com.kingdee.eas.scm.common.SCMResource.NotAudit"));
		        return;
        	}
        }
        pks = CSUtils.convertStringToObjectPK(ids);
        Map mapInfo = ibill.audit(pks);
        if(((Boolean)mapInfo.get("status")).booleanValue())
        {
            GeneralBatchLog log = (GeneralBatchLog)mapInfo.get("info");
            if(SwingUtilities.getWindowAncestor(this) instanceof KDFrame)
            {
                DlgGeneralBatch dlgLog = new DlgGeneralBatch((KDFrame)SwingUtilities.getWindowAncestor(this), log);
                dlgLog.setModal(true);
                dlgLog.show();
                dlgLog.dispose();
            }
            if(SwingUtilities.getWindowAncestor(this) instanceof KDDialog)
            {
                DlgGeneralBatch dlgLog = new DlgGeneralBatch((KDDialog)SwingUtilities.getWindowAncestor(this), log);
                dlgLog.setModal(true);
                dlgLog.show();
                dlgLog.dispose();
            }
        } else
        {
        	XRBillException exception = new XRBillException(XRBillException.CSSP_MSGAPPROVE_PARTSUCCESS, new String[] {
                ""
            });
            MsgBox.showWarning(this, exception.getMessage());
        }
        refresh(e);
    }
    public void actionUnAudit_actionPerformed(java.awt.event.ActionEvent e)
        throws Exception
    {

    	checkSelected();
        IObjectPK pks[];
        IXRBillBase ibill = (IXRBillBase)getBizInterface();
        String ids[] = CSUtils.getSelectRowFieldValue(tblMain, "id");
        String ErrorMsg = "";
        for (int i = 0; i < ids.length; i++) {
        	XRBillBaseInfo billInfo = ibill.getXRBillBaseInfo(new ObjectUuidPK(ids[i]));
        	if(WorkflowXRHelper.checkInProInst(ids[i]))
        		if(!"".equals(ErrorMsg.trim()))
        			ErrorMsg += ","+billInfo.getNumber();
        		else
        			ErrorMsg += billInfo.getNumber();
		}
        if(!"".equals(ErrorMsg.trim())){
        	MsgBox.showWarning("所选单据编号为["+ErrorMsg+"]的单据已经有流程正在运行，请重新选择!");
        	SysUtil.abort();
        }
        if(ids.length == 1){
        	XRBillBaseInfo billInfo = ibill.getXRBillBaseInfo(new ObjectUuidPK(ids[0]));
        	if(!billInfo.getStatus().equals(XRBillStatusEnum.AUDITED)){
		        MsgBox.showWarning(this, "当前单据不是已审批状态！");
		        return;
        	}
        }
        pks = CSUtils.convertStringToObjectPK(ids);
        Map mapInfo = ibill.unAudit(pks);
        if(((Boolean)mapInfo.get("status")).booleanValue())
        {
            GeneralBatchLog log = (GeneralBatchLog)mapInfo.get("info");
            if(SwingUtilities.getWindowAncestor(this) instanceof KDFrame)
            {
                DlgGeneralBatch dlgLog = new DlgGeneralBatch((KDFrame)SwingUtilities.getWindowAncestor(this), log);
                dlgLog.setModal(true);
                dlgLog.show();
                dlgLog.dispose();
            }
            if(SwingUtilities.getWindowAncestor(this) instanceof KDDialog)
            {
                DlgGeneralBatch dlgLog = new DlgGeneralBatch((KDDialog)SwingUtilities.getWindowAncestor(this), log);
                dlgLog.setModal(true);
                dlgLog.show();
                dlgLog.dispose();
            }
        } else
        {
        	XRBillException exception = new XRBillException(XRBillException.CSSP_MSGUNAPPROVE_PARTSUCCESS, new String[] {
                ""
            });
            MsgBox.showWarning(this, exception.getMessage());
        }
        refresh(e);
    }

    public void auditBill(ObjectUuidPK pk)
        throws Exception
    {
        ((IXRBillBase)getBizInterface()).passAudit(pk, null);
    }

    public void actionEdit_actionPerformed(java.awt.event.ActionEvent e)
    throws Exception
	{
	    checkSelected();
	    checkCanEdit();
        String billID = getSelectedKeyValue();
        if(billID == null)
            return;
        ObjectUuidPK pk = new ObjectUuidPK(BOSUuid.read(billID));
        if(WorkflowXRHelper.checkInProInst(pk.toString())){
			MsgBox.showWarning("此单据记录有流程正在运行!");
			SysUtil.abort();
		}
	    super.actionEdit_actionPerformed(e);
	}
	
	protected void checkCanEdit()
	    throws Exception
	{
	    String id = getSelectedKeyValue();
	    if(id != null)
	    {
	        IObjectPK pk = new ObjectStringPK(id);
	        XRBillBaseInfo billInfo = ((IXRBillBase)getBizInterface()).getXRBillBaseInfo(pk);
	        checkCanEdit(billInfo);
	    }
	}
	
	protected void checkCanEdit(XRBillBaseInfo billInfo)
	    throws Exception
	{
	    if(getUIContext().get("BillQuery") != null)
	    {
	        if(!billInfo.getStatus().equals(XRBillStatusEnum.AUDITED))
	        {
	            MsgBox.showWarning(this, SCMClientUtils.getResource("BillAt") + billInfo.getStatus().getAlias() + SCMClientUtils.getResource("CantBeEdited"));
	            SysUtil.abort();
	        }
	        return;
	    }
	    if(billInfo.getStatus().equals(XRBillStatusEnum.AUDITED)){
        	MsgBox.showWarning(this, SCMClientUtils.getResource("BillAt") + billInfo.getStatus().getAlias() + SCMClientUtils.getResource("CantBeEdited"));
	        SysUtil.abort();
        }
	    if(billInfo.getStatus().equals(XRBillStatusEnum.PAY)||billInfo.getStatus().equals(XRBillStatusEnum.BFFK)||billInfo.getStatus().equals(XRBillStatusEnum.QBFK)){
        	MsgBox.showWarning(this, SCMClientUtils.getResource("BillAt") + billInfo.getStatus().getAlias() + SCMClientUtils.getResource("CantBeEdited"));
	        SysUtil.abort();
        }
//	    if(!billInfo.getStatus().equals(XRBillStatusEnum.TEMPORARILYSAVED) && !billInfo.getStatus().equals(XRBillStatusEnum.SUBMITED) && !billInfo.getStatus().equals(XRBillStatusEnum.ADD))
//	    {
//	        MsgBox.showWarning(this, SCMClientUtils.getResource("BillAt") + billInfo.getStatus().getAlias() + SCMClientUtils.getResource("CantBeEdited"));
//	        SysUtil.abort();
//	    }
	}
	public abstract void actionMultiSubmit_actionPerformed(ActionEvent e)throws Exception;	
	
    public void actionRemove_actionPerformed(java.awt.event.ActionEvent e)
        throws Exception
    {
        checkSelected();
        if(confirmRemove())
        {
            ArrayList ids = super.getSelectedIdValues();
            if(ids != null)
            {
                boolean hasException = false;
                ICoreBase scmBillBase = getBizInterface();
                int i = 0;
                for(int num = ids.size(); i < num; i++)
                {
                    try
                    {
                        setOprtState("REMOVE");
                        pubFireVOChangeListener(ids.get(i).toString());
                    }
                    catch(Throwable ex)
                    {
                        if(num == 1)
                        {
                            handUIException(ex);
                            abort();
                        }
                        hasException = true;
                        continue;
                    }
                    try
                    {
                    	if(WorkflowXRHelper.checkInProInst(ids.get(i).toString())){
                  			MsgBox.showWarning("此单据记录有流程正在运行!");
                  			SysUtil.abort();
                  		}
                    	scmBillBase.delete(new ObjectUuidPK(BOSUuid.read(ids.get(i).toString())));
                    }
                    catch(Exception onfe)
                    {
                        if(num == 1)
                        {
                            refreshList();
                            throw onfe;
                        }
                        hasException = true;
                    }
                    try
                    {
                        setOprtState("RELEASEALL");
                        pubFireVOChangeListener(ids.get(i).toString());
                    }
                    catch(Throwable t) { }
                }

                if(hasException)
                {
                    refreshList();
                    throw new SCMBillException(SCMBillException.PARTOFDELETEDBILL_CANNOT_BE_DELETE);
                }
            }
            refresh(e);
        }
    }
    
    protected boolean confirmUnAduit()
    {
        return MsgBox.isYes(MsgBox.showConfirm2(this, EASResource.getString("com.kingdee.eas.scm.common.SCM_COMMONResource", "IsConfirmUnAudit")));
    }
}