package cn.com.customization.schedule;

import java.awt.Component;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeSelectionModel;

import com.teamcenter.rac.aif.AbstractAIFDialog;
import com.teamcenter.rac.aif.AbstractAIFUIApplication;
import com.teamcenter.rac.aif.kernel.AIFComponentContext;
import com.teamcenter.rac.aifrcp.AIFUtility;
import com.teamcenter.rac.common.TCTypeRenderer;
import com.teamcenter.rac.common.lov.LOVComboBox;
import com.teamcenter.rac.kernel.TCComponent;
import com.teamcenter.rac.kernel.TCComponentBOMLine;
import com.teamcenter.rac.kernel.TCComponentBOMWindow;
import com.teamcenter.rac.kernel.TCComponentBOMWindowType;
import com.teamcenter.rac.kernel.TCComponentItem;
import com.teamcenter.rac.kernel.TCComponentItemRevision;
import com.teamcenter.rac.kernel.TCComponentItemType;
import com.teamcenter.rac.kernel.TCComponentRevisionRule;
import com.teamcenter.rac.kernel.TCComponentRevisionRuleType;
import com.teamcenter.rac.kernel.TCComponentSchedule;
import com.teamcenter.rac.kernel.TCComponentScheduleTask;
import com.teamcenter.rac.kernel.TCException;
import com.teamcenter.rac.kernel.TCProperty;
import com.teamcenter.rac.kernel.TCSession;
import com.teamcenter.rac.kernel.TCUserService;
import com.teamcenter.rac.schedule.commands.reload.ReloadOperation;
import com.teamcenter.rac.schedule.common.tree.ScheduleTreeLine;
import com.teamcenter.rac.schedule.scheduler.componentutils.ScheduleHelper;
import com.teamcenter.rac.schedule.scheduler.componentutils.TaskHelper;
import com.teamcenter.rac.util.PropertyLayout;
import com.teamcenter.rac.util.iTextField;

import cn.com.customization.util.UtilApi;
import cn.com.teamcenter.rac.form.GCSelectionUserCommand;

@SuppressWarnings({"deprecation","rawtypes"})
public class BOMTransPlanDialog extends AbstractAIFDialog implements WindowListener{

	private static final long serialVersionUID = 1L;
	private TCSession					session = null;
	private AbstractAIFUIApplication	application = null;
	private TCComponentSchedule         scheduleTag = null;
	private ScheduleTreeLine            rootscheduleTreeLine = null;
	
	private JButton      addButton;
	private JButton      removeButton;
//	private JComboBox    ysr8_TaskUse;
	private LOVComboBox  ysr8_TaskUse;
	private JComboBox    workFlowTemp;
	private iTextField   taskReso;
	private JCheckBox    isTranOwner;
	private JCheckBox    isDevi;
	
	private JTree scheduleTree;
	private JTree bomTree;
	
	//private String strLOVTaskUse = "YSR_Task_Use_LOV";
	private String strLOVWorkFlowTemp = "YSR_Workflow_Template_LOV";
	
	public BOMTransPlanDialog(AbstractAIFUIApplication application, Frame frame, TCComponentSchedule scheduleTag) {
		super(frame, true); 
		session = (TCSession) application.getSession();
		this.application = application;
		this.scheduleTag = scheduleTag;
		init();
	}
	
	private void init() {
		
		setLayout(new PropertyLayout(5, 5, 5, 5, 5, 5));
		
		setTitle("添加BOM到工作计划");
		this.addWindowListener(this);
		
		rootscheduleTreeLine = new ScheduleTreeLine(scheduleTag);
		DefaultMutableTreeNode scheduleTop = new DefaultMutableTreeNode(rootscheduleTreeLine); 
		initTreeTableModel(scheduleTag, scheduleTop);

		DefaultTreeModel scheduleModel = new DefaultTreeModel(scheduleTop);  
		scheduleTree = new JTree(scheduleModel);
		scheduleTree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);// 一次只能选择一个节点的选项  
		scheduleTree.setCellRenderer(new ScheduleDefaultTreeCellRenderer());
		JScrollPane jScrollPane = new JScrollPane(scheduleTree);
		jScrollPane.setPreferredSize(new Dimension(300, 400));
		add("1.1.left.center",jScrollPane);
		
