package cn.com.customization.purchasing;

import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.PrintWriter;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

import org.apache.log4j.Logger;
import com.teamcenter.rac.aif.AbstractAIFApplication;
import com.teamcenter.rac.aif.AbstractAIFDialog;
import com.teamcenter.rac.aif.kernel.AIFComponentContext;
import com.teamcenter.rac.aifrcp.AIFUtility;
import com.teamcenter.rac.kernel.TCAccessControlService;
import com.teamcenter.rac.kernel.TCComponent;
import com.teamcenter.rac.kernel.TCComponentContextList;
import com.teamcenter.rac.kernel.TCComponentFolder;
import com.teamcenter.rac.kernel.TCComponentQuery;
import com.teamcenter.rac.kernel.TCComponentQueryType;
import com.teamcenter.rac.kernel.TCComponentUser;
import com.teamcenter.rac.kernel.TCException;
import com.teamcenter.rac.kernel.TCSession;
import com.teamcenter.rac.kernel.TCTextService;
import com.teamcenter.rac.util.ButtonLayout;
import com.teamcenter.rac.util.MessageBox;
import com.teamcenter.rac.util.PropertyLayout;
import com.teamcenter.rac.util.iTextField;
import cn.com.teamcenter.rac.form.GCSelectionUserCommand;

/**
 * 采购科到货查询对话框
 * 
 * @author
 */
@SuppressWarnings({"serial","rawtypes"})
public class PurchasingDepartmentSearchDialog extends AbstractAIFDialog {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(PurchasingDepartmentSearchDialog.class);

	private TCSession session;

	private TCComponent tcTargets[];

	private iTextField	txtUserId;
	private JComboBox   comboBoxType;

	private AbstractAIFApplication app = null;

