package cn.com.teamcenter.rac.form;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Vector;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.border.EmptyBorder;
import javax.swing.border.TitledBorder;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;

import com.teamcenter.rac.aif.AbstractAIFDialog;
import com.teamcenter.rac.aif.kernel.AIFComponentContext;
import com.teamcenter.rac.aifrcp.AIFUtility;
import com.teamcenter.rac.commands.open.OpenFormDialog;
import com.teamcenter.rac.common.organization.OrgTreePanel;
import com.teamcenter.rac.common.organization.OrganizationTree;
import com.teamcenter.rac.kernel.TCComponent;
import com.teamcenter.rac.kernel.TCComponentForm;
import com.teamcenter.rac.kernel.TCComponentGroup;
import com.teamcenter.rac.kernel.TCComponentGroupMember;
import com.teamcenter.rac.kernel.TCComponentItem;
import com.teamcenter.rac.kernel.TCComponentItemType;
import com.teamcenter.rac.kernel.TCComponentProject;
import com.teamcenter.rac.kernel.TCComponentRole;
import com.teamcenter.rac.kernel.TCComponentSchedule;
import com.teamcenter.rac.kernel.TCComponentUser;
import com.teamcenter.rac.kernel.TCException;
import com.teamcenter.rac.kernel.TCFormProperty;
import com.teamcenter.rac.kernel.TCPreferenceService;
import com.teamcenter.rac.kernel.TCSession;
import com.teamcenter.rac.kernel.TCUserService;
import com.teamcenter.rac.stylesheet.AbstractRendering;
import com.teamcenter.rac.stylesheet.PropertyDateButton;
import com.teamcenter.rac.util.DateButton;
import com.teamcenter.rac.util.MessageBox;
import com.teamcenter.rac.util.PropertyLayout;
import com.teamcenter.rac.util.iTextArea;
import com.teamcenter.rac.util.iTextField;

import cn.com.customization.util.KUtil;
import cn.com.customization.util.UtilApi;

public class YSR8_ProjectForm extends AbstractRendering {

	private static final long serialVersionUID = 1L;
	private TCSession session = null;
	private TCComponentForm ysr8ProjectForm = null;
	private TCComponentSchedule schedule;
	private TCComponentProject projectComp;

	private DateButton dateUpdateTime;
	private JButton btnUpdateData;
	private iTextField ysr8_QuotationNo; // 报价单编号
	private iTextField ysr8_ProjectCode; // 订货单编号
	private iTextField ysr8_ProjectName; // 项目名称
	private iTextField ysr8_OrderManufacturer; // 订货厂家
	private iTextField ysr8_CustomerName; // 用户名称
	private iTextField ysr8_ProjectCategory; // 项目类别
	private iTextField ysr8_Factory; // 厂别
	private iTextField ysr8_Product; // 产品
	private iTextField ysr8_Use; // 用途
	private iTextArea ysr8_ProjectContent; // 项目内容
	private iTextField ysr8_FixtrueCount; // 夹具数量
	private iTextField ysr8_AttachCount; // 附具数量
	private iTextField ysr8_GuidCount; // 安全栏
	private iTextField ysr8_JigCount; // 变位机
	private iTextField ysr8_PositionerCount; // 外委数
	private iTextField ysr8_RobotCount; // 机器人数
	private iTextArea ysr8_RobotModel; // 机器人型号
	private DateButton ysr8_ReceiveDate; // 订单下发日期
	private DateButton ysr8_SaleStartDate; // 销售启动日期
	private DateButton ysr8_StartDate; // 系统科启动日期
	private DateButton ysr8_ContractDate; // 签订合同日期
	private DateButton ysr8_ActualFactoryDate; // 实际出厂时间
	private DateButton ysr8_PlanDeliveryDate; // 交货时间（启动通知）
	private DateButton ysr8_ActualDeliveryDate; // 交货时间（合同）
	private DateButton ysr8_ProductionDate; // 量产预定时间
	private DateButton ysr8_PlanAcceptance; // 计划验收日期
	private DateButton ysr8_FinalAcceptance; // 实际验收日期

	private DefaultTableModel modMilestone;
	private DefaultTableModel modKeyTasks;
	private DefaultTableModel modMembers;

	private JTable tblProjectMilestone;// 项目里程碑
	private JTable tblProjectKeyTasks; // 项目关键任务
	private JTable tblProjectMembers; // 项目人员

	private iTextField ysr8_ProjectManager; // 项目经理
	private iTextField ysr8_Planner; // 计划管理员
	private iTextField ysr8_DesignDirector; // 设计主管
	private iTextField ysr8_ElectricDirector; // 电气主管
	private iTextField ysr8_Purcher; // 采购负责人
	private iTextField ysr8_Machiner; // 加工负责人
	private iTextField ysr8_EngineerDebug; // 工程调试人员
	private iTextField ysr8_ElecDebug; // 电气调试人员
	private iTextField ysr8_Sales; // 销售负责人

	private JButton btnAddMember;
	private JButton btnRemoveMember;

	private Vector<TCComponentUser> vtProjectAdmin;
	// private Vector<TCComponentUser> vtProjectMembers;
	private Vector<TCComponentGroupMember> vtProjectMembers;
	private Vector<TCComponentUser> vtPrivilegedUsers;
	private HashMap<TCComponentUser, String> hmUserRole;
	private String[] arrMilestoneTaskProp;
	private String[] arrKeyTaskProp;
	private JDialog dlg;

	private Vector<Component> allComponents = new Vector<Component>();
	private TCFormProperty[] formProperties;
	private Hashtable<TCFormProperty, JComponent> indices = new Hashtable<TCFormProperty, JComponent>();
	private static SimpleDateFormat format = new SimpleDateFormat("yyyy.MM.dd");

	public YSR8_ProjectForm(TCComponentForm form) throws Exception {
		super(form);
		//  Auto-generated constructor stub
		this.ysr8ProjectForm = form;
		session = ysr8ProjectForm.getSession();

		addUIComponents();
		initUI();
		loadRendering();

		getSchedule();
		getScheduleTasks();
		getMilestoneTaskInfo();
		getKeyTaskInfo();
		loadProjectMember();
	}
	
	

	@Override
	public void displayDialog(AbstractAIFDialog arg0, boolean arg1) {
		KUtil.fitToScreen(arg0);
		super.displayDialog(arg0, arg1);
	}



	@Override
	public void displayDialog(OpenFormDialog arg0, boolean arg1) {
		KUtil.fitToScreen(arg0);
		super.displayDialog(arg0, arg1);
	}



	private void initUI() {

		// JPanel projectBasicInfo = new JPanel(new BorderLayout());
		// projectBasicInfo.add(BorderLayout.NORTH, initProjectBasicInfo());
		// JPanel projectPersonInfo = new JPanel(new BorderLayout());

		JTabbedPane tabPane = new JTabbedPane();
		tabPane.addTab("项目基础信息", initProjectBasicInfo());
		tabPane.addTab("项目人员信息", initProjectPersonInfo());

		setLayout(new GridLayout());
		add(tabPane);
	}

