package com.gx.obe.management.dialog;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;

import org.eclipse.swt.SWT;
import org.eclipse.swt.core.MessageDialog;
import org.eclipse.swt.core.widgets.EButton;
import org.eclipse.swt.core.widgets.EDialog;
import org.eclipse.swt.custom.CLabel;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;

import com.gx.obe.common.icons.IconsActivator;
import com.gx.obe.message.Messages;
import com.gx.obe.util.utils.LogUtils;
import com.gx.obe.util.utils.NumericChineseUtils;
import com.gx.obe.util.utils.ObjectUtils;
import com.gx.obe.util.utils.StringUtils;
import com.gx.obe.config.utils.PropertiesUtils;
import com.swtdesigner.ResourceManager;
import com.swtdesigner.SWTResourceManager;

import de.kupzog.ktable.KTable;
import de.kupzog.ktable.KTableCellMouseRightListener;
import de.kupzog.ktable.KTableCellSelectionListener;
import de.kupzog.ktable.SWTX;
import de.kupzog.ktable.editors.KTableCellEditorGCombo;
import de.kupzog.ktable.editors.KTableCellEditorText;
import de.kupzog.ktable.model.CommonKtableCModel;
import de.kupzog.ktable.renderers.CellAlignmentRender;
import de.kupzog.ktable.renderers.CellContentRender;
import de.kupzog.ktable.renderers.CellEditContentRender;
import de.kupzog.ktable.renderers.CellEditorRender;
import de.kupzog.ktable.renderers.CellRender;
import de.kupzog.ktable.renderers.FixedCellRenderer;
import de.kupzog.ktable.renderers.TextCellRenderer;

/**
 * @Description: 
 * @author guoyr
 */
public class EvaluationVideoConfigDialog extends EDialog {

	private KTable resultKTable;
	private CommonKtableCModel commKTableModel;
	private Composite composite;
	private List<String> videoList = new ArrayList<String>();
	private EButton btnAdd;
	private EButton btnDel;
	
	{
		LogUtils.logClass(EvaluationVideoConfigDialog.class);
	}
	
	/**
	 * Create the dialog.
	 * @param parentShell
	 */
	public EvaluationVideoConfigDialog(Shell parentShell) {
		super(parentShell);
	}

