package com.pinglian.ji.rcu.panel;

import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.awt.TextArea;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.swing.ButtonGroup;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.ScrollPaneConstants;
import javax.swing.filechooser.FileFilter;

import com.pinglian.ji.rcu.RcuSet;
import com.pinglian.ji.rcu.panel.ProgramExecConfigPanel.AirConfig;
import com.pinglian.rcu.activity.db.AirInfraredStudy;
import com.pinglian.rcu.activity.db.SCUPg;
import com.pinglian.rcu.bean.Packet;
import com.pinglian.rcu.communication.Communication;
import com.pinglian.rcu.communication.ScuUtils;
import com.pinglian.rcu.connect.SocketOpt;
import com.pinglian.rcu.constans.Constans;
import com.pinglian.rcu.constans.PreferenceConstants;
import com.pinglian.rcu.util.PreferenceUtils;

import javax.swing.JList;

/**
 * 红外设置界面
 * 
 * @author jixy
 * 
 */
public class RedSetPanel extends JPanel implements ActionListener {
	private JTextField et_send_time, et_time_out, et_nowchoice, et_template;
	private JButton btn_restudy, btn_time_query, btn_time_write, btn_control,
			btn_study, btn_cut, btn_add;
	ButtonGroup group_switch;
	ButtonGroup group_mode;
	ButtonGroup group_speed;
	JRadioButton switch_open, switch_close, mode_auto, mode_cool, mode_hot,
			mode_dehu, mode_vent, speed_auto, speed_low, speed_middle,
			speed_high;
	JLabel red_state;
	TextArea air_info, file_air_info;
	// 红外列表
	JList<AirInfraredStudy> redlist;
	DefaultListModel<AirInfraredStudy> airModel = new DefaultListModel<>();
	RcuSet activity;
	String fileName;
	String fileDir = "d:\\pl_ouput\\";
	// 正在学习的红外学习数据
	List<AirInfraredStudy> study_airRedData = new ArrayList<AirInfraredStudy>();
	// 文件中的红外学习数据
	List<AirInfraredStudy> file_airRedData = new ArrayList<AirInfraredStudy>();
	public static boolean saveFile = false;

	public static int studyIndex = 1;
	private JButton btn_export_redfile;
	private JPanel panel_2;
	private JLabel label_5;
	private JLabel label_14;
	private JTextField tv_file_path;
	private JButton btn_explorer;
	private static long sendTime = 5;
	private JLabel label_12;

	public boolean handleMessage(int what, Object obj) {
		switch (what) {
		case 0:
			break;
		case 1:
			SCUPg pack = (SCUPg) obj;
			et_send_time.setText((Communication.byteArray2Long(
					new byte[] { pack.datas[0] }, 0)) + "");
			et_time_out.setText((Communication.byteArray2Long(
					new byte[] { pack.datas[1] }, 0)) + "");
			// 设置按钮置灰延时时间

			sendTime = (Communication.byteArray2Long(
					new byte[] { pack.datas[1] }, 0));
		}
		return false;
	}

