package cn.net.connor.std.processedit.ldy;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Vector;

import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;


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.TCComponentBOMLine;
import com.teamcenter.rac.kernel.TCComponentEnvelope;
import com.teamcenter.rac.kernel.TCComponentForm;
import com.teamcenter.rac.kernel.TCComponentItem;
import com.teamcenter.rac.kernel.TCComponentItemRevision;
import com.teamcenter.rac.kernel.TCComponentUser;
import com.teamcenter.rac.kernel.TCSession;
import com.teamcenter.rac.util.MessageBox;
import com.teamcenter.services.rac.core.DataManagementService;
import com.teamcenter.services.rac.core.EnvelopeService;
import com.teamcenter.services.rac.core._2008_06.DataManagement.CreateIn;
import com.teamcenter.services.rac.core._2008_06.DataManagement.CreateInput;
import com.teamcenter.services.rac.core._2008_06.DataManagement.CreateResponse;

import cn.net.connor.std.aifrcp.util.KUtil;

public class GXDivisionDialog extends AbstractAIFDialog {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private TCSession session;
	private JTable				table;
	private DefaultTableModel	model;
	private String[] tableHeader;
	private JButton divisionBtn;
	private JButton okBtn;
	private JButton cancelBtn;
	private int ld6_resperson = -1;
	private TCAccessControlService accessControlService;
	private ArrayList<String[]> colList;
	private ArrayList<TCComponent[]> compList;
	private HashMap<String, TCComponentUser> userMap;
	
	public GXDivisionDialog(TCSession session, TCComponentBOMLine[] target, String[] options) throws Exception{
		super(AIFUtility.getActiveDesktop());
		this.session = session;
		accessControlService = session.getTCAccessControlService();
		userMap = new HashMap<>();
		compList = new ArrayList<>();
		
		setTitle("工序分工");
		divisionBtn = new JButton("工序分工");
		okBtn = new JButton("确定");
		cancelBtn = new JButton("取消");
		addActionListener();
		
//		String[] tableHeader = new String[] { "序号", "名称", "规格" };
		int size = options.length;
		tableHeader = new String[size+1];
		tableHeader[0] = "序号";
		colList = new ArrayList<>();
		for(int i=0; i<size; i++) {
			String[] option = options[i].split("=");
			tableHeader[i+1] = option[0];
			if(option[1].equals("Rev.j6_resperson")) {//TODO object_desc
				ld6_resperson = i+1;
			}
			String[] prop = option[1].split("\\.");
			colList.add(prop);
		}
		if(ld6_resperson == -1) {
			throw new Exception("首选项未配置Rev.j6_resperson，无法进行分工");
		}
		model = new DefaultTableModel(tableHeader, 0);
		table = new JTable() {
			private static final long serialVersionUID = 1L;
			@Override
			public boolean isCellEditable(int row, int col) {
				return false;
			}
		};
		table.setFillsViewportHeight(true);
		table.setEnabled(true);
//		impTable.setAutoResizeMode(JTable.AUTO_RESIZE_NEXT_COLUMN);
		table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
		table.setModel(model);
		table.getColumnModel().getColumn(0).setPreferredWidth(50);
		for (int i = 1; i < table.getColumnCount(); i++) {
			table.getColumnModel().getColumn(i).setPreferredWidth(180);
		}
		table.getTableHeader().setReorderingAllowed(false);
		recycleBom(target);
		
		JScrollPane tablePanel = new JScrollPane();
		tablePanel.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
		tablePanel.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
		tablePanel.setViewportView(table);
		JPanel btnPanel = new JPanel(new FlowLayout());
		btnPanel.add(divisionBtn);
		btnPanel.add(okBtn);
		btnPanel.add(cancelBtn);
//		tablePanel.setBounds(20, 20, 330, 180);
//		okBtn.setBounds(70, 220, 100, 25);
//		cancelBtn.setBounds(180, 220, 100, 25);
		setLayout(new BorderLayout());
		add(BorderLayout.CENTER, tablePanel);
		add(BorderLayout.SOUTH, btnPanel);
//		add(new JLabel(""));
		
		setSize(new Dimension(1000, 600));
		Dimension screen = getToolkit().getScreenSize();
		setLocation((screen.width - getSize().width) / 2, (screen.height - getSize().height) / 2);
		this.setAlwaysOnTop(true);
		setVisible(true);
	}
	
	private void addActionListener() {
		final AbstractAIFDialog dialog = this;
		divisionBtn.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				try {
					int[] rows = table.getSelectedRows();
					if(rows==null || rows.length==0) {
						MessageBox.post(GXDivisionDialog.this, "请选择要分工的行", "ERROR", MessageBox.ERROR);
						return;
					}
					new SelectUserDialog(table, rows, ld6_resperson, userMap).showDialog();
				} catch (Exception e1) {
					e1.printStackTrace();
					MessageBox.post(dialog, "错误："+e1.getMessage(), "ERROR", MessageBox.ERROR);
					return;
				}
//				dialog.dispose();
			}
		});
		okBtn.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				try {
					KUtil.setByPassItk(session, true);
					for(int i=0; i<table.getRowCount(); i++) {
						String user = table.getValueAt(i, ld6_resperson).toString();
						if(user.isEmpty() || !userMap.containsKey(user))
							continue;
						for(TCComponent comp : compList.get(i)) {
//							if(!accessControlService.checkAccessorsPrivilege(atccomponent, topFolder, "WRITE"))
							accessControlService.grantPrivilege(comp, userMap.get(user), new String[]{ "WRITE" });
						}
						compList.get(i)[1].setProperty("j6_resperson", user);//TODO  object_desc
						sendMail("工序分工", "您好，此任务已经分配给您请及时完成", userMap.get(user), compList.get(i));
					}
					KUtil.setByPassItk(session, false);
					MessageBox.post(dialog, "分工完成", "INFO", MessageBox.INFORMATION);
					dispose();
				} catch (Exception e1) {
					e1.printStackTrace();
					MessageBox.post(dialog, "错误："+e1.getMessage(), "ERROR", MessageBox.ERROR);
					KUtil.setByPassItk(session, false);
					return;
				}finally {
					KUtil.setByPassItk(session, false);
				}