	private JScrollPane initProjectBasicInfo() {

		JPanel paneUpdate = new JPanel(new PropertyLayout(5, 5, 5, 5, 5, 0));
		paneUpdate.add("1.1.right.right", new JLabel("更新时间:    "));
		paneUpdate.add("1.2.right.right", dateUpdateTime);
		paneUpdate.add("1.3.right.right", btnUpdateData);

		JPanel paneBasic = new JPanel(new GridBagLayout());
		GridBagConstraints g4 = new GridBagConstraints();
		g4.insets = new Insets(5, 5, 5, 5);
		g4.anchor = GridBagConstraints.WEST;
		g4.fill = GridBagConstraints.HORIZONTAL;
		
		g4.gridx = 0;
		g4.gridy = 0;
		paneBasic.add(new JLabel("项目名称:"), g4);

		g4.gridx = 1;
		g4.gridy = 0;
		g4.gridwidth=3;
		paneBasic.add(ysr8_ProjectName, g4);
		g4.gridwidth=1;

		g4.gridx = 0;
		g4.gridy = 1;
		paneBasic.add(new JLabel("项目内容:"), g4);

		g4.gridx = 1;
		g4.gridy = 1;
		g4.gridheight = 4;
		g4.gridwidth=3;
		paneBasic.add(new JScrollPane(ysr8_ProjectContent), g4);
		g4.gridwidth=1;
		g4.gridheight=1;
		
		g4.gridwidth = 1;
		g4.gridx = 0;
		g4.gridy = 5;
		paneBasic.add(new JLabel("报价单编号:"), g4);

		g4.gridx = 1;
		paneBasic.add(ysr8_QuotationNo, g4);

		g4.gridx = 2;
		paneBasic.add(new JLabel("订货单编号:"), g4);

		g4.gridx = 3;
		paneBasic.add(ysr8_ProjectCode, g4);

		g4.gridx = 0;
		g4.gridy++;
		paneBasic.add(new JLabel("订货厂家:"), g4);

		g4.gridx = 1;
		g4.gridwidth = 3;
		paneBasic.add(ysr8_OrderManufacturer, g4);

		g4.gridx = 0;
		g4.gridy++;
		paneBasic.add(new JLabel("用户名称:"), g4);

		g4.gridx = 1;
		g4.gridwidth = 3;
		paneBasic.add(ysr8_CustomerName, g4);

		g4.gridwidth = 1;
		g4.gridx = 0;
		g4.gridy++;
		paneBasic.add(new JLabel("项目类别:"), g4);

		g4.gridx = 1;
		paneBasic.add(ysr8_ProjectCategory, g4);

		g4.gridx = 2;
		paneBasic.add(new JLabel("厂别:"), g4);

		g4.gridx = 3;
		paneBasic.add(ysr8_Factory, g4);

		g4.gridx = 0;
		g4.gridy++;
		paneBasic.add(new JLabel("产品:"), g4);

		g4.gridx = 1;
		paneBasic.add(ysr8_Product, g4);

		g4.gridx = 2;
		paneBasic.add(new JLabel("用途:"), g4);

		g4.gridx = 3;
		paneBasic.add(ysr8_Use, g4);

		

		/*JPanel paneCount = new JPanel(new GridBagLayout());
		GridBagConstraints g3 = new GridBagConstraints();
		g3.insets = new Insets(5, 5, 5, 5);
		g3.anchor = GridBagConstraints.WEST;
		g3.fill = GridBagConstraints.HORIZONTAL;

		g3.gridwidth = 1;
		g3.gridx = 0;
		g3.gridy = 0;
		paneCount.add(new JLabel("夹具数量:"), g3);

		g3.gridx = 1;
		g3.gridy = 0;
		paneCount.add(ysr8_FixtrueCount, g3);

		g3.gridx = 2;
		g3.gridy = 0;
		paneCount.add(new JLabel("附具数量:"), g3);

		g3.gridx = 3;
		g3.gridy = 0;
		paneCount.add(ysr8_AttachCount, g3);

		g3.gridx = 4;
		g3.gridy = 0;
		paneCount.add(new JLabel("安全栏:"), g3);

		g3.gridx = 5;
		g3.gridy = 0;
		paneCount.add(ysr8_GuidCount, g3);

		g3.gridx = 0;
		g3.gridy = 1;
		paneCount.add(new JLabel("变位机:"), g3);

		g3.gridx = 1;
		g3.gridy = 1;
		paneCount.add(ysr8_JigCount, g3);

		g3.gridx = 2;
		g3.gridy = 1;
		paneCount.add(new JLabel("外委数:"), g3);

		g3.gridx = 3;
		g3.gridy = 1;
		paneCount.add(ysr8_PositionerCount, g3);

		g3.gridx = 4;
		g3.gridy = 1;
		paneCount.add(new JLabel("机器人数:"), g3);

		g3.gridx = 5;
		g3.gridy = 1;
		paneCount.add(ysr8_RobotCount, g3);

		g3.gridx = 0;
		g3.gridy = 2;
		paneCount.add(new JLabel("机器人型号:"), g3);

		g3.gridx = 1;
		g3.gridy = 2;
		g3.gridheight = 2;
		g3.gridwidth=5;
		JScrollPane scrollPane = new JScrollPane(ysr8_RobotModel);
		scrollPane.setPreferredSize(new Dimension(755, 57));
		paneCount.add(scrollPane, g3);
		g3.gridwidth=1;*/

		JPanel pane1 = new JPanel(new GridBagLayout());
		GridBagConstraints g2 = new GridBagConstraints();
		g2.insets = new Insets(5, 5, 5, 5);
		g2.anchor = GridBagConstraints.WEST;
		g2.fill = GridBagConstraints.HORIZONTAL;

		g2.gridx = 0;
		g2.gridy = 0;
		pane1.add(new JLabel("订单下发:　"), g2);

		g2.gridx = 1;
		g2.gridy = 0;
		ysr8_ReceiveDate.setPreferredSize(new Dimension(133, 23));
		pane1.add(ysr8_ReceiveDate, g2);

		g2.gridx = 2;
		g2.gridy = 0;
		pane1.add(new JLabel("销售启动:"), g2);

		g2.gridx = 3;
		g2.gridy = 0;
		ysr8_SaleStartDate.setPreferredSize(new Dimension(133, 23));
		pane1.add(ysr8_SaleStartDate, g2);

		g2.gridx = 4;
		g2.gridy = 0;
		pane1.add(new JLabel("系统科启动:"), g2);

		g2.gridx = 5;
		g2.gridy = 0;
		ysr8_StartDate.setPreferredSize(new Dimension(133, 23));
		pane1.add(ysr8_StartDate, g2);

		g2.gridx = 6;
		g2.gridy = 0;
		pane1.add(new JLabel("签订合同:"), g2);

		g2.gridx = 7;
		g2.gridy = 0;
		ysr8_ContractDate.setPreferredSize(new Dimension(132, 23));
		pane1.add(ysr8_ContractDate, g2);

		JPanel pane2 = new JPanel(new GridBagLayout());
		GridBagConstraints g1 = new GridBagConstraints();
		g1.insets = new Insets(5, 5, 5, 5);
		g1.anchor = GridBagConstraints.WEST;
		g1.fill = GridBagConstraints.HORIZONTAL;

		g1.gridx = 0;
		g1.gridy = 0;
		pane2.add(new JLabel("实际出厂时间:"), g1);

		g1.gridx = 1;
		g1.gridy = 0;
		ysr8_ActualFactoryDate.setPreferredSize(new Dimension(161, 23));
		pane2.add(ysr8_ActualFactoryDate, g1);

		g1.gridx = 2;
		g1.gridy = 0;
		pane2.add(new JLabel("交货时间（启动通知）:"), g1);

		g1.gridx = 3;
		g1.gridy = 0;
		ysr8_PlanDeliveryDate.setPreferredSize(new Dimension(161, 23));
		pane2.add(ysr8_PlanDeliveryDate, g1);

		g1.gridx = 4;
		g1.gridy = 0;
		pane2.add(new JLabel("交货时间（合同）:"), g1);

		g1.gridx = 5;
		g1.gridy = 0;
		ysr8_ActualDeliveryDate.setPreferredSize(new Dimension(160, 23));
		pane2.add(ysr8_ActualDeliveryDate, g1);

		g1.gridx = 0;
		g1.gridy = 1;
		pane2.add(new JLabel("量产预定时间:"), g1);

		g1.gridx = 1;
		g1.gridy = 1;
		pane2.add(ysr8_ProductionDate, g1);

		g1.gridx = 2;
		g1.gridy = 1;
		pane2.add(new JLabel("计划验收日期:"), g1);

		g1.gridx = 3;
		g1.gridy = 1;
		pane2.add(ysr8_PlanAcceptance, g1);

		g1.gridx = 4;
		g1.gridy = 1;
		pane2.add(new JLabel("实际验收日期:"), g1);

		g1.gridx = 5;
		g1.gridy = 1;
		pane2.add(ysr8_FinalAcceptance, g1);

		// 项目里程碑
		JPanel paneMilestone = new JPanel(new BorderLayout());
		paneMilestone.setBorder(new TitledBorder(BorderFactory.createEtchedBorder(), "项目里程碑"));
		String[] arrMilestoneTitle = new String[] { "里程碑", "完成情况", "倒计时", "计划完成时间", "实际完成时间", "描述" };
		modMilestone = new DefaultTableModel(new Object[0][6], arrMilestoneTitle) {

			private static final long serialVersionUID = 1L;

			public boolean isCellEditable(int row, int column) {
				return false;
			}
		};

		tblProjectMilestone = new JTable(modMilestone);
		tblProjectMilestone.setDefaultRenderer(Object.class, new ORTableColorRender());
		tblProjectMilestone.setColumnSelectionAllowed(false);
		tblProjectMilestone.getTableHeader().setReorderingAllowed(false);

		JScrollPane jspMilestone = new JScrollPane(tblProjectMilestone);
		paneMilestone.add(BorderLayout.CENTER, jspMilestone);
		paneMilestone.setPreferredSize(new Dimension(835, 150));
		tblProjectMilestone.addMouseListener(new MouseListener() {

			@Override
			public void mouseClicked(MouseEvent e) {
				if (e.getClickCount() == 1) {
					for (int i = 0; i <= 5; i++) {
						if (i != 1) {
							TableColumn column = tblProjectMilestone.getColumnModel().getColumn(i);
							column.setCellRenderer(new DefaultTableCellRenderer());
						}
					}
				}
			}

			@Override
			public void mouseEntered(MouseEvent e) {

			}

			@Override
			public void mouseExited(MouseEvent e) {
				
			}

			@Override
			public void mousePressed(MouseEvent e) {

			}

			@Override
			public void mouseReleased(MouseEvent e) {

			}

		});

		// 项目关键任务
		JPanel paneKeyTasks = new JPanel(new BorderLayout());
		paneKeyTasks.setBorder(new TitledBorder(BorderFactory.createEtchedBorder(), "项目关键任务"));
		String[] arrKeyTasksTitle = new String[] { "项目任务", "完成情况", "倒计时", "任务状态", "描述", "计划开始时间", "计划完成时间", "实际开始时间", "实际完成时间" };
		modKeyTasks = new DefaultTableModel(new Object[0][9], arrKeyTasksTitle) {

			private static final long serialVersionUID = 1L;

			public boolean isCellEditable(int row, int column) {
				return false;
			}
		};
		tblProjectKeyTasks = new JTable(modKeyTasks);
		tblProjectKeyTasks.setDefaultRenderer(Object.class, new ORTableColorRender());
		tblProjectKeyTasks.getTableHeader().setReorderingAllowed(false);

		JScrollPane jspKeyTasks = new JScrollPane(tblProjectKeyTasks);
		paneKeyTasks.add(BorderLayout.CENTER, jspKeyTasks);
		paneKeyTasks.setPreferredSize(new Dimension(835, 150));
		tblProjectKeyTasks.addMouseListener(new MouseListener() {

			@Override
			public void mouseClicked(MouseEvent e) {
				if (e.getClickCount() == 1) {
					for (int i = 0; i <= 8; i++) {
						if (i != 1) {
							TableColumn column = tblProjectKeyTasks.getColumnModel().getColumn(i);
							column.setCellRenderer(new DefaultTableCellRenderer());
						}
					}
				}
			}

			@Override
			public void mouseEntered(MouseEvent e) {

			}

			@Override
			public void mouseExited(MouseEvent e) {
				
			}

			@Override
			public void mousePressed(MouseEvent e) {
				
			}

			@Override
			public void mouseReleased(MouseEvent e) {
				
			}
		});

		JPanel paneProjectBasicInfo = new JPanel();
		paneProjectBasicInfo.setLayout(new PropertyLayout());
		//int width=(int) paneBasic.getPreferredSize().getWidth();
		//paneCount.setPreferredSize(new Dimension(width, (int)paneCount.getPreferredSize().getHeight()));
		paneProjectBasicInfo.add("1.1.left.center", paneUpdate);
		paneProjectBasicInfo.add("2.1.left.center", paneBasic);
//		paneProjectBasicInfo.add("3.1.left.center", paneCount);
		paneProjectBasicInfo.add("3.1.left.center", pane1);
		paneProjectBasicInfo.add("4.1.left.center", pane2);
		paneProjectBasicInfo.add("5.1.left.center", paneMilestone);
		paneProjectBasicInfo.add("6.1.left.center", paneKeyTasks);

		JScrollPane sMain = new JScrollPane(paneProjectBasicInfo);
		return sMain;
	}