	public PurchasingDepartmentSearchDialog(Frame parent, AbstractAIFApplication papp) {
		super(parent, true);
		app = papp;
		session = (TCSession) papp.getSession();
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				initDialog();
			}
		});
	}

	/*
	 * 初始化界面
	 */
	public void initDialog() {
		
		this.setTitle("采购科到货任务查询");
		JPanel mainPanel = new JPanel(new PropertyLayout());
		this.getContentPane().add(mainPanel);
		txtUserId = new iTextField(20);
		comboBoxType = new JComboBox<String>(new String[]{"加工确认到货","采购确认到货"}); 

		JPanel botPanel = new JPanel();
		botPanel.setLayout(new ButtonLayout(ButtonLayout.HORIZONTAL, ButtonLayout.CENTER, 10));
		JButton selsectUserButton = new JButton("选择");
		selsectUserButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				action(e);
			}
		});

		JButton searchButton = new JButton("查询");
		searchButton.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				action(e);
			}

		});
		JLabel jl1 = new JLabel("用户:");
		JLabel jl2 = new JLabel("       ");

		try {
			txtUserId.setText(session.getUser().getUserId());
		} catch (TCException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		mainPanel.add("1.1.center.center", jl1);
		mainPanel.add("1.2.center.center", txtUserId);
		mainPanel.add("1.3.center.center", selsectUserButton);
		mainPanel.add("1.4.center.center", jl2);
		mainPanel.add("1.5.center.center", comboBoxType);
		mainPanel.add("1.6.center.center", searchButton);
		this.pack();
		this.centerToScreen();
		this.setVisible(true);

	}

	public void action(ActionEvent e) {
		if (logger.isDebugEnabled()) {
			logger.debug("actionPerformed(ActionEvent) - start"); //$NON-NLS-1$
		}
		try {
			if (e.getActionCommand().equals("选择")) {
				GCSelectionUserCommand selectionUserCmd = new GCSelectionUserCommand(AIFUtility.getCurrentApplication().getDesktop(), session);
				selectionUserCmd.setContextBean("采购科到货确认查询",txtUserId);
				selectionUserCmd.executeModal();
			} else if (e.getActionCommand().equals("查询")) {
	
				if(!txtUserId.getText().equals("") && comboBoxType.getSelectedItem() != null){
					doSearch(txtUserId.getText(),comboBoxType.getSelectedItem().toString());
					dispose();
				}else{
					MessageBox.post("请输入查询条件.","提示",MessageBox.INFORMATION);
				}
			}
		} catch (TCException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (Exception e2) {
			// TODO Auto-generated catch block
			e2.printStackTrace();
		}
		
		if (logger.isDebugEnabled()) {
			logger.debug("actionPerformed(ActionEvent) - end"); //$NON-NLS-1$
		}
	}

	private void doSearch(String userId, String taskName){
		System.out.println("userId="+userId);
		try {
			String str_key = "Type";
			String str_value = "TasksToPerform";
			String str_key2 = "OwningUser";
			String str_value2 = userId;

			TCTextService textService = session.getTextService();
			TCComponentQueryType querytype = (TCComponentQueryType) session.getTypeComponent("ImanQuery");
			TCComponentQuery query = (TCComponentQuery) querytype.find("__find_user_inbox");//常规...
			querytype.clearCache();
			String as[] = new String[2];
			String as1[] = new String[2];
			as[0] = textService.getTextValue(str_key);
			as1[0] = str_value;
			as[1] = textService.getTextValue(str_key2);
			as1[1] = str_value2;
			query.clearCache();
			System.out.println("query " + query);
			TCComponentContextList list = query.getExecuteResultsList(as, as1);

			if (list != null) {
				String filePath = System.getenv("temp") + "/logger.txt";
				PrintWriter pw = new PrintWriter(filePath);
				int count = list.getListCount();
				System.out.println(" folder coutn " + count);
				if(taskName.equals("加工确认到货")){
					for (int i = 0; i < count; i++) {
						TCComponent[] tasks = ((TCComponentFolder) list.get(i).getComponent()).getRelatedComponents("contents");
						for(int ix = 0; ix < tasks.length; ix++){
							String rootTaskName = tasks[ix].getProperty("object_name");
							//System.out.println(rootTaskName);
							if(rootTaskName.contains("加工完成") || rootTaskName.contains("加工确认到货")){
								TCComponent[] taskAttachments = tasks[ix].getReferenceListProperty("root_target_attachments");
								for(int jy = 0; jy < taskAttachments.length; jy++){
									String attType = taskAttachments[jy].getType();
									//System.out.println(attType);
									if(attType.equals("YSR8_ECN2RevisionMaster") || attType.equals("YSR8_ECN4RevisionMaster") ){
										if(!taskAttachments[jy].getProperty("ysr8_PurchFinishDate").equals("")){
											//System.out.println("======找到了,输出到TXT=============");
											pw.print(tasks[ix].getProperty("job_name")+";"+taskAttachments[jy].toString()+"\r\n");
										}
									}
								}
							}
						}
					}
				}else{
					for (int i = 0; i < count; i++) {
						TCComponent[] tasks = ((TCComponentFolder) list.get(i).getComponent()).getRelatedComponents("contents");
						for(int ix = 0; ix < tasks.length; ix++){
							String rootTaskName = tasks[ix].getProperty("object_name");//job_name.getReferenceProperty("root_task").getProperty("object_name");
							//System.out.println(rootTaskName);
							if(rootTaskName.contains("采购完成") || rootTaskName.contains("采购确认到货")){
								TCComponent[] taskAttachments = tasks[ix].getReferenceListProperty("root_target_attachments");
								for(int jy = 0; jy < taskAttachments.length; jy++){
									String attType = taskAttachments[jy].getType();
									//System.out.println(attType);
									if(attType.equals("YSR8_ECN1RevisionMaster") || attType.equals("YSR8_ECN3RevisionMaster") ){
										if(!taskAttachments[jy].getProperty("ysr8_PurchFinishDate").equals("")){//creation_date attType.equals("ItemRevision Master") || 
											//System.out.println("======找到了,输出到TXT=============");
											pw.print(tasks[ix].getProperty("job_name")+";"+taskAttachments[jy].toString()+"\r\n");
										}
									}
								}
							}
						}
					}
				}
				pw.flush();
				pw.close();
				Runtime runtime = Runtime.getRuntime(); 
				runtime.exec("cmd /c "+filePath);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/*
	 * 检查选中的输入对象是否符合条件
	 */
	@SuppressWarnings("unused")
	private int checkTargets() {
		if (logger.isDebugEnabled()) {
			logger.debug("checkTargets() - start"); //$NON-NLS-1$
		}

		int flag = 0;
		AIFComponentContext aifcomponentcontext[] = app.getTargetContexts();
		if (aifcomponentcontext != null && aifcomponentcontext.length >= 0) {
			tcTargets = new TCComponent[aifcomponentcontext.length];
			for (int i = 0; i < aifcomponentcontext.length; i++) {
				tcTargets[i] = (TCComponent) aifcomponentcontext[i].getComponent();
				System.out.println("tcTargets[i]===" + tcTargets[i]);
			}
			//selectedFolder = (TCComponentFolder) tcTargets[0];
			try {
				if (!checkAccessPrivilige(session.getUser(), tcTargets[0], "WRITE")) {
					flag = 2;
				}
			} catch (TCException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		} else {
			flag = 3;
		}

		if (logger.isDebugEnabled()) {
			logger.debug("checkTargets() - end"); //$NON-NLS-1$
		}
		return flag;
	}

	/**
	 * 检测用户针对指定对象是否有某项权限
	 * 
	 * @param user
	 *            用户
	 * @param comp
	 *            对象
	 * @param accessName
	 *            权限名称
	 * @return 是否有权限
	 * @throws TCException
	 */
	private boolean checkAccessPrivilige(TCComponentUser user, TCComponent comp, String accessName) throws TCException {
		if (logger.isDebugEnabled()) {
			logger.debug("checkAccessPrivilige(TCComponentUser, TCComponent, String) - start"); //$NON-NLS-1$
		}

		if (logger.isInfoEnabled()) {
			logger.info("checkAccessPrivilige(TCComponentUser, TCComponent, String) - TCComponentUser user=" + user); //$NON-NLS-1$
			logger.info("checkAccessPrivilige(TCComponentUser, TCComponent, String) - TCComponentUser comp=" + comp); //$NON-NLS-1$
			logger.info("checkAccessPrivilige(TCComponentUser, TCComponent, String) - TCComponentUser accessName=" + accessName); //$NON-NLS-1$
		}
		TCAccessControlService accessService = ((TCSession) session).getTCAccessControlService();
		if (logger.isInfoEnabled()) {
			logger.info("checkAccessPrivilige(TCComponentUser, TCComponent, String) - TCAccessControlService accessService=" + accessService); //$NON-NLS-1$
		}
		boolean returnboolean = accessService.checkUsersPrivilege(user, comp, accessName);
		if (logger.isInfoEnabled()) {
			logger.info("checkAccessPrivilige(TCComponentUser, TCComponent, String) - boolean returnboolean=" + returnboolean); //$NON-NLS-1$
		}

		if (logger.isDebugEnabled()) {
			logger.debug("checkAccessPrivilige(TCComponentUser, TCComponent, String) - end"); //$NON-NLS-1$
		}
		return returnboolean;
	}
}