//				dialog.dispose();
			}
		});
		
		cancelBtn.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				dispose();
			}
		});
	}
	
//	private void recycleBom(TCComponentBOMLine parent) throws Exception {
//		for(AIFComponentContext c : parent.getChildren()) {
//			TCComponentBOMLine line = (TCComponentBOMLine) c.getComponent();
////			String type = line.getItemRevision().getType();
////			if(!type.equals("LD6_MEOPRevision") && !type.equals("LD6_ProDevMEOPRevision")) {
////			if(!type.equals("LD6_MEProcessRevision") && !type.equals("LD6_OMEOPRevision")) {
//			/*
//			 * if(!type.equals("LD6_MEOPRevision")) { recycleBom(line); continue; }
//			 */
//			TCComponentItem item = line.getItem();
//			TCComponentItemRevision rev = line.getItemRevision();
//			TCComponentForm form = TCUtil.getItemRevisionMasterForm(rev);
//			Vector<String> v = new Vector<>();
//			v.add(table.getRowCount()+1+"");
//			for(String[] s : colList) {
//				if(s[0].equals("Item")) {
//					v.add(item.getProperty(s[1]));
//				}else if(s[0].equals("Rev")) {
//					v.add(rev.getProperty(s[1]));
//				}else if(s[0].equals("RevMaster")) {
//					v.add(form.getProperty(s[1]));
//				}else if(s[0].equals("BOMLine")) {
//					v.add(line.getProperty(s[1]));
//				}
//			}
//			model.addRow(v);
//			AIFComponentContext[] cs = rev.getChildren("bom_view_tags");
//			if(cs.length>0)
//				compList.add(new TCComponent[] { item, rev, form, (TCComponent) cs[0].getComponent() });
//			else
//				compList.add(new TCComponent[] { item, rev, form });
//			recycleBom(line);
//		}
//	}
	
	
	
	private void recycleBom(TCComponentBOMLine[] parent) throws Exception {
		for (int i = 0; i < parent.length; i++) {

			TCComponentBOMLine line = parent[i];
			TCComponentItem item = line.getItem();
			TCComponentItemRevision rev = line.getItemRevision();
			TCComponentForm form = TCUtil.getItemRevisionMasterForm(rev);
			Vector<String> v = new Vector<>();
			v.add(table.getRowCount()+1+"");
			for(String[] s : colList) {
				if(s[0].equals("Item")) {
					v.add(item.getProperty(s[1]));
				}else if(s[0].equals("Rev")) {
					v.add(rev.getProperty(s[1]));
				}else if(s[0].equals("RevMaster")) {
					v.add(form.getProperty(s[1]));
				}else if(s[0].equals("BOMLine")) {
					v.add(line.getProperty(s[1]));
				}
			}
			model.addRow(v);
			AIFComponentContext[] cs = rev.getChildren("bom_view_tags");
			if(cs.length>0)
				compList.add(new TCComponent[] { item, rev, form, (TCComponent) cs[0].getComponent() });
			else
				compList.add(new TCComponent[] { item, rev, form });
		}
	}
	
	
	
	private void sendMail(String name, String desc, TCComponentUser user, TCComponent[] comps) throws Exception {
		DataManagementService dataManagementService = DataManagementService.getService(session);
		CreateIn[] arrayOfCreateIn = new CreateIn[] { new CreateIn() };
		CreateInput createInput = new CreateInput();
		createInput.stringProps.put("object_name", name);
		createInput.stringProps.put("object_desc", desc);
		createInput.boName = "Envelope";
		createInput.tagArrayProps.put("listOfReceivers", new TCComponent[] { user });
		createInput.tagArrayProps.put("contents", comps);
		
//		if (paramArrayOfString1 != null && paramArrayOfString1.length > 0)
//			createInput.stringArrayProps.put("fnd0ListOfExtRecipients", paramArrayOfString1); 
//		if (paramArrayOfString2 != null && paramArrayOfString2.length > 0)
//			createInput.stringArrayProps.put("fnd0ListOfCcExtRecipients", paramArrayOfString2); 
		arrayOfCreateIn[0].data = createInput;

		CreateResponse createResponse = dataManagementService.createObjects(arrayOfCreateIn);
		
//		String uid2 = e.getUid();		
//		System.out.println("uid2===================="+uid2);
		TCComponentEnvelope[] arrayOfTCComponentEnvelope = new TCComponentEnvelope[] { (TCComponentEnvelope)createResponse.output[0].objects[0] };
		EnvelopeService envelopeService = EnvelopeService.getService(session);
		envelopeService.sendAndDeleteEnvelopes(arrayOfTCComponentEnvelope);
	}
}