	/**
	 * Create the panel.
	 */
	public RedSetPanel(RcuSet rcuSet) {
		this.activity = rcuSet;
		setLayout(null);
		JPanel panel = new JPanel();
		panel.setBounds(10, 10, 579, 104);
		// panel.setBorder (BorderFactory.createTitledBorder ("红外发射、超时配置"));
		add(panel);
		panel.setLayout(null);

		JLabel label_1 = new JLabel("红外发射、超时配置");
		label_1.setFont(new Font("宋体", Font.BOLD, 18));
		label_1.setBounds(10, 10, 214, 21);
		panel.add(label_1);

		et_send_time = new JTextField();
		et_send_time.setColumns(10);
		et_send_time.setBounds(74, 39, 77, 21);
		panel.add(et_send_time);

		et_time_out = new JTextField();
		et_time_out.setColumns(10);
		et_time_out.setBounds(74, 67, 77, 21);
		panel.add(et_time_out);

		JLabel label_3 = new JLabel("设置数末尾为0或者为5暂设置范围80-200之间");
		label_3.setForeground(Color.RED);
		label_3.setBounds(161, 42, 268, 15);
		panel.add(label_3);

		btn_time_query = new JButton("刷新");
		btn_time_query.addActionListener(this);
		btn_time_query.setBounds(427, 38, 80, 23);
		panel.add(btn_time_query);

		JLabel lbls = new JLabel("(小于30s)整数");
		lbls.setForeground(Color.RED);
		lbls.setBounds(161, 71, 268, 15);
		panel.add(lbls);

		btn_time_write = new JButton("设置");
		btn_time_write.addActionListener(this);
		btn_time_write.setBounds(427, 67, 80, 23);
		panel.add(btn_time_write);

		JLabel label = new JLabel("发射时间:");
		label.setBounds(10, 41, 60, 15);
		panel.add(label);

		JLabel label_2 = new JLabel("超时时间:");
		label_2.setBounds(10, 70, 60, 15);
		panel.add(label_2);

		JPanel panel_1 = new JPanel();
		panel_1.setBounds(10, 109, 579, 336);
		add(panel_1);
		panel_1.setLayout(null);
		JLabel label_4 = new JLabel("红外控制、学习配置");
		label_4.setFont(new Font("宋体", Font.BOLD, 18));
		label_4.setBounds(10, 10, 171, 21);
		panel_1.add(label_4);

		red_state = new JLabel("红外控制/学习状态");
		red_state.setBounds(10, 41, 680, 15);
		panel_1.add(red_state);

		JLabel label_6 = new JLabel("当前行为:");
		label_6.setBounds(10, 68, 60, 15);
		panel_1.add(label_6);

		et_nowchoice = new JTextField();
		et_nowchoice.setText("学习");
		et_nowchoice.setEditable(false);
		et_nowchoice.setColumns(10);
		et_nowchoice.setBounds(74, 66, 77, 21);
		panel_1.add(et_nowchoice);

		btn_control = new JButton("控制");
		btn_control.addActionListener(this);
		btn_control.setBounds(290, 199, 80, 23);
		panel_1.add(btn_control);

		btn_study = new JButton("学习");
		btn_study.addActionListener(this);
		btn_study.setBounds(161, 66, 80, 23);
		panel_1.add(btn_study);

		btn_restudy = new JButton("重新学习");
		btn_restudy.addActionListener(this);
		btn_restudy.setBounds(269, 66, 80, 23);
		panel_1.add(btn_restudy);

		JLabel label_7 = new JLabel("状态:");
		label_7.setBounds(10, 93, 60, 15);
		panel_1.add(label_7);
		group_switch = new ButtonGroup();
		switch_open = new JRadioButton("开");
		switch_open.setSelected(true);
		switch_open.setActionCommand("开");
		switch_open.setBounds(70, 89, 60, 23);
		group_switch.add(switch_open);
		panel_1.add(switch_open);

		switch_close = new JRadioButton("关");
		switch_close.setActionCommand("关");
		switch_close.setBounds(136, 89, 60, 23);
		group_switch.add(switch_close);
		panel_1.add(switch_close);

		JLabel label_8 = new JLabel("温度:");
		label_8.setBounds(10, 122, 60, 15);
		panel_1.add(label_8);

		btn_cut = new JButton("-");
		btn_cut.addActionListener(this);
		btn_cut.setBounds(74, 118, 42, 23);
		panel_1.add(btn_cut);

		et_template = new JTextField("24");
		et_template.setColumns(10);
		et_template.setEnabled(false);
		et_template.setBounds(136, 118, 42, 21);
		panel_1.add(et_template);

		// JSpinner s=new JSpinner();
		//
		// s.setBounds(136, 118, 42, 21);
		// panel_1.add(s);

		JLabel label_9 = new JLabel("℃");
		label_9.setBounds(181, 122, 24, 15);
		panel_1.add(label_9);

		btn_add = new JButton("+");
		btn_add.addActionListener(this);
		btn_add.setBounds(218, 118, 42, 23);
		panel_1.add(btn_add);

		JLabel label_10 = new JLabel("模式:");
		label_10.setBounds(10, 149, 60, 15);
		panel_1.add(label_10);
		group_mode = new ButtonGroup();
		mode_auto = new JRadioButton("自动");
		mode_auto.setSelected(true);
		mode_auto.setBounds(70, 145, 60, 23);
		mode_auto.setActionCommand("自动");
		group_mode.add(mode_auto);
		panel_1.add(mode_auto);

		mode_cool = new JRadioButton("制冷");
		mode_cool.setBounds(136, 145, 60, 23);
		mode_cool.setActionCommand("制冷");
		group_mode.add(mode_cool);
		panel_1.add(mode_cool);

		mode_hot = new JRadioButton("制热");
		mode_hot.setBounds(194, 145, 60, 23);
		mode_hot.setActionCommand("制热");
		group_mode.add(mode_hot);
		panel_1.add(mode_hot);

		mode_dehu = new JRadioButton("通风");
		mode_dehu.setBounds(254, 145, 60, 23);
		mode_dehu.setActionCommand("通风");
		group_mode.add(mode_dehu);
		panel_1.add(mode_dehu);

		mode_vent = new JRadioButton("除湿");
		mode_vent.setBounds(314, 145, 60, 23);
		mode_vent.setActionCommand("除湿");
		group_mode.add(mode_vent);
		panel_1.add(mode_vent);

		JLabel label_11 = new JLabel("风速:");
		label_11.setBounds(10, 174, 60, 15);
		panel_1.add(label_11);
		group_speed = new ButtonGroup();
		speed_auto = new JRadioButton("自动");
		speed_auto.setSelected(true);
		speed_auto.setActionCommand("自动");
		speed_auto.setBounds(70, 170, 60, 23);
		group_speed.add(speed_auto);
		panel_1.add(speed_auto);

		speed_low = new JRadioButton("低速");
		speed_low.setBounds(136, 170, 60, 23);
		speed_low.setActionCommand("低速");
		panel_1.add(speed_low);
		group_speed.add(speed_low);
		speed_middle = new JRadioButton("中速");
		speed_middle.setBounds(194, 170, 60, 23);
		speed_middle.setActionCommand("中速");
		group_speed.add(speed_middle);
		panel_1.add(speed_middle);

		speed_high = new JRadioButton("高速");
		speed_high.setBounds(254, 170, 60, 23);
		speed_high.setActionCommand("高速");
		group_speed.add(speed_high);
		panel_1.add(speed_high);

		air_info = new TextArea();
		air_info.setVisible(false);
		air_info.setEditable(false);
		// air_info.setLineWrap(true);// 如果内容过长。自动换行
		air_info.setBounds(10, 195, 219, 108);
		panel_1.add(air_info);

		btn_export_redfile = new JButton("导出红外文件");
		btn_export_redfile.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				query();
			}
		});

		btn_export_redfile.setBounds(10, 309, 120, 23);
		panel_1.add(btn_export_redfile);
		redlist = new JList<AirInfraredStudy>();
		redlist.setModel(airModel);

		JScrollPane scrollPane = new JScrollPane((Component) redlist);
		scrollPane
				.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
		scrollPane
				.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
		scrollPane.setBounds(10, 197, 270, 102);
		panel_1.add(scrollPane);

		label_12 = new JLabel("\"控制\"选中行,不选择表示控制最后项");
		label_12.setForeground(Color.RED);
		label_12.setBounds(290, 232, 268, 15);
		panel_1.add(label_12);

		panel_2 = new JPanel();
		panel_2.setLayout(null);
		panel_2.setBounds(10, 443, 579, 220);
		add(panel_2);

		label_5 = new JLabel("红外写入");
		label_5.setFont(new Font("宋体", Font.BOLD, 18));
		label_5.setBounds(10, 10, 214, 21);
		panel_2.add(label_5);

		label_14 = new JLabel("红外文件:");
		label_14.setBounds(10, 44, 60, 15);
		panel_2.add(label_14);
		tv_file_path = new JTextField("请选择红外学习文件(*.cfg)");
		tv_file_path.setToolTipText("");
		tv_file_path.setForeground(Color.GRAY);
		tv_file_path.setEditable(false);
		tv_file_path.setBounds(79, 39, 206, 25);
		tv_file_path.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {

				JFileChooser fileChooser = new JFileChooser(RcuSet.basePath);
				fileChooser.setFileFilter(new FileFilter() {
					@Override
					public String getDescription() {
						return "RCU红外文件|(*.cfg)";
					}

					@Override
					public boolean accept(File f) {
						if (f.getName().toUpperCase().endsWith(".CFG")
								|| f.isDirectory()) {
							return true;
						}
						return false;
					}
				});
				fileChooser.setDialogTitle("选择RCU红外文件");
				fileChooser.setMultiSelectionEnabled(false);
				fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
				int result = fileChooser.showOpenDialog(activity);
				if (result == JFileChooser.APPROVE_OPTION) {
					RcuSet.basePath=fileChooser.getSelectedFile().getParent();
					tv_file_path.setText(fileChooser.getSelectedFile()
							.getAbsolutePath());
					readRedFile(fileChooser.getSelectedFile().getAbsolutePath());

				}
			}
		});
		panel_2.add(tv_file_path);

		btn_explorer = new JButton("选择文件");
		btn_explorer.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				JFileChooser fileChooser = new JFileChooser(RcuSet.basePath);
				fileChooser.setFileFilter(new FileFilter() {
					@Override
					public String getDescription() {
						return "RCU红外文件|(*.cfg)";
					}

					@Override
					public boolean accept(File f) {
						if (f.getName().toUpperCase().endsWith(".CFG")
								|| f.isDirectory()) {
							return true;
						}
						return false;
					}
				});
				fileChooser.setDialogTitle("选择RCU红外文件");
				fileChooser.setMultiSelectionEnabled(false);
				fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
				int result = fileChooser.showOpenDialog(activity);
				if (result == JFileChooser.APPROVE_OPTION) {
					RcuSet.basePath=fileChooser.getSelectedFile().getParent();
					tv_file_path.setText(fileChooser.getSelectedFile()
							.getAbsolutePath());
					readRedFile(fileChooser.getSelectedFile().getAbsolutePath());

				}
			}
		});
		btn_explorer.setBounds(295, 40, 111, 23);
		panel_2.add(btn_explorer);

		file_air_info = new TextArea("");
		file_air_info.setFont(new Font("宋体", Font.PLAIN, 12));
		file_air_info.setBounds(10, 69, 503, 108);
		panel_2.add(file_air_info);

		JButton btnrcu = new JButton("写入RCU");
		btnrcu.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				writeIr();
			}
		});
		btnrcu.setBounds(416, 40, 111, 23);
		panel_2.add(btnrcu);

		initFilePath();
	}

	/**
	 * 初始化 红外文件读取
	 */
	private void initFilePath() {
		// 历史路径记录
		String filePath = PreferenceUtils.getPrefString(activity,
				PreferenceConstants.RED_FILE_PATH, "");
		// 如果有数据则加载历史数据
		if (!"".equals(filePath)) {
			tv_file_path.setText(filePath);
			readRedFile(filePath);
		}
	}

	/**
	 * 写入红外学习数据到Rcu
	 */
	protected void writeIr() {
		Packet packet = new Packet();
		int redByteSize = file_airRedData.size();
		if (redByteSize == 0) {
			JOptionPane.showMessageDialog(activity, "还没有数据红外,请先读取一个红外文件~");
			return;
		}
		int index = 0;
		byte[] saveRedInfo = new byte[redByteSize * 256];
		for (int i = 0; i < redByteSize; i++) {
			System.arraycopy(file_airRedData.get(i).getRedData(), 0,
					saveRedInfo, index, 256);
			index += 256;
		}
		List<SCUPg> list = ScuUtils.getArr(Constans.PackageType.TYPE_SYS_SET,
				Constans.SysSet.SET_IR, saveRedInfo);
		System.out.println("------------------------");
		changeState("开始写入~");
		System.out.println("开始写入~");
		for (int i = 0; i < list.size(); i++) {
			byte[] arr = list.get(i).toBytes();
			String msg = "";
			for (int j = 0; j < arr.length; j++) {
				msg = msg + Integer.toHexString(arr[j] & 0xff) + "-";
				System.out.print(Integer.toHexString(arr[j] & 0xff) + "-");
			}
			changeState("写入第" + (int) ((double) (i / list.size()) * 100) + "个~");
			System.out.println("写入第" + (int) ((double) (i / list.size()) * 100)
					+ "个~");
			activity.SetTaskStatus(1, SocketOpt.ACT_SEND,
					list.get(i).toBytes(), packet);
			try {
				Thread.sleep(200);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		changeState("写入完毕~");
		JOptionPane.showMessageDialog(activity, "写入完毕~");
		System.out.println("------------------------");
	}

	protected void readRedFile(String path) {
		try {
			File redFile = new File(path);
			if (redFile.exists()) {
				file_airRedData.clear();
				FileInputStream f = new FileInputStream(redFile);
				long totalSize = redFile.length() / 262;
				byte[] fileByte = new byte[(int) redFile.length()];
				int start = 0;
				f.read(fileByte);
				// int a = 66810; //最大的内容大小
				String airRedInfoDes = "";
				for (int i = 0; i < totalSize; i++) {
					byte[] airInfo = new byte[262];
					System.arraycopy(fileByte, start, airInfo, 0, 262);
					AirInfraredStudy ais = new AirInfraredStudy(airInfo);
					ais.setId(i + 1);
					start += 262;
					airRedInfoDes += ais.toString() + "\n";
					file_airRedData.add(ais);
					System.out.println(ais.toString());
				}
				file_air_info.setText(airRedInfoDes);
				// 保存历史路径记录
				PreferenceUtils.setPrefString(activity,
						PreferenceConstants.RED_FILE_PATH, path);
			} else {
				System.out.println("文件不存在");
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 发送查询红外编码 发送者为 {0x0,0x27} (0x27表示查询红外编码) 接受者 {0x0,0xa0} (0xa0
	 * 表示查询类型),在数据回发的时候 就可以判断接受者和发送者 筛选是此界面发送的请求
	 */
	private void query() {
		int redByteSize = study_airRedData.size();
		if (redByteSize == 0) {
			JOptionPane.showMessageDialog(activity, "还未学习红外,请先学习红外后再保存哦~");
			return;
		}
		// 清空接收框
		byte[] datas = new byte[] { (byte) redByteSize };
		SCUPg p = ScuUtils.getRedNumber(datas);

		p.srcAddr = new byte[] { 0x0, Constans.Query.RED_NUMBER };
		p.targetAddr = new byte[] { 0x0, Constans.PackageType.TYPE_QUERY };

		byte[] msg = p.toBytes();
		String sb = "";
		for (int i = 0; i < msg.length; i++) {
			sb += Integer.toHexString(msg[i] & 0xff) + "-";
		}
		System.out.println("getRedNumber in RedSetPanel:" + sb);
		Packet packet = new Packet();
		saveFile = true;
		activity.SetTaskStatus(1, SocketOpt.ACT_SEND, msg, packet);

	}

	/**
	 * 另存为
	 * 
	 * @return
	 */
	public String selectSavePath() {

		SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd_HHmmss");
		String name = dateformat.format(new Date());
		name = name + ".cfg";
		// 构造文件保存对话框
		JFileChooser chooser = new JFileChooser(RcuSet.basePath);
		chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
		chooser.setDialogType(JFileChooser.SAVE_DIALOG);
		chooser.setMultiSelectionEnabled(false);
		chooser.setAcceptAllFileFilterUsed(false);
		chooser.setDialogTitle("导出红外数据");

		// 取得文件名输入框冰设置指定格式
		// textField.setText(name);
		// 添加文件过滤器
		chooser.addChoosableFileFilter(new FileFilter() {

			public boolean accept(File f) {
				if (f.getName().endsWith("cfg") || f.isDirectory()) {
					return true;
				} else {
					return false;
				}
			}

			public String getDescription() {
				return "红外数据文件(*.cfg)";
			}
		});
		// 添加文件过滤器
		chooser.addChoosableFileFilter(new FileFilter() {

			public boolean accept(File f) {
				return true;
			}

			public String getDescription() {
				return "所有文件(*.*)";
			}
		});

		// 打开对话框
		int result = chooser.showSaveDialog(activity);// null

		// 文件确定
		if (result == JFileChooser.APPROVE_OPTION) {
			RcuSet.basePath=chooser.getSelectedFile().getParent();
			String outPath = chooser.getSelectedFile().getAbsolutePath();
			if (new File(outPath).exists()) {
				// if(!po.showConfirmDialog("文件已经存在,是否要覆盖该文件?")){
				// return null;
				// }
				// 不是点击确定按钮,
				if (JOptionPane.showConfirmDialog(activity, "文件已经存在,是否要覆盖该文件?") != 0) {
					return null;
				}
			}
			System.out.println(outPath);
			return outPath;
		}
		return null;
	}

	/**
	 * 保存红外文件到文件中
	 */
	public void saveRedDataToFile(byte[] recvData) {
		// 是否保存文件
		if (!saveFile) {
			return;
		}

		String path = selectSavePath();
		if (null != path) {
			if (path.indexOf(".cfg") < 0) {
				path += ".cfg";

			}
		}

//		File fDir = new File(fileDir);
//		if (!fDir.exists()) {
//			try {
//				fDir.mkdir();
//			} catch (Exception e1) {
//				e1.printStackTrace();
//			}
//		}
		// 创建一个文件
		File redFile = new File(path);
		if (!redFile.exists()) {
			try {
				redFile.createNewFile();
			} catch (Exception e1) {
				e1.printStackTrace();
			}
		}
		FileOutputStream fos = null;
		try {
			fos = new FileOutputStream(redFile);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			return;
		}
		int start = 0;
		int dataCount = recvData.length / 265;
		for (int i = 0; i < dataCount && i < study_airRedData.size(); i++) {
			System.arraycopy(recvData, start, study_airRedData.get(i).redData,
					0, 256);
			start += 256;
			System.out.println("加载红外数据第" + (i + 1) + "个红外数据,共" + dataCount
					+ "个红外数据,集合共" + study_airRedData.size() + "个");
		}
		for (int i = 0; i < study_airRedData.size(); i++) {
			try {
				fos.write(study_airRedData.get(i).toByteArr());
				System.out.println("写入空调红外实体第" + (i + 1) + "个,共" + dataCount
						+ "个红外数据,集合共" + study_airRedData.size() + "个");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		try {
			fos.flush();
			fos.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		changeState("保存成功,文件路径:" + redFile.getAbsolutePath());
		JOptionPane.showMessageDialog(activity,
				"保存成功,文件路径:" + redFile.getAbsolutePath());
		saveFile = false;

	}

	private void redSend(Packet packet) {
		if (study_airRedData.size() == 0) {
			JOptionPane.showMessageDialog(activity, "还未学习过,请先学习后再控制!");
			return;
		}
		int index = redlist.getSelectedIndex();
		if (index < 0) {
			index = study_airRedData.size();
		}else{
			index=index+1;
		}
		byte[] datas = { 0x04, (byte) index };
		SCUPg p = ScuUtils.redSend(datas);
		byte[] msg = p.toBytes();
		String sb = "";
		for (int i = 0; i < msg.length; i++) {
			sb += Integer.toHexString(msg[i] & 0xff) + "-";
		}
		activity.SetTaskStatus(1, SocketOpt.ACT_SEND, msg, packet);
		et_nowchoice.setText("控制");
	}

	private void redStudy(Packet packet) {
		for (int i = 0; i < study_airRedData.size(); i++) {
			if (study_airRedData.get(i).equals(getAirInfoData())) {
				JOptionPane.showMessageDialog(activity, "本组合已经学习过了");
				return;
			}
		}

		red_state.setText("点击了按钮,等待学习~!" + studyIndex);
		byte[] datas = { 0x04, (byte) studyIndex };
		SCUPg p = ScuUtils.redStudy(datas);
		byte[] msg = p.toBytes();
		String sb = "";
		for (int i = 0; i < msg.length; i++) {
			sb += Integer.toHexString(msg[i] & 0xff) + "-";
		}
		System.out.println("redStudy: " + sb);
		activity.SetTaskStatus(1, SocketOpt.ACT_SEND, msg, packet);
		et_nowchoice.setText("学习");
		changeEnable(false);
		new Thread(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				try {
					Thread.sleep(sendTime * 1000);
					changeEnable(true);
					// 测试中,立即学习成功
//					 change();
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}).start();

	}

	public void changeEnable(boolean enable) {

		btn_restudy.setEnabled(enable);
		btn_control.setEnabled(enable);
		btn_study.setEnabled(enable);
		btn_cut.setEnabled(enable);
		btn_add.setEnabled(enable);
		et_template.setEnabled(enable);
		switch_open.setEnabled(enable);
		switch_close.setEnabled(enable);
		mode_auto.setEnabled(enable);
		mode_cool.setEnabled(enable);
		mode_hot.setEnabled(enable);
		mode_dehu.setEnabled(enable);
		mode_vent.setEnabled(enable);
		speed_auto.setEnabled(enable);
		speed_low.setEnabled(enable);
		speed_middle.setEnabled(enable);
		speed_high.setEnabled(enable);

	}

	public byte[] getAirInfoData() {
		byte[] airInfo = new byte[6];
		// 温度
		airInfo[0] = (byte) (Integer.parseInt(et_template.getText().trim()));
		// 模式
		if (mode_auto.isSelected()) {
			airInfo[1] = (byte) 0x04;
		} else if (mode_cool.isSelected()) {
			airInfo[1] = (byte) 0x00;
		} else if (mode_hot.isSelected()) {
			airInfo[1] = (byte) 0x01;
		} else if (mode_dehu.isSelected()) {
			airInfo[1] = (byte) 0x02;
		} else if (mode_vent.isSelected()) {
			airInfo[1] = (byte) 0x03;
		}
		// 阀门 ,预留
		airInfo[2] = (byte) 0x00;
		// 风速
		if (speed_auto.isSelected()) {
			airInfo[3] = (byte) 0x00;
		} else if (speed_low.isSelected()) {
			airInfo[3] = (byte) 0x01;
		} else if (speed_middle.isSelected()) {
			airInfo[3] = (byte) 0x02;
		} else if (speed_high.isSelected()) {
			airInfo[3] = (byte) 0x03;
		}
		// 开关
		if (switch_open.isSelected()) {
			airInfo[4] = (byte) 0x01;
		} else if (switch_close.isSelected()) {
			airInfo[4] = (byte) 0x00;
		}
		// 预留
		airInfo[5] = (byte) 0x00;
		return airInfo;
	}

	public void change() {
		AirInfraredStudy ais = new AirInfraredStudy(getAirInfoData());
		ais.setId(study_airRedData.size() + 1);
		study_airRedData.add(ais);
		studyIndex = ais.getId();
		System.out.println("airInfo:" + ais.toString() + " "
				+ study_airRedData.size());
		changeAirInfo();
		changeState("学习成功");
		changeEnable(true);
	}

	public void changeState(String msg) {
		if (null != red_state) {
			red_state.setText(msg);
		}
	}

	/**
	 * 改变空调状态信息
	 */
	private void changeAirInfo() {
		String airInfo = "";
		airModel.removeAllElements();
		for (int i = 0; i < study_airRedData.size(); i++) {
			airModel.addElement(study_airRedData.get(i));
			airInfo += study_airRedData.get(i).toString() + "\n";
		}
		redlist.setModel(airModel);
		air_info.setText(airInfo);
	}

	/**
	 * 重新学习
	 */
	private void reStudy() {
		if (null != study_airRedData && study_airRedData.size() > 0) {
			study_airRedData.remove(study_airRedData.size() - 1);
		}
		changeAirInfo();
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		Packet packet = new Packet();
		Object obj = e.getSource();
		if (obj == btn_control) {
			redSend(packet);
		} else if (obj == btn_study) {
			redStudy(packet);
		} else if (obj == btn_time_query) {
			try {
				SCUPg p = ScuUtils.getRedQuery();
				byte[] msg = p.toBytes();
				String sb = "";
				for (int i = 0; i < msg.length; i++) {
					sb += Integer.toHexString(msg[i] & 0xff) + "-";
				}
				activity.SetTaskStatus(1, SocketOpt.ACT_SEND, msg, packet);
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		} else if (obj == btn_time_write) {
			int sendTime = -1;
			try {
				sendTime = Integer.parseInt(et_send_time.getText().toString()
						.trim());
			} catch (NumberFormatException ex) {
				sendTime = -1;
			}
			if (sendTime < 80 || sendTime > 200 || sendTime % 5 != 0) {
				JOptionPane.showMessageDialog(activity, "发射时间填写有误!");
				return;
			}
			int timeOut = -1;
			try {
				timeOut = Integer.parseInt(et_time_out.getText().toString()
						.trim());
			} catch (NumberFormatException ex) {
				// TODO Auto-generated catch block
				timeOut = -1;
			}

			if (timeOut > 30 || timeOut < 0) {
				JOptionPane.showMessageDialog(activity, "设置数超出(0-30)的范围");
				return;
			}
			// 清空接收框
			byte[] datas = new byte[] { (byte) sendTime, (byte) timeOut };
			SCUPg p = ScuUtils.controlRedTime(datas);
			byte[] msg = p.toBytes();
			String sb = "";
			for (int i = 0; i < msg.length; i++) {
				sb += Integer.toHexString(msg[i] & 0xff) + "-";
			}
			activity.SetTaskStatus(1, SocketOpt.ACT_SEND, msg, packet);
		}

		else if (obj == btn_add) {
			int nowTemp = Integer.parseInt(et_template.getText().toString());
			if (nowTemp >= 30) {
				nowTemp = 30;
			} else {
				nowTemp++;
			}
			et_template.setText(nowTemp + "");
		} else if (obj == btn_cut) {
			int cutTemp = Integer.parseInt(et_template.getText().toString());
			if (cutTemp <= 16) {
				cutTemp = 16;
			} else {
				cutTemp--;
			}
			et_template.setText(cutTemp + "");
		} else if (obj == btn_restudy) {
			reStudy();
		}

	}
}