	private JScrollPane initProjectPersonInfo() {

		JPanel topPanel = new JPanel();
		topPanel.setLayout(new PropertyLayout(10,7,5,5,5,5));

		topPanel.add("1.1.left.center", new JLabel("项目经理:"));
		topPanel.add("1.2.left.center", ysr8_ProjectManager);
		topPanel.add("1.3.left.center", new JLabel("计划管理员:"));
		topPanel.add("1.4.left.center", ysr8_Planner);
		topPanel.add("1.5.left.center", new JLabel("机械设计主管:"));
		//  hubing 20180615
		topPanel.add("1.6.left.center", ysr8_DesignDirector);
		topPanel.add("2.1.left.center", new JLabel("电气设计:"));
		topPanel.add("2.2.left.center", ysr8_ElectricDirector);
		topPanel.add("2.3.left.center", new JLabel("采购负责人:"));
		topPanel.add("2.4.left.center", ysr8_Purcher);
		topPanel.add("2.5.left.center", new JLabel("加工负责人:　"));
		topPanel.add("2.6.left.center", ysr8_Machiner);
		topPanel.add("3.1.left.center", new JLabel("工程调试人员:"));
		topPanel.add("3.2.left.center", ysr8_EngineerDebug);
		topPanel.add("3.3.left.center", new JLabel("电气调试员:"));
		topPanel.add("3.4.left.center", ysr8_ElecDebug);
		topPanel.add("3.5.left.center", new JLabel("销售负责人:　"));
		topPanel.add("3.6.left.center", ysr8_Sales);

		String[] arrMemberTitle = new String[] { "项目角色", "组织角色", "项目人员（姓名）", "联系电话" };
		modMembers = new DefaultTableModel(new Object[0][4], arrMemberTitle) {
			private static final long serialVersionUID = 1L;

			public boolean isCellEditable(int row, int column) {
				return false;
			}
		};
		tblProjectMembers = new JTable(modMembers);
		tblProjectMembers.getTableHeader().setReorderingAllowed(false);
		JScrollPane jspMembers = new JScrollPane(tblProjectMembers);
		jspMembers.setPreferredSize(new Dimension(946, 300));

		btnAddMember = new JButton("添加人员");
		btnAddMember.setVisible(false);
		btnAddMember.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				if (checkPrivilege()) {
					AddMember();
				}
			}
		});
		btnRemoveMember = new JButton("移除人员");
		btnRemoveMember.setVisible(false);
		btnRemoveMember.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				if (checkPrivilege()) {
					removeMember();
				}
			}
		});
		JPanel paneButton = new JPanel(new PropertyLayout());
		paneButton.add("1.1.left.center", btnAddMember);
		paneButton.add("2.1.left.center", btnRemoveMember);

		JPanel panelMember = new JPanel(new PropertyLayout());
		panelMember.add("1.1.left.center", jspMembers);
		panelMember.add("1.2.left.center", paneButton);

		JPanel paneProjectPersonInfo = new JPanel();
		paneProjectPersonInfo.setBorder(new EmptyBorder(5, 5, 5, 5));
		paneProjectPersonInfo.setLayout(new PropertyLayout());
		paneProjectPersonInfo.add("1.1.left.center", topPanel);
		paneProjectPersonInfo.add("2.1.left.center", panelMember);

		JScrollPane sMain = new JScrollPane(paneProjectPersonInfo);
		return sMain;
	}

	@Override
	public void loadRendering() throws TCException {
		//  Auto-generated method stub
		try {
			this.formProperties = ysr8ProjectForm.getAllFormProperties();
			int length = this.formProperties.length;
			int pSize = allComponents.size();
			for (int k = 0; k < length; ++k) {
				String propName = this.formProperties[k].getPropertyName().trim();
				// System.out.println("propName="+propName);
				for (int i = 0; i < pSize; i++) {
					Component component = allComponents.get(i);
					String name = component.getName();
					if (component instanceof iTextField) {
						iTextField textField = (iTextField) component;
						if (propName.equalsIgnoreCase(name)) {
							textField.setText(this.formProperties[k].getStringValue());
							indices.put(formProperties[k], textField);
							break;
						}
					} else if (component instanceof JTextArea) {
						JTextArea textArea = (JTextArea) component;
						if (propName.equalsIgnoreCase(name)) {
							textArea.setText(this.formProperties[k].getStringValue());
							indices.put(formProperties[k], textArea);
							break;
						}
					} else if (component instanceof JComboBox) {
						JComboBox combox = (JComboBox) component;
						if (propName.equalsIgnoreCase(name)) {
							combox.setSelectedItem(this.formProperties[k].getStringValue());
							indices.put(formProperties[k], combox);
							break;
						}
					} else if (component instanceof DateButton) {
						DateButton btn = (DateButton) component;
						if (propName.equalsIgnoreCase(name)) {
							btn.setDate(formProperties[k].getDateValue());
							indices.put(formProperties[k], btn);
							break;
						}
					}
				}
			}
		} catch (TCException imanexception) {
			throw imanexception;
		}
	}

	@Override
	public void saveRendering() {
		//  Auto-generated method stub
		Enumeration<TCFormProperty> enumeration = this.indices.keys();
		Enumeration<JComponent> enumeration1 = this.indices.elements();
		TCFormProperty[] aimanformproperty = new TCFormProperty[this.indices.size()];
		try {
			for (int i = 0; enumeration.hasMoreElements(); i++) {
				TCFormProperty imanformproperty = (TCFormProperty) enumeration.nextElement();
				Object component = enumeration1.nextElement();
				//String propName = imanformproperty.getPropertyName();
				if (component instanceof iTextField) {
					//setByPass(true);
					//System.out.println("属性："+imanformproperty.getName()+" = "+((iTextField) component).getText().toString());
					setStringToPropertyValue(imanformproperty, ((iTextField) component).getText().toString());
					//setByPass(false);
				} else if (component instanceof JTextArea) {
					setStringToPropertyValue(imanformproperty, ((JTextArea) component).getText().toString());
				} else if (component instanceof JComboBox) {
					setStringToPropertyValue(imanformproperty, ((JComboBox) component).getSelectedItem().toString());
				} else if (component instanceof DateButton) {
					DateButton btn = (DateButton) component;
					if (btn.getDate() != null) {
						imanformproperty.setDateValue(btn.getDate());
					} else {
						imanformproperty.setDateValue(null);
					}
				}
				aimanformproperty[i] = imanformproperty;
			}
			try {
				ysr8ProjectForm.setTCProperties(aimanformproperty);
			} catch (Exception exception) {
				exception.printStackTrace();
				MessageBox.post(exception);
			}
		} catch (TCException imane) {
			imane.printStackTrace();
		}

		updateProjectMember();
	}

	public static void setByPass(boolean val) throws TCException {
		TCUserService userservice = null;
		if (userservice == null) {
			userservice = ((TCSession) AIFUtility.getCurrentApplication().getSession()).getUserService();
		}
		Object[] obj = new Object[1];
		obj[0] = "origin";
		if (val) {
			userservice.call("YSR_set_bypass", obj);
		} else {
			userservice.call("YSR_close_bypass", obj);
		}
	}
	@Override
	public boolean isRenderingModified() {
		Enumeration<TCFormProperty> enumeration = this.indices.keys();
		Enumeration<JComponent> enumeration1 = this.indices.elements();
		for (int i = 0; enumeration.hasMoreElements(); i++) {
			TCFormProperty imanformproperty = (TCFormProperty) enumeration.nextElement();
			Object component = enumeration1.nextElement();
			if (component instanceof iTextField) {
				String strTempValue = ((iTextField) component).getText().toString();
				if (!imanformproperty.getStringValue().equals(strTempValue)) {
					return true;
				}
			} else if (component instanceof iTextArea) {
				String strTempValue = ((iTextArea) component).getText().toString();
				if (!imanformproperty.getStringValue().equals(strTempValue)) {
					return true;
				}
			} else if (component instanceof JComboBox) {
				String strTempValue = ((JComboBox) component).getSelectedItem().toString();
				if (!imanformproperty.getStringValue().equals(strTempValue)) {
					return true;
				}
			} else if (component instanceof DateButton) {
				DateButton btn = (DateButton) component;
				if (imanformproperty.getDateValue() != null && btn.getDate() != null) {
					if (imanformproperty.getDateValue().getTime() != btn.getDate().getTime()) {
						return true;
					}
				} else if (imanformproperty.getDateValue() != null && btn.getDate() == null) {
					return true;
				} else if (imanformproperty.getDateValue() == null && btn.getDate() != null) {
					return true;
				}
			}
		}
		return false;
	}
	//kk 首选项增加多个角色配置，用;隔开
	public String getUserNames(String orgName) {
		String[] orgNameSplit = orgName.split(";");
		StringBuilder res=new StringBuilder();
		for (String org : orgNameSplit) {
			String val=getPropertyValue2(org);
			if(!"".equals(val)) {
				res.append(val).append(";");
			}
		}
		if(res.length()>0) {
			res.setLength(res.length()-1);
		}
		return res.toString();
	}

	public String getPropertyValue2(String orgName) {
		String value = "";
		if(orgName==null||"".equals(orgName)) {
			return value;
		}
		//kk 首选项增加两个配置项，写在等号右边
		if("项目小组管理员".equals(orgName)) {
			TCComponent[] comps;
			try {
				comps = schedule.getReferenceListProperty("project_list");
				if (comps != null && comps.length > 0) {
					projectComp = (TCComponentProject) comps[0];
				}
				if (projectComp == null) {
					return value;
				}
				TCComponentUser[] admins = (TCComponentUser[])projectComp.getTeam().get(1);
				StringBuilder valueB = new StringBuilder();
				for (TCComponentUser admin : admins) {
					valueB.append(admin.getStringProperty("user_name")).append(";");
				}
				if(valueB.length()>0) {
					valueB.setLength(valueB.length()-1);
				}
				value = valueB.toString();
				return value;
			} catch (TCException e) {
				e.printStackTrace();
				return value;
			}
		}else if("项目所有者".equals(orgName)) {
			TCComponent[] comps;
			try {
				comps = schedule.getReferenceListProperty("project_list");
				if (comps != null && comps.length > 0) {
					projectComp = (TCComponentProject) comps[0];
				}
				if (projectComp == null) {
					return value;
				}
				TCComponentUser user=(TCComponentUser) projectComp.getReferenceProperty("owning_user");
				value=user.getStringProperty("user_name");
				return value;
			} catch (TCException e) {
				e.printStackTrace();
				return value;
			}
		}
		StringBuilder valueB = new StringBuilder();
		int rowCount = tblProjectMembers.getRowCount();
		for (int i = 0; i < rowCount; i++) {
			Object orgObj = tblProjectMembers.getModel().getValueAt(i, 1);
			Object userNameObj = tblProjectMembers.getModel().getValueAt(i, 2);
			String orgStr = orgObj == null ? "" : orgObj.toString();
			String userNameStr = userNameObj == null ? "" : userNameObj.toString();
			if (orgName.equalsIgnoreCase(orgStr)) {
				valueB.append(userNameStr).append(";");
			}
		}
		if(valueB.length()>0) {
			valueB.setLength(valueB.length()-1);
		}
		value = valueB.toString();
		if (value.endsWith(";")) {
			value.substring(0, value.length() - 1);
		}

		return value;
	}

	private void getPropertyValueByPreference() {
		ysr8_ProjectManager.setName("ysr8_ProjectManager");
		ysr8_Planner.setName("ysr8_Planner");
		ysr8_EngineerDebug.setName("ysr8_EngineerDebug");
		ysr8_ElecDebug.setName("ysr8_ElecDebug");
		ysr8_Sales.setName("ysr8_Sales");
		ysr8_DesignDirector.setName("ysr8_DesignDirector");
		ysr8_ElectricDirector.setName("ysr8_ElectricDirector");
		ysr8_Purcher.setName("ysr8_Purcher");
		ysr8_Machiner.setName("ysr8_Machiner");

		TCPreferenceService service = session.getPreferenceService();

		String[] values = service.getStringValues("YSR_ProjectForm_Personnel");
		if (values == null || values.length < 2) {
			return;
		}
		for (String value : values) {
			String[] names = value.split("=");
			if (names == null || names.length < 2) {
				continue;
			}
			String propName = names[0];
			String orgName = names[1];
			//System.out.println(propName);
			switch (propName) {
			case "ysr8_ProjectManager":
				ysr8_ProjectManager.setText(getUserNames(orgName));
				break;
			case "ysr8_Planner":
				ysr8_Planner.setText(getUserNames(orgName));
				break;
			case "ysr8_EngineerDebug":
				ysr8_EngineerDebug.setText(getUserNames(orgName));
				break;
			case "ysr8_ElecDebug":
				ysr8_ElecDebug.setText(getUserNames(orgName));
				break;
			case "ysr8_Sales":
				ysr8_Sales.setText(getUserNames(orgName));
				break;
			case "ysr8_DesignDirector":
				//System.out.println(getUserNames(orgName)+"@"+orgName);
				ysr8_DesignDirector.setText(getUserNames(orgName));
				break;
			case "ysr8_ElectricDirector":
				ysr8_ElectricDirector.setText(getUserNames(orgName));
				break;
			case "ysr8_Purcher":
				ysr8_Purcher.setText(getUserNames(orgName));
				break;
			case "ysr8_Machiner":
				ysr8_Machiner.setText(getUserNames(orgName));
				break;

			}

		}
	}

	private void addUIComponents() {

		dateUpdateTime = newDateButton();
		// dateUpdateTime.setPreferredSize(new Dimension(186, 23));
		btnUpdateData = new JButton("数据更新"); // kk 增加项目所有者 和 项目小组管理员
		btnUpdateData.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				clearData();
				dateUpdateTime.setDate(new Date());
				boolean isOK = getBasicInfo();
				if (!isOK) {
					return;
				}
				loadProjectMember();
				getScheduleTasks();
				getMilestoneTaskInfo();
				getKeyTaskInfo();
				//  添加
				getPropertyValueByPreference();
			}
		});

		ysr8_QuotationNo = new iTextField(30);
		ysr8_QuotationNo.setEnabled(false);
		ysr8_ProjectCode = new iTextField(30);
		ysr8_ProjectCode.setEnabled(false);
		ysr8_ProjectName = new iTextField(30);
		ysr8_ProjectName.setEnabled(false);
		ysr8_OrderManufacturer = new iTextField(30);
		ysr8_OrderManufacturer.setEnabled(false);
		ysr8_CustomerName = new iTextField(30);
		ysr8_CustomerName.setEnabled(false);

		ysr8_ProjectCategory = new iTextField(30);
		ysr8_ProjectCategory.setEnabled(false);
		ysr8_Factory = new iTextField(30);
		ysr8_Factory.setEnabled(false);
		ysr8_Product = new iTextField(30);
		ysr8_Product.setEnabled(false);
		ysr8_Use = new iTextField(30);
		ysr8_Use.setEnabled(false);
		ysr8_ProjectContent = new iTextArea(7, 60);
		ysr8_ProjectContent.setEnabled(false);

		ysr8_FixtrueCount = new iTextField(16);
		ysr8_AttachCount = new iTextField(16);
		ysr8_GuidCount = new iTextField(16);
		ysr8_JigCount = new iTextField(16);
		ysr8_PositionerCount = new iTextField(16);

		ysr8_RobotCount = new iTextField(16);
		ysr8_RobotModel = new iTextArea(3, 60);

		ysr8_ReceiveDate = new DateButton(new Date(), "yyyy-MM-dd", false, false, false);
		ysr8_SaleStartDate = new DateButton(new Date(), "yyyy-MM-dd", false, false, false);
		ysr8_StartDate = new DateButton(new Date(), "yyyy-MM-dd", false, false, false);
		ysr8_ContractDate = new DateButton(new Date(), "yyyy-MM-dd", false, false, false);
		ysr8_ActualFactoryDate = new DateButton(new Date(), "yyyy-MM-dd", false, false, false);
		ysr8_PlanDeliveryDate = new DateButton(new Date(), "yyyy-MM-dd", false, false, false);
		ysr8_ActualDeliveryDate = new DateButton(new Date(), "yyyy-MM-dd", false, false, false);
		ysr8_ProductionDate = new DateButton(new Date(), "yyyy-MM-dd", false, false, false);
		ysr8_PlanAcceptance = new DateButton(new Date(), "yyyy-MM-dd", false, false, false);
		ysr8_FinalAcceptance = new DateButton(new Date(), "yyyy-MM-dd", false, false, false);

		ysr8_ProjectManager = new iTextField(20);
		ysr8_ProjectManager.setEnabled(false);
		ysr8_Planner = new iTextField(20);
		ysr8_Planner.setEnabled(false);
		//  HUBING 20180615
		ysr8_DesignDirector = new iTextField(20);
		ysr8_DesignDirector.setEnabled(false);
		ysr8_ElectricDirector = new iTextField(20);
		ysr8_ElectricDirector.setEnabled(false);
		ysr8_Purcher = new iTextField(20);
		ysr8_Purcher.setEnabled(false);
		//  HUBING 20180615
		final GCSelectionUserCommand selectionUserCmd = new GCSelectionUserCommand(AIFUtility.getCurrentApplication().getDesktop(), session);
		/*ysr8_Purcher.setToolTipText("双击选择");
		ysr8_Purcher.addMouseListener(new MouseAdapter() {

			public void mouseClicked(MouseEvent mouseevent) {
				if (mouseevent.getClickCount() == 2) {
					ViewEditHelper editHelp = new ViewEditHelper(session);
					boolean checkedOut = editHelp.isCheckedOutByUser(ysr8ProjectForm);
					if (checkedOut && isModifiable()) {
						selectionUserCmd.setContextBean(ysr8_Purcher);
						try {
							selectionUserCmd.executeModal();
						} catch (Exception e) {
							//  Auto-generated catch block
							e.printStackTrace();
						}
					}
				}
			}
		});*/
		ysr8_Machiner = new iTextField(20);
		ysr8_Machiner.setEnabled(false);
		/*ysr8_Machiner.setToolTipText("双击选择");
		ysr8_Machiner.addMouseListener(new MouseAdapter() {

			public void mouseClicked(MouseEvent mouseevent) {
				if (mouseevent.getClickCount() == 2) {
					ViewEditHelper editHelp = new ViewEditHelper(session);
					boolean checkedOut = editHelp.isCheckedOutByUser(ysr8ProjectForm);
					if (checkedOut && isModifiable()) {
						selectionUserCmd.setContextBean(ysr8_Machiner);
						try {
							selectionUserCmd.executeModal();
						} catch (Exception e) {
							//  Auto-generated catch block
							e.printStackTrace();
						}
					}
				}
			}
		});*/
		ysr8_EngineerDebug = new iTextField(20);
		ysr8_EngineerDebug.setEnabled(false);
		/*ysr8_EngineerDebug.setToolTipText("双击选择");
		ysr8_EngineerDebug.addMouseListener(new MouseAdapter() {

			public void mouseClicked(MouseEvent mouseevent) {
				if (mouseevent.getClickCount() == 2) {
					ViewEditHelper editHelp = new ViewEditHelper(session);
					boolean checkedOut = editHelp.isCheckedOutByUser(ysr8ProjectForm);
					if (checkedOut && isModifiable()) {
						selectionUserCmd.setContextBean(ysr8_EngineerDebug);
						try {
							selectionUserCmd.executeModal();
						} catch (Exception e) {
							//  Auto-generated catch block
							e.printStackTrace();
						}
					}
				}
			}
		});*/
		ysr8_ElecDebug = new iTextField(20);
		ysr8_ElecDebug.setEnabled(false);
		/*ysr8_ElecDebug.setToolTipText("双击选择");
		ysr8_ElecDebug.addMouseListener(new MouseAdapter() {

			public void mouseClicked(MouseEvent mouseevent) {
				if (mouseevent.getClickCount() == 2) {
					ViewEditHelper editHelp = new ViewEditHelper(session);
					boolean checkedOut = editHelp.isCheckedOutByUser(ysr8ProjectForm);
					if (checkedOut && isModifiable()) {
						selectionUserCmd.setContextBean(ysr8_ElecDebug);
						try {
							selectionUserCmd.executeModal();
						} catch (Exception e) {
							//  Auto-generated catch block
							e.printStackTrace();
						}
					}
				}
			}
		});*/
		ysr8_Sales = new iTextField(20);
		ysr8_Sales.setEnabled(false);

		dateUpdateTime.setName("ysr8_UpdateT");
		ysr8_QuotationNo.setName("ysr8_QuotationNo");
		ysr8_ProjectCode.setName("ysr8_ProjectCode");
		ysr8_ProjectName.setName("ysr8_ProjectName");
		ysr8_OrderManufacturer.setName("ysr8_OrderManufacturer");
		ysr8_CustomerName.setName("ysr8_CustomerName");
		ysr8_ProjectCategory.setName("ysr8_ProjectCategory");
		ysr8_Factory.setName("ysr8_Factory");
		ysr8_Product.setName("ysr8_Product");
		ysr8_Use.setName("ysr8_Use");
		ysr8_ProjectContent.setName("ysr8_ProjectContent");
		ysr8_FixtrueCount.setName("ysr8_FixtrueCount");
		ysr8_AttachCount.setName("ysr8_AttachCount");
		ysr8_GuidCount.setName("ysr8_GuidCount");
		ysr8_JigCount.setName("ysr8_JigCount");
		ysr8_PositionerCount.setName("ysr8_PositionerCount");
		ysr8_RobotCount.setName("ysr8_RobotCount");
		ysr8_RobotModel.setName("ysr8_RobotModel");
		ysr8_ReceiveDate.setName("ysr8_ReceiveDate");
		ysr8_SaleStartDate.setName("ysr8_SaleStartDate");
		ysr8_StartDate.setName("ysr8_StartDate");
		ysr8_ContractDate.setName("ysr8_ContractDate");
		ysr8_ActualFactoryDate.setName("ysr8_ActualFactoryDate");
		ysr8_PlanDeliveryDate.setName("ysr8_PlanDeliveryDate");
		ysr8_ActualDeliveryDate.setName("ysr8_ActualDeliveryDate");
		ysr8_ProductionDate.setName("ysr8_ProductionDate");
		ysr8_PlanAcceptance.setName("ysr8_PlanAcceptance");
		ysr8_FinalAcceptance.setName("ysr8_FinalAcceptance");

		ysr8_ProjectManager.setName("ysr8_ProjectManager");
		ysr8_Planner.setName("ysr8_Planner");
		//  HUBING 20180615
		ysr8_DesignDirector.setName("ysr8_DesignDirector");
		ysr8_ElectricDirector.setName("ysr8_ElectricDirector");
		ysr8_Purcher.setName("ysr8_Purcher");
		ysr8_Machiner.setName("ysr8_Machiner");
		ysr8_EngineerDebug.setName("ysr8_EngineerDebug");
		ysr8_ElecDebug.setName("ysr8_ElecDebug");
		ysr8_Sales.setName("ysr8_Sales");

		allComponents.add(dateUpdateTime);
		allComponents.add(ysr8_QuotationNo);
		allComponents.add(ysr8_ProjectCode);
		allComponents.add(ysr8_ProjectName);
		allComponents.add(ysr8_OrderManufacturer);
		allComponents.add(ysr8_CustomerName);
		allComponents.add(ysr8_ProjectCategory);
		allComponents.add(ysr8_Factory);
		allComponents.add(ysr8_Product);
		allComponents.add(ysr8_Use);
		allComponents.add(ysr8_ProjectContent);
		allComponents.add(ysr8_FixtrueCount);
		allComponents.add(ysr8_AttachCount);
		allComponents.add(ysr8_GuidCount);
		allComponents.add(ysr8_JigCount);
		allComponents.add(ysr8_PositionerCount);
		allComponents.add(ysr8_RobotCount);
		allComponents.add(ysr8_RobotModel);
		allComponents.add(ysr8_ReceiveDate);
		allComponents.add(ysr8_SaleStartDate);
		allComponents.add(ysr8_StartDate);
		allComponents.add(ysr8_ContractDate);
		allComponents.add(ysr8_ActualFactoryDate);
		allComponents.add(ysr8_PlanDeliveryDate);
		allComponents.add(ysr8_ActualDeliveryDate);
		allComponents.add(ysr8_ProductionDate);
		allComponents.add(ysr8_PlanAcceptance);
		allComponents.add(ysr8_FinalAcceptance);
		allComponents.add(ysr8_ProjectManager);
		allComponents.add(ysr8_Planner);
		//  HUBING 20180615
		allComponents.add(ysr8_DesignDirector);
		allComponents.add(ysr8_ElectricDirector);
		allComponents.add(ysr8_Purcher);
		allComponents.add(ysr8_Machiner);
		allComponents.add(ysr8_EngineerDebug);
		allComponents.add(ysr8_ElecDebug);
		allComponents.add(ysr8_Sales);
	}

	/**
	 * getSchedule:: 根据表单获取时间表对象
	 */
	private void getSchedule() {
		try {
			AIFComponentContext[] context = ysr8ProjectForm.whereReferenced();
			for (int i = 0; i < context.length; i++) {
				if (context[i].getComponent() instanceof TCComponentSchedule) {
					schedule = (TCComponentSchedule) context[i].getComponent();
				}
			}
		} catch (TCException e) {
			e.printStackTrace();
		}
	}

	/**
	 * getScheduleMilestone:: 获取项目里程碑任务和关键任务
	 */
	private void getScheduleTasks() {
		if (schedule == null) {
			return;
		}
		try {
			TCUserService service = session.getUserService();
			Object[] parameters = new Object[] { schedule };

			long startime = System.currentTimeMillis();
			Object getScheduleTasks = service.call("Get_Schedule_Tasks", parameters);
			if (getScheduleTasks == null) {
				return;
			}
			Object taskproperties[] = (Object[]) getScheduleTasks;
			// Object taskproperties[] = (Object[])
			// service.call("Get_Schedule_Tasks", parameters);

			int iTotalMaxLen = taskproperties.length;

			// 里程碑个数
			int iMilestonMaxLen = Integer.parseInt(taskproperties[iTotalMaxLen - 1].toString());

			arrMilestoneTaskProp = new String[iMilestonMaxLen];

			for (int i = 0; i < iMilestonMaxLen; i++) {
				arrMilestoneTaskProp[i] = taskproperties[i].toString();
			}
			if (iMilestonMaxLen != (iTotalMaxLen - 1)) {
				arrKeyTaskProp = new String[iTotalMaxLen - 1 - iMilestonMaxLen];
				for (int i = iMilestonMaxLen; i < iTotalMaxLen - 1; i++) {
					arrKeyTaskProp[i - iMilestonMaxLen] = taskproperties[i].toString();
				}
			}
			long lendTime = System.currentTimeMillis();
			System.out.println("调用C获取时间任务属性，耗时：" + (lendTime - startime) + "毫秒");

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

	/**
	 * getMilestoneTaskInfo::获取项目里程碑信息
	 */
	private void getMilestoneTaskInfo() {
		try {
			Object[] objData;
			for (int i = 0; arrMilestoneTaskProp != null && i < arrMilestoneTaskProp.length; i++) {
				String strProperty = arrMilestoneTaskProp[i];
				String[] arrProperties = strProperty.split("&&");

				// 任务名称
				String strTaskName = arrProperties[0];
				// 计划完成时间
				Date dtFinish = null;
				String strFinishDate = arrProperties[2].equals("N/A") ? "" : arrProperties[2];
				if (!strFinishDate.equals("")) {
					dtFinish = format.parse(strFinishDate);
				}

				// 实际完成时间
				Date dtActualFinish = null;
				String strActualFinishDate = arrProperties[3].equals("N/A") ? "" : arrProperties[3];
				if (!strActualFinishDate.equals("")) {
					dtActualFinish = format.parse(strActualFinishDate);
				}

				// 描述
				String strDesc = arrProperties[1].equals("N/A") ? "" : arrProperties[1];

				// 完成情况
				String strPerfor = "";
				long day = 0;
				if (strActualFinishDate != "") {
					if (dtFinish.after(dtActualFinish)) {
						day = UtilApi.getDaysBetween(dtActualFinish, dtFinish);
						if (day == 0) {
							strPerfor = "准时完成";
						} else {
							strPerfor = "提前完成";
						}
					} else {
						day = UtilApi.getDaysBetween(dtFinish, dtActualFinish);
						if (day == 0) {
							strPerfor = "准时完成";
						} else {
							day = (-1) * day;
							strPerfor = "拖期完成";
						}
					}
				} else {
					Date nowDate = new Date();
					if (dtFinish.after(nowDate)) {
						day = UtilApi.getDaysBetween(nowDate, dtFinish);
						if (day == 0) {
							strPerfor = "已拖期";
						} else if (day <= 15) {
							strPerfor = "有延期风险";
						} else {
							strPerfor = "正常";
						}
					} else {
						day = UtilApi.getDaysBetween(dtFinish, nowDate);
						strPerfor = "已拖期";
						if (day != 0) {
							day = (-1) * day;
						}
					}
				}

				// 倒计时
				String strCountdown = "0天";
				if (day != 0) {
					strCountdown = day + "天";
				}
				objData = new Object[] { strTaskName, strPerfor, strCountdown, strFinishDate, strActualFinishDate, strDesc };
				modMilestone.addRow(objData);
			}
		} catch (ParseException e) {
			e.printStackTrace();
		}
	}

	/**
	 * getKeyTaskInfo::获取项目关键任务信息
	 */
	private void getKeyTaskInfo() {
		Object[] objData;
		for (int i = 0; arrKeyTaskProp != null && i < arrKeyTaskProp.length; i++) {
			String strProperty = arrKeyTaskProp[i];
			String[] arrProperties = strProperty.split("&&");

			// 项目任务
			String strTaskName = arrProperties[0];

			// 任务状态
			String strTaskStatus = arrProperties[2];

			// 描述
			String strDesc = arrProperties[1].equals("N/A") ? "" : arrProperties[1];

			// 计划开始时间
			String strStartDate = arrProperties[3].equals("N/A") ? "" : arrProperties[3];

			// 计划完成时间
			String strFinishDate = arrProperties[5].equals("N/A") ? "" : arrProperties[5];

			// 实际开始时间
			String strActualStartDate = arrProperties[4].equals("N/A") ? "" : arrProperties[4];

			// 实际完成时间
			String strActualFinishDate = arrProperties[6].equals("N/A") ? "" : arrProperties[6];

			// 完成情况
			String strPerfor = "";

			Date dtActualFinish = null;
			Date dtFinish = null;
			try {
				if (!strActualFinishDate.equals("")) {
					dtActualFinish = format.parse(strActualFinishDate);
				}
				if (!strFinishDate.equals("")) {
					dtFinish = format.parse(strFinishDate);
				}
			} catch (ParseException e) {
				e.printStackTrace();
			}

			long day = 0;
			Date nowDate = new Date();
			if (dtActualFinish != null) {// 完成
				if (dtFinish.after(dtActualFinish)) {
					day = UtilApi.getDaysBetween(dtActualFinish, dtFinish);
					if (day == 0) {
						strPerfor = "准时完成";
					} else {
						strPerfor = "提前完成";
					}
				} else {
					day = UtilApi.getDaysBetween(dtFinish, dtActualFinish);
					if (day == 0) {
						strPerfor = "准时完成";
					} else {
						day = (-1) * day;
						strPerfor = "拖期完成";
					}
				}
			} else {// 未完成
				if (dtFinish.after(nowDate)) {
					day = UtilApi.getDaysBetween(nowDate, dtFinish);
					if (day == 0) {
						strPerfor = "已拖期";
					} else if (day <= 15) {
						strPerfor = "有延期风险";
					} else {
						strPerfor = "正常";
					}
				} else {
					day = UtilApi.getDaysBetween(dtFinish, nowDate);
					strPerfor = "已拖期";
					if (day != 0) {
						day = (-1) * day;
					}
				}
			}

			// 倒计时
			String strCountDown = "0天";
			if (day != 0) {
				strCountDown = day + "天";
			}

			objData = new Object[] { strTaskName, strPerfor, strCountDown, strTaskStatus, strDesc, strStartDate, strFinishDate, strActualStartDate, strActualFinishDate };
			modKeyTasks.addRow(objData);
		}
	}

	/**
	 * checkPrivilege:: 检查当前用户是否是项目管理员，如果不是则不能添加、移除项目成员
	 * 
	 * @return boolean 返回是否有权限
	 */
	private boolean checkPrivilege() {
		if (!vtProjectAdmin.contains(session.getUser())) {
			MessageBox.post("您不是项目管理员，没有权限管理项目成员！", "警告", MessageBox.WARNING);
			return false;
		}
		return true;
	}

	/**
	 * loadProjectMember:: 加载项目人员信息
	 */
	private void loadProjectMember() {
		try {
			if (schedule == null) {
				return;
			}

			hmUserRole = new HashMap<TCComponentUser, String>();

			vtProjectAdmin = new Vector<TCComponentUser>();
			vtProjectMembers = new Vector<TCComponentGroupMember>();
			vtPrivilegedUsers = new Vector<TCComponentUser>();
			List<Object> oldvtUser = null;

			TCComponent[] comps = schedule.getReferenceListProperty("project_list");
			if (comps != null && comps.length > 0) {
				projectComp = (TCComponentProject) comps[0];
			}
			if (projectComp == null) {
				return;
			}
			oldvtUser = projectComp.getTeam();
			//   (TCComponentUser[])projectComp.getTeam().get(1)
			// System.out.println("oldvtUser = " + oldvtUser);

			TCComponent[] teamMembers = (TCComponent[]) oldvtUser.get(0);
			TCComponentUser[] teamAdmin = (TCComponentUser[]) oldvtUser.get(1);
			TCComponentUser[] privilegedUsers = (TCComponentUser[]) oldvtUser.get(2);

			for (int ix = 0; ix < teamAdmin.length; ix++)
				vtProjectAdmin.add(teamAdmin[ix]);

			for (int ix = 0; ix < privilegedUsers.length; ix++)
				vtPrivilegedUsers.add(privilegedUsers[ix]);

			for (int j = 0; j < teamMembers.length; j++) {
				TCComponent compUser = teamMembers[j];
				// System.out.println("j = " + j + ":: compUser = " + compUser);
				TCComponentUser user = null;
				if (compUser instanceof TCComponentGroupMember) {
					TCComponentGroupMember tmpGroupMember = (TCComponentGroupMember) compUser;
					try {
						user = tmpGroupMember.getUser();
					} catch (TCException e) {
						e.printStackTrace();
					}
					if (vtProjectMembers.contains(tmpGroupMember)) {
						continue;
					}
					vtProjectMembers.add(tmpGroupMember);
					hmUserRole.put(user, compUser.toString());
				} else if (compUser instanceof TCComponentGroup) {
					TCComponentGroup group = (TCComponentGroup) compUser;
					getGroup(group, false);
				}
				// else if (compUser instanceof TCComponentUser) {
				// user = (TCComponentUser) compUser;
				// if (vtProjectMembers.contains(user)) {
				// continue;
				// }
				// vtProjectMembers.add(user);
				// hmUserRole.put(user, compUser.toString());
				// }
			}

			Object[] objData;
			for (int i = 0; vtProjectAdmin != null && i < vtProjectAdmin.size(); i++) {
				TCComponentUser user = vtProjectAdmin.get(i);
				// System.out.println("user = " + user);
				String strRoleName = "项目经理";
				String strGroupName = hmUserRole.get(user);
				if (strGroupName == null) {
					continue;
				}
				System.out.println("i = " + i + ":: strGroupName = " + strGroupName);
				strGroupName = strGroupName.substring(0, strGroupName.lastIndexOf("/"));
				strGroupName = strGroupName.replace(".", "/");

				String strUserName = user.getProperty("user_name");
				String strPhone = user.getReferenceProperty("person").getProperty("PA10");
				objData = new Object[] { strRoleName, strGroupName, strUserName, strPhone };
				modMembers.addRow(objData);
			}

			for (int i = 0; vtProjectMembers != null && i < vtProjectMembers.size(); i++) {
				TCComponentUser user = vtProjectMembers.get(i).getUser();
				if (vtProjectAdmin.contains(user)) {
					continue;
				}
				String strRoleName = "项目成员";
				String strGroupName = "";
				strGroupName = hmUserRole.get(user);
				strGroupName = strGroupName.substring(0, strGroupName.lastIndexOf("/"));
				strGroupName = strGroupName.replace(".", "/");

				String strUserName = user.getProperty("user_name");
				String strPhone = user.getReferenceProperty("person").getProperty("PA10");

				objData = new Object[] { strRoleName, strGroupName, strUserName, strPhone };
				modMembers.addRow(objData);
			}
		} catch (TCException e) {
			e.printStackTrace();
		}
	}

	/**
	 * getGroup::根据组得到User对象
	 * 
	 * @param TCComponentGroup
	 *            group
	 */
	private void getGroup(TCComponentGroup group, boolean isAdmin) {
		try {
			TCComponent[] comprolegroup = group.getRolesAndGroups();
			for (int i = 0; i < comprolegroup.length; i++) {
				TCComponent tccomponent = comprolegroup[i];
				if (tccomponent instanceof TCComponentRole) {
					getRole((TCComponentRole) tccomponent, group, isAdmin);
					continue;
				}
				if (tccomponent instanceof TCComponentGroup) {
					getGroup((TCComponentGroup) tccomponent, isAdmin);
				}
			}
		} catch (TCException e) {
			e.printStackTrace();
		}
	}

	/**
	 * getRole::根据role得到User
	 * 
	 * @param TCComponentRole
	 * @param TCComponentGroup
	 */
	private void getRole(TCComponentRole tccomponentrole, TCComponentGroup tccomponentgroup, boolean isAdmin) {
		try {
			TCComponentGroupMember atccomponentgroupmember[] = tccomponentrole.getGroupMembers(tccomponentgroup);
			for (int i = 0; i < atccomponentgroupmember.length; i++) {
				TCComponentUser user = atccomponentgroupmember[i].getUser();

				if (!isAdmin) {
					if (vtProjectMembers.contains(atccomponentgroupmember[i])) {
						continue;
					}
					vtProjectMembers.add(atccomponentgroupmember[i]);
				}
				hmUserRole.put(user, atccomponentgroupmember[i].toString());
			}
		} catch (TCException e) {
			e.printStackTrace();
		}
	}

	/**
	 * AddMember:: 添加人员
	 */
	private void AddMember() {
		OrgTreePanel org = new OrgTreePanel(session);
		final OrganizationTree orgTree = org.getOrgTree();
		orgTree.addMouseListener(new MouseAdapter() {

			public void mouseClicked(MouseEvent mouseevent) {
				if (mouseevent.getClickCount() == 2) {
					if (orgTree.getSelectedNode() != null && orgTree.getSelectedNode().isLeaf()) {

						String strUserInfo = orgTree.getSelectedNode().getUserObject().toString();
						System.out.println("strUserInfo = " + strUserInfo);
						String strGroupName = "";
						String strRoleName = "";
						String strUserName = "";
						if (strUserInfo.contains("/")) {
							strGroupName = strUserInfo.substring(0, strUserInfo.lastIndexOf("/"));
							strGroupName = strGroupName.replace(".", "/");
							strUserName = strUserInfo.substring(strUserInfo.lastIndexOf("/") + 1);
						} else {
							Object[] obj = orgTree.getSelectedNode().getUserObjectPath();
							int objLen = obj.length - 2;
							for (int i = 1; i < objLen; i++) {
								if (strGroupName.length() == 0) {
									strGroupName = obj[i].toString();
								} else {
									strGroupName = strGroupName + "/" + obj[i];
								}
							}
							strRoleName = obj[obj.length - 2].toString();
							strUserName = obj[obj.length - 1].toString();
							strUserName = strUserName.substring(0, strUserName.indexOf("(")).trim();
						}

						String strPhone = "";
						try {
							String[] attr = new String[1];
							String[] values = new String[1];
							attr[0] = "PersonName";
							values[0] = strUserName;
							TCComponent[] comp = UtilApi.searchComponentCollection(session, "__Cust_findUser", attr, values);
							TCComponentUser userComp = null;
							if (comp != null && comp.length > 0) {
								userComp = (TCComponentUser) comp[0];
								strPhone = userComp.getReferenceProperty("person").getProperty("PA10");
								if (!vtProjectMembers.contains(userComp)) {
									Object[] objData = new Object[] { "项目成员", strGroupName + "/" + strRoleName, strUserName, strPhone };
									modMembers.addRow(objData);
									comp = UtilApi.searchComponentCollection(session, "__Cust_GroupMember", new String[] { "user_name", "Group", "Role" },
											new String[] { strUserName, strGroupName, strRoleName });
									if (comp != null && comp.length > 0) {
										vtProjectMembers.add((TCComponentGroupMember) comp[0]);
									}
								}
							}
						} catch (Exception e) {
							e.printStackTrace();
						}
						dlg.setVisible(false);
						dlg = null;
					}
				}
			}
		});

		Point point = tblProjectMembers.getLocationOnScreen();
		dlg = new JDialog();
		dlg.setTitle("选择人员");
		dlg.add(org);
		dlg.setLocation(point.x + 50, point.y - 50);
		dlg.setPreferredSize(new Dimension(300, 400));
		dlg.pack();
		dlg.setVisible(true);
	}

	/**
	 * removeMember:: 移除人员
	 */
	private void removeMember() {
		try {
			int[] rows = tblProjectMembers.getSelectedRows();
			if (rows == null || rows.length == 0) {
				MessageBox.post("请选择要移除的行！", "提示", MessageBox.WARNING);
				return;
			}

			for (int i = 0; i < rows.length; i++) {
				String strRoleName = tblProjectMembers.getValueAt(rows[i], 0).toString();
				String strUserName = tblProjectMembers.getValueAt(rows[i], 2).toString();
				if (strRoleName.equals("项目经理")) {
					vtProjectAdmin.remove(rows[i]);
				} else if (strRoleName.equals("项目成员")) {
					for (int j = vtProjectMembers.size() - 1; j >= 0; j--) {
						if (vtProjectMembers.get(j).getProperty("user_name").equals(strUserName)) {
							vtProjectMembers.remove(j);
						}
					}
				}
				modMembers.removeRow(rows[i]);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * updateProjectMember::更新项目用户
	 */
	private void updateProjectMember() {
		if (vtProjectMembers == null || vtProjectMembers.size() == 0) {
			return;
		}
		TCComponent[] comp = new TCComponent[vtProjectMembers.size()];
		vtProjectMembers.toArray(comp);
		// TCComponentUser[] privilegedUsers = new TCComponentUser[comp.length];

		// for (int j = 0; j < comp.length; j++) {
		// if (comp[j] instanceof TCComponentGroupMember) {
		// TCComponentGroupMember tmpGroupMember = (TCComponentGroupMember)
		// comp[j];
		// try {
		// privilegedUsers[j] = tmpGroupMember.getUser();
		// } catch (TCException e) {
		// privilegedUsers[j] = null;
		// e.printStackTrace();
		// }
		// } else {
		// privilegedUsers[j] = (TCComponentUser) comp[j];
		// }
		// }
		try {
			projectComp.modifyTeam(comp, vtProjectAdmin.toArray(new TCComponentUser[vtProjectAdmin.size()]), vtPrivilegedUsers.toArray(new TCComponentUser[vtPrivilegedUsers.size()]));
		} catch (TCException e) {
			e.printStackTrace();
		}
	}

	@SuppressWarnings("deprecation")
	private DateButton newDateButton() {
		DateButton db = new PropertyDateButton() {

			private static final long serialVersionUID = 1L;

			@Override
			public void setEnabled(boolean f) {
				super.setEnabled(false);
			}
		};
		return db;
	}

	/**
	 * clearData::清除表格中的数据
	 */
	private void clearData() {
		for (int row = tblProjectKeyTasks.getRowCount() - 1; row >= 0; row--) {
			modKeyTasks.removeRow(row);
		}
		for (int row = tblProjectMembers.getRowCount() - 1; row >= 0; row--) {
			modMembers.removeRow(row);
		}
		for (int row = tblProjectMilestone.getRowCount() - 1; row >= 0; row--) {
			modMilestone.removeRow(row);
		}
		arrMilestoneTaskProp = null;
		arrKeyTaskProp = null;
	}

	/**
	 * getBasicInfo::从项目启动通知版本表单获取基本信息
	 * 
	 * @return boolean
	 **/
	@SuppressWarnings("deprecation")
	private boolean getBasicInfo() {
		System.out.println("--从项目启动通知版本表单获取基本信息--Start");
		try {
			if (schedule == null) {
				MessageBox.post("根据该表单未找到时间表对象，请检查！", "警告", MessageBox.WARNING);
				return false;
			}
			// String strScheduleName = schedule.getProperty("object_name");
			// if (strScheduleName.contains("【") &&
			// strScheduleName.contains("】")) {
			// strProjectNum =
			// strScheduleName.substring(strScheduleName.indexOf("【") + 1,
			// strScheduleName.indexOf("】"));
			// }
			//
			// String[] attr = new String[1];
			// String[] values = new String[1];
			// TCTextService textService = session.getTextService();
			// attr[0] = textService.getTextValue("ProjectID");
			// values[0] = strProjectNum;
			//
			// TCComponent[] components =
			// UtilApi.searchComponentCollection(session, "Projects...", attr,
			// values);
			// if (components == null || components.length == 0) {
			// MessageBox.post("尚未创建当前项目号的项目！", "提示", MessageBox.WARNING);
			// return false;
			// }
			//
			// // 获取时间表里指派的项目
			// TCComponent[] comps =
			// schedule.getReferenceListProperty("project_list");
			// if (comps != null && comps.length > 0) {
			// for (int i = 0; i < comps.length; i++) {
			// if (comps[i] instanceof TCComponentProject
			// && comps[i].getProperty("project_id").equals(strProjectNum)) {
			// projectComp = (TCComponentProject) comps[i];
			// break;
			// }
			// }
			// }
			if (projectComp == null) {
				MessageBox.post("该项目尚未指派到该时间表中，无法获取相关信息！", "提示", MessageBox.WARNING);
				return false;
			}

			// 获取项目编号
			String strProjectNum = projectComp.getProperty("project_id");
			// 设置属性值
			String strDocId = new StringBuffer(strProjectNum).append("_XMQD").toString();
			TCComponentItemType itemType = (TCComponentItemType) session.getTypeComponent("Item");
			TCComponentItem docItem = itemType.find(strDocId);
			TCComponentForm docForm = null;
			if (docItem != null) {
				AIFComponentContext[] context = docItem.getLatestItemRevision().getRelated("IMAN_master_form_rev");
				if (context != null && context.length > 0) {
					for (int index = 0; index < context.length; index++) {
						if (context[index].getComponent() instanceof TCComponentForm) {
							docForm = (TCComponentForm) context[index].getComponent();
							break;
						}
					}
				}
			}

			if (docForm == null) {
				MessageBox.post("未获取项目启动通知，无法获取相关信息！", "提示", MessageBox.WARNING);
				return false;
			} else {
				ysr8_QuotationNo.setText(docForm.getProperty("ysr8_QuotationNo"));
				ysr8_ProjectCode.setText(docForm.getProperty("ysr8_ProjectCode"));
				ysr8_ProjectName.setText(docForm.getProperty("ysr8_ProjectName"));
				ysr8_OrderManufacturer.setText(docForm.getProperty("ysr8_OrderManufacturer"));
				ysr8_CustomerName.setText(docForm.getProperty("ysr8_CustomerName"));
				ysr8_ProjectCategory.setText(docForm.getProperty("ysr8_ProjectCategory"));
				ysr8_Factory.setText(docForm.getProperty("ysr8_Factory"));
				ysr8_Product.setText(docForm.getProperty("ysr8_Product"));
				ysr8_Use.setText(docForm.getProperty("ysr8_Use"));
				ysr8_ProjectContent.setText(docForm.getProperty("ysr8_ProjectContent"));

				ysr8_Sales.setText(docForm.getProperty("ysr8_Sales"));
				ysr8_ProjectManager.setText(docForm.getProperty("ysr8_ProjectManager"));
				ysr8_Planner.setText(docForm.getProperty("ysr8_Planner"));
				//  HUBING 20180615
				ysr8_DesignDirector.setText(docForm.getProperty("ysr8_DesignDirector"));
				ysr8_ElectricDirector.setText(docForm.getProperty("ysr8_ElectricDirector"));

				ysr8_ReceiveDate.setDate(docForm.getDateProperty("ysr8_ReceiveDate"));
				ysr8_StartDate.setDate(docForm.getDateProperty("ysr8_StartDate"));
				ysr8_ProductionDate.setDate(docForm.getDateProperty("ysr8_ProductionDate"));
				ysr8_PlanAcceptance.setDate(docForm.getDateProperty("ysr8_FinalAcceptance"));
			}
		} catch (TCException e) {
			//  Auto-generated constructor stub
			e.printStackTrace();
		}
		System.out.println("--从项目启动通知版本表单获取基本信息--End");
		return true;
	}
}