		JPanel centerPanel = new JPanel();
		centerPanel.setLayout(new PropertyLayout(5, 5, 5, 5, 5, 5));
		addButton = new JButton("<<<添加");
		removeButton = new JButton("移除>>>");
		removeButton.setVisible(false);
//		ysr8_TaskUse = new JComboBox();
//		UtilApi.getOptionValues(session, ysr8_TaskUse, strLOVTaskUse);
		ysr8_TaskUse = new LOVComboBox("YSR8_ScheduleTask01_LOV");
		workFlowTemp = new JComboBox();
		UtilApi.getOptionValues(session, workFlowTemp, strLOVWorkFlowTemp);
		taskReso = new iTextField(30);
		taskReso.setEditable(false);
		taskReso.setToolTipText("双击选择");
		final GCSelectionUserCommand selectionUserCmd = new GCSelectionUserCommand(AIFUtility.getCurrentApplication().getDesktop(), session);
		taskReso.addMouseListener(new MouseAdapter() {

			public void mouseClicked(MouseEvent mouseevent) {
				if (mouseevent.getClickCount() == 2) {
					isTranOwner.setSelected(false);
					selectionUserCmd.setContextBean(taskReso);
					try {
						selectionUserCmd.executeModal();
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		});
		isTranOwner = new JCheckBox("所有者转任务执行者");
		isTranOwner.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent arg0) {
				// TODO Auto-generated method stub
				if(isTranOwner.isSelected()){
					taskReso.setText("");
				}
			}
		});
		isDevi = new JCheckBox("关联交付对象版本到时间表");
		addButton.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent actionevent) {
				// TODO Auto-generated method stub
				addButtonListener();
			}
		});
		removeButton.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent actionevent) {
				// TODO Auto-generated method stub
				removeButtonListener();
			}
		});
		centerPanel.add("1.1.center.center",addButton);
		centerPanel.add("2.1.center.center",removeButton);
		centerPanel.add("3.1.left.center",new JLabel(" "));
		centerPanel.add("4.1.left.center",new JLabel("任务用途分类:"));
		centerPanel.add("5.1.left.center",ysr8_TaskUse);
		centerPanel.add("6.1.left.center",new JLabel("工作流触发流程模板:"));
		centerPanel.add("7.1.left.center",workFlowTemp);
		centerPanel.add("8.1.left.center",new JLabel("任务责任人:"));
		centerPanel.add("9.1.left.center",taskReso);
		centerPanel.add("10.1.left.center",new JLabel(" "));
		centerPanel.add("11.1.left.center",isTranOwner);
		//centerPanel.add("12.1.left.center",isDevi);
		add("1.2.left.center",centerPanel);
		
		try {
			TCComponent[] projectList = scheduleTag.getReferenceListProperty("project_list");
			if( projectList != null && projectList.length > 0){
				String project_id = projectList[0].getProperty("project_id");
				TCComponentItemType tccomItemType = (TCComponentItemType) session.getTypeComponent("Item");
				TCComponentItem systemPart = tccomItemType.find(project_id);
				if( systemPart != null){
					TCComponentItemRevision systemPartRevision = systemPart.getLatestItemRevision();
					TCComponentBOMLine bomLine=getBOMLine(session, systemPartRevision);
					CheckBoxTreeNode itemRevTop = new CheckBoxTreeNode(systemPartRevision);
					AIFComponentContext[] childLines = bomLine.getChildren();
					int childCount = bomLine.getChildrenCount();
					for(int ix = 0; ix < childCount; ix++ ){
						TCComponentBOMLine cl = (TCComponentBOMLine)childLines[ix].getComponent();
						String clt = cl.getItemRevision().getType();
						if(clt.equals("YSR8_MachPartsRevision") || clt.equals("YSR8_ElecPartsRevision")){
							CheckBoxTreeNode childTreeNode = new CheckBoxTreeNode(cl.getItemRevision());
							childTreeNode.setQuantity(cl.getProperty("bl_quantity"));
							itemRevTop.add(childTreeNode);
						}
					}
					
					DefaultTreeModel bomModel = new DefaultTreeModel(itemRevTop);  
					bomTree = new JTree(bomModel);
					bomTree.addMouseListener(new CheckBoxTreeNodeSelectionListener());
					bomTree.setCellRenderer(new CheckBoxTreeCellRenderer());
					JScrollPane jScrollPaneBom = new JScrollPane(bomTree);
					jScrollPaneBom.setPreferredSize(new Dimension(300, 400));
					add("1.3.left.center",jScrollPaneBom);
				}
			}
		} catch (TCException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		pack();
		centerToScreen();
		setVisible(true);
	}
	
	private void addButtonListener(){
		if(scheduleTree != null && bomTree != null ){
			DefaultMutableTreeNode scheduleNode = (DefaultMutableTreeNode) scheduleTree.getLastSelectedPathComponent();
			CheckBoxTreeNode bomNode = (CheckBoxTreeNode) bomTree.getModel().getRoot();
			if(scheduleNode != null){
				int bomNodeChildCount = bomNode.getChildCount();
				List<TCComponentItemRevision> systemPartRevisions = new ArrayList<TCComponentItemRevision>();
				List<String>quantity = new ArrayList<String>();
				for(int ix = 0; ix < bomNodeChildCount; ix++){
					CheckBoxTreeNode bomChildNode = (CheckBoxTreeNode) bomNode.getChildAt(ix);
					if(bomChildNode.isSelected){
//						TCComponentItemRevision systemPartRevision = (TCComponentItemRevision) bomChildNode.getUserObject();
//						System.out.println("systemPartRevision = "+systemPartRevision);
						systemPartRevisions.add((TCComponentItemRevision) bomChildNode.getUserObject());
						quantity.add(bomChildNode.getQuantity());
					}
				}
				TCUserService userService = (TCUserService) session.getUserService();
				Object objs[] = new Object[9];
				objs[0] = (TCComponentScheduleTask)((ScheduleTreeLine)scheduleNode.getUserObject()).getUserObject();
				objs[1] = systemPartRevisions.toArray();
				if(ysr8_TaskUse.getSelectedItem() != null ){
					objs[2] = ysr8_TaskUse.getSelectedDisplayString();
					objs[8] = ysr8_TaskUse.getSelectedItem();
				}else{
					objs[2] = "";
					objs[8] = "-1";
				}
				if(workFlowTemp.getSelectedItem() != null){
					objs[3] = workFlowTemp.getSelectedItem();
				}else{
					objs[3] = "";
				}
				objs[4] = isTranOwner.isSelected();
				objs[5] = isDevi.isSelected();
				objs[6] = quantity.toArray();
				objs[7] = taskReso.getText();
				try {
					Object[] reb = (Object[])userService.call("BOM_Trans_Plan", objs);
					if( reb != null ){
						int rebCnt = reb.length;
						System.out.println("reb.length = "+rebCnt);
						ScheduleTreeLine parentTreeLine = (ScheduleTreeLine)scheduleNode.getUserObject();
						for(int ix = 0; ix < rebCnt; ix++ ){
							populateTask(parentTreeLine, (TCComponent)reb[ix], scheduleNode);
						}
						scheduleTree.repaint();
						scheduleTree.updateUI();
						scheduleTag.refresh();
					}
				} catch (TCException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
	
	private void removeButtonListener(){
		
	}
	
	private void initTreeTableModel(TCComponentSchedule scheduleTag, DefaultMutableTreeNode top) {
		try {
			TCComponent scheduleTask = ScheduleHelper.getScheduleSummaryTask(scheduleTag);
			TCProperty tcproperty = scheduleTask.getTCProperty("child_task_taglist");
			TCComponent atccomponent[] = tcproperty.getReferenceValueArray();
			for (int l = 0; l < atccomponent.length; l++)
				populateTask(rootscheduleTreeLine, atccomponent[l], top);

		} catch (TCException e) {
			e.printStackTrace();
		}
	}

	public void populateTask(ScheduleTreeLine parentScheduleTreeLine, TCComponent tccomponent, DefaultMutableTreeNode parentTreeNode) {
		if (tccomponent != null) {
			ScheduleTreeLine scheduletreeline = new ScheduleTreeLine(tccomponent);
			DefaultMutableTreeNode treeNode = new DefaultMutableTreeNode(scheduletreeline); 
			parentTreeNode.add(treeNode);
			parentScheduleTreeLine.add(scheduletreeline);
			try {
				TCComponent atccomponent[] = TaskHelper.getChildTasks((TCComponentScheduleTask) tccomponent);
				for (int i = 0; i < atccomponent.length; i++)
					populateTask(scheduletreeline, atccomponent[i], treeNode);

			} catch (TCException tcexception) {
				tcexception.printStackTrace();
			}
		}
	}
	
	/** 
	 * 自定义树描述类,将树的每个节点设置成不同的图标 
	 * @author 
	 * 
	 */  
	public class ScheduleDefaultTreeCellRenderer extends DefaultTreeCellRenderer  
	{  
	    /** 
	     * ID 
	     */  
	    private static final long   serialVersionUID    = 1L;  
	  
	    /** 
	     * 重写父类DefaultTreeCellRenderer的方法 
	     */  
	    @Override  
	    public Component getTreeCellRendererComponent(JTree tree, Object value,  
	            boolean sel, boolean expanded, boolean leaf, int row,  
	            boolean hasFocus)  
	    {  
	  
	        //执行父类原型操作  
	        super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus);  
	  
//	        setText(value.toString());  
	          
	        if (sel)  
	        {  
	            setForeground(getTextSelectionColor());  
	        }  
	        else  
	        {  
	            setForeground(getTextNonSelectionColor());  
	        }  
	          
	        //得到每个节点的TreeNode  
	        DefaultMutableTreeNode node = (DefaultMutableTreeNode) value;  
	        
	        this.setIcon(TCTypeRenderer.getIcon(((ScheduleTreeLine)node.getUserObject()).getUserObject()));  
	  
	        return this;  
	    }  
	}  
	public static TCComponentBOMLine getBOMLine(TCSession session, TCComponentItemRevision revision) {
		TCComponentBOMLine bomLine = null;
		try {
			// 获取版本规则
			TCComponentRevisionRuleType revRuleType = (TCComponentRevisionRuleType) session.getTypeComponent("RevisionRule");
			TCComponentRevisionRule revRule = revRuleType.getDefaultRule();
			// 创建BOMWindow
			TCComponentBOMWindowType bomWinType = (TCComponentBOMWindowType) session.getTypeComponent("BOMWindow");
			TCComponentBOMWindow window = bomWinType.create(revRule);
			window.lock();
			bomLine = window.setWindowTopLine(revision.getItem(), revision, null, null);
			window.unlock();
		} catch (TCException e) {
			e.printStackTrace();
		}
		return bomLine;
	}

	@Override
	public void windowActivated(WindowEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void windowClosed(WindowEvent arg0) {
		// TODO Auto-generated method stub
		ReloadOperation reloadoperation = new ReloadOperation(application);
        try {
			reloadoperation.executeOperation();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public void windowClosing(WindowEvent arg0) {
		// TODO Auto-generated method stub
	}

	@Override
	public void windowDeactivated(WindowEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void windowDeiconified(WindowEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void windowIconified(WindowEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void windowOpened(WindowEvent arg0) {
		// TODO Auto-generated method stub
		
	}
}