	/**
	 * Create contents of the dialog.
	 * @param parent
	 */
	@Override
	protected Control createDialogArea(Composite parent) {
		Composite container = (Composite) super.createDialogArea(parent);
		GridLayout gl_container = new GridLayout(1, false);
		gl_container.verticalSpacing = 0;
		gl_container.horizontalSpacing = 0;
		gl_container.marginHeight = 0;
		gl_container.marginWidth = 0;
		container.setLayout(gl_container);
		
//		Composite composite_2 = new Composite(container, SWT.NONE);
//		composite_2.setBackgroundImage(ResourceManager.getPluginImage(SWTCoreActivator.PLUGIN_ID, "icons/fill_yellow_bg.png"));
//		composite_2.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1));
//		composite_2.setLayout(new GridLayout(1, false));
//		
//		CLabel label = new CLabel(composite_2, SWT.WRAP);
//		label.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
//		label.setText("配置监控视频");
//		
//		Label label_2 = new Label(container, SWT.SEPARATOR | SWT.HORIZONTAL);
//		label_2.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
		
		Composite titleComposite = new Composite(container, SWT.NONE);
		GridLayout gl_titleComposite = new GridLayout(3, false);
		titleComposite.setLayout(gl_titleComposite);
		titleComposite.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false, 1, 1));
		titleComposite.setBackgroundImage(ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/bg_searchBar.png"));
		titleComposite.setBackgroundMode(SWT.INHERIT_FORCE);
		CLabel label_3 = new CLabel(titleComposite, SWT.NONE);
		label_3.setImage(ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/administrator.png"));
		label_3.setFont(SWTResourceManager.getFont("宋体", 10, SWT.BOLD));
		label_3.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, true, false, 1, 1));
		label_3.setText("视频配置管理");
		
		btnAdd = new EButton(titleComposite, SWT.NONE);
		btnAdd.setImage(ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/btn/blue/add.png"));
		btnAdd.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseUp(MouseEvent e) {
				addNewAction();
			}
		});
		GridData gd_btnAdd = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1);
		gd_btnAdd.widthHint = 60;
		btnAdd.setLayoutData(gd_btnAdd);
		btnAdd.setText(Messages.Button_add);
		
		btnDel = new EButton(titleComposite, SWT.NONE);
		btnDel.setImage(ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/btn/blue/delete.png"));
		btnDel.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseUp(MouseEvent e) {
				deleteAction();
			}
		});
		GridData gd_btnDel = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1);
		gd_btnDel.widthHint = 60;
		btnDel.setLayoutData(gd_btnDel);
		btnDel.setText(Messages.Button_delete);
		
		composite = new Composite(container, SWT.NONE);
		GridLayout gl_composite = new GridLayout(1, false);
		gl_composite.verticalSpacing = 0;
		gl_composite.horizontalSpacing = 0;
		gl_composite.marginHeight = 0;
		gl_composite.marginWidth = 1;
		composite.setLayout(gl_composite);
		composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
		
		Label label_1 = new Label(container, SWT.SEPARATOR | SWT.HORIZONTAL);
		label_1.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
		
		Composite composite_1 = new Composite(container, SWT.NONE);
		composite_1.setBackgroundMode(SWT.INHERIT_FORCE);
		composite_1.setBackgroundImage(ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/fill_bg.png"));
		GridLayout gl_composite_1 = new GridLayout(2, false);
		composite_1.setLayout(gl_composite_1);
		composite_1.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
		
		EButton save_btn = new EButton(composite_1, SWT.NONE);
		save_btn.setImage(ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/btn/blue/yes.png"));
		GridData gd_button = new GridData(SWT.RIGHT, SWT.CENTER, true, false, 1, 1);
		gd_button.widthHint = 90;
		save_btn.setLayoutData(gd_button);
		save_btn.setText(Messages.Button_ok);
		save_btn.addMouseListener(new MouseAdapter(){
			@Override
			public void mouseUp(MouseEvent e) {
				saveVideoConfigAction();
			}
		});
		
		EButton close_btn = new EButton(composite_1, SWT.NONE);
		close_btn.setImage(ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/btn/blue/close.png"));
		GridData gd_button_1 = new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1);
		gd_button_1.widthHint = 90;
		close_btn.setLayoutData(gd_button_1);
		close_btn.setText(Messages.Button_close);
		close_btn.addMouseListener(new MouseAdapter(){
			@Override
			public void mouseUp(MouseEvent e) {
				getShell().close();
			}
		});

		init();
		return container;
	}

	/**
	 * @Description: 初始化
	 * @author guoyr
	 */
	private void init(){
		String videoInfo = PropertiesUtils.getProperty("videoInfo", "");
		if(!"".equals(videoInfo)){
			String[] videos = videoInfo.split(",");
			videoList = new ArrayList<String>(Arrays.asList(videos));
		}
			
		drawKtable();
	}

	/**
	 * @Description: 汇制开标一览表
	 * @author guoyr
	 */
	private void drawKtable(){
		resultKTable = new KTable(composite, SWTX.AUTO_SCROLL | SWT.FULL_SELECTION | SWTX.EDIT_ON_KEY);
		resultKTable.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
		
		commKTableModel = new CommonKtableCModel(resultKTable, 1, 1, videoList.size(), 6);
//		commKTableModel.setContentRowHeight(30);
		final String[] title = new String[]{Messages.Num,Messages.Name, "IP", "端口", Messages.Account, Messages.Password, "通道"}; 
		// 设置单元格内容
		CellContentRender contentRender = new CellContentRender(){
			public Object receiveContent(int row, int col) {
				if(resultKTable.isFixedCell(col, row)){
					if(row == 0){
						return title[col];
					}else {
						return row+"";
					}
				}else {
					if(col == 0){
						return (row-commKTableModel.getFixedRowCount() +1)+"";
					}else {
						String[] info = videoList.get(row-commKTableModel.getFixedRowCount()).split(":");
						if(info.length == 6){
							if(col == commKTableModel.getColumnCount() -1){
								if(StringUtils.isNotEmpty(info[col - commKTableModel.getFixedColumnCount()])){
									return "通道"+(NumericChineseUtils.getChinese(Integer.parseInt(info[col - commKTableModel.getFixedColumnCount()])+ 1) );
								}
							}
							return ObjectUtils.getObjString(info[col - commKTableModel.getFixedColumnCount()]);
						}
					}
					return "";
				}
			}
		};
		commKTableModel.setCellContentRender(contentRender);
		
		// 编辑单元格内容
		CellEditContentRender editContentRender = new CellEditContentRender(){
			public void receiveContent(int row, int col, Object content) {
				if(null != content){
					String[] info = videoList.get(row-commKTableModel.getFixedRowCount()).split(":");
					if(info.length == 6){
						info[col - commKTableModel.getFixedColumnCount()] = content.toString();
					}
					StringBuilder infoSb = new StringBuilder();
					int index = 0;
					for(String value : info){
						if(index ++ > 0){
							infoSb.append(":");
						}
						infoSb.append(value);
					}
					videoList.set(row-commKTableModel.getFixedRowCount(), infoSb.toString());
				}
			}
		};
		commKTableModel.setCellEditContentRender(editContentRender);
		
		// 设置单元格编辑器
		final KTableCellEditorText textEdit = new KTableCellEditorText();
		textEdit.setTextLimit(20);
		textEdit.setSingleClickEdit(true);
		final KTableCellEditorGCombo combo = new KTableCellEditorGCombo();
		combo.setSingleClickEdit(true);
		for(int i = 0; i < 10; i++){
			combo.addItem("通道"+NumericChineseUtils.getChinese(i+1), i);
		}
		CellEditorRender cellEditorRender = new CellEditorRender(){
			public Object receiveCellEditor(int row, int col) {
				if(resultKTable.isFixedCell(col, row)){
					return null;
				}else if(col == commKTableModel.getColumnCount() -1){
					return combo;
				}else {
					return textEdit;
				}
			}
		};
		commKTableModel.setCellEditorRender(cellEditorRender);
		// 设置单元格渲染器
		CellRender cellRender = new CellRender(){
			public Object receiveCellRender(int row, int col) {
				if(commKTableModel.isFixedCell(col, row)){
					return new FixedCellRenderer();
				}else {
					return new TextCellRenderer();
				}
		}};
		commKTableModel.setCellRender(cellRender);
		// 编辑单元格对齐方式
		CellAlignmentRender cellAlignmentRender = new CellAlignmentRender(){
			public int receiveCellAlignment(int row, int col) {
				if(resultKTable.isFixedCell(col, row)){
					return SWTX.ALIGN_VERTICAL_CENTER | SWTX.ALIGN_HORIZONTAL_CENTER;
				}else {
					return SWTX.ALIGN_VERTICAL_CENTER | SWTX.ALIGN_HORIZONTAL_LEFT;
				}
			}
		};
		commKTableModel.setCellAlignmentRender(cellAlignmentRender);
		resultKTable.setModel(commKTableModel);
		
		resultKTable.addCellSelectionListener(new KTableCellSelectionListener(){
		    public void cellSelected(int col, int row, int statemask) {
//	    		String videoParams = videoList.get(row-commKTableModel.getFixedRowCount());
	    		btnDel.setEnabled(true);
			}
			public void fixedCellSelected(int col, int row, int statemask) {
				btnDel.setEnabled(false);
			}
		});
		resultKTable.addCellMouseRightListener(new KTableCellMouseRightListener(){

			public void cellMouseRightClick(int col, int row,
					Rectangle rectangle) {
				
			}

			public void mouseRightClick(Rectangle rectangle) {
				
			}
		});
	}
	
	/**
	 * @Description: 添加视频
	 * @author guoyr
	 */
	private void addNewAction(){

		if(btnAdd.getEnabled()){
			resultKTable.closeCellEditor();
			int addNewRow = resultKTable.getCurRow()- commKTableModel.getFixedRowCount() + 1;
			String videoParams = ":::::0";
			if(resultKTable.getCurRow() >= commKTableModel.getFixedRowCount()){
				videoList.add(addNewRow, videoParams);
			}else {
				videoList.add(videoList.size(), videoParams);
			}
			commKTableModel.addNewRow();
			resultKTable.setSelection(1, addNewRow+1, true);
			resultKTable.autoComputerColumnWidth();
//			resultKTable.refresh();
			btnDel.setEnabled(true);
		}
	
	}
	
	/**
	 * @Description: 删除视频
	 * @author guoyr
	 */
	private void deleteAction(){

		if(btnDel.getEnabled() && resultKTable.getCurRow() > 0 && resultKTable.getCurRow() >= commKTableModel.getFixedRowCount()){
			resultKTable.closeCellEditor();
			if(!MessageDialog.openConfirm(getShell(), "确认要删除该监控吗？")){
				return;
			}
			//删除Model中行数据
			videoList.remove(resultKTable.getCurRow()-commKTableModel.getFixedRowCount());
			
			if(videoList.size() == 0){//判断是否全部删除，若全部删除则删除按钮变为灰色，不可操作。
				btnDel.setEnabled(false);
			}
			commKTableModel.delRow();
			resultKTable.setSelection(1, resultKTable.getCurRow(), true);
		}
	}
	
	/**
	 * @Description: 保存视步配置
	 * @author guoyr
	 */
	private void saveVideoConfigAction(){
		Properties configProperties = PropertiesUtils.getProperties("config.properties");
		if(videoList.size() > 0){
			int index = 0;
			StringBuilder videoInfoSb = new StringBuilder();
			for(String videoInfo : videoList){
				if(index ++ > 0){
					videoInfoSb.append(",");
				}
				videoInfoSb.append(videoInfo);
			}
			configProperties.setProperty("videoInfo", videoInfoSb.toString());
			PropertiesUtils.setPropertyValue("videoInfo", videoInfoSb.toString());
		}else {
			PropertiesUtils.setPropertyValue("videoInfo", "");
			configProperties.setProperty("videoInfo", "");
		}
		PropertiesUtils.saveProperties(configProperties);
		getShell().close();
	}
	
	/**
	 * Return the initial size of the dialog.
	 */
	@Override
	protected Point getInitialSize() {
		return new Point(670, 414);
	}
}
