package com.util;

import java.io.InputStream;
import java.lang.reflect.Method;
import java.util.Iterator;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.chaoran.component.AntLine;
import com.chaoran.component.SelfHRule;
import com.chaoran.entiry.PhotographUi;
import com.chaoran.entiry.SelfButton;
import com.chaoran.entiry.SelfCheckBox;
import com.chaoran.entiry.SelfDateField;
import com.chaoran.entiry.SelfEditText;
import com.chaoran.entiry.SelfImage;
import com.chaoran.entiry.SelfTextBut;
import com.chaoran.entiry.UpdataInfo;
import com.chaoran.imp.InputInterface;
import com.chaoran.thread.ImageUrl;
import com.activity.chaoran.DjActivity;
import com.sys.SysData;

import android.text.InputType;
import android.util.TypedValue;
import android.view.Gravity;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class Dom4jUtil {
	public static void testParseXMLData(InputStream in, DjActivity aa)
			throws DocumentException {
		// 产生一个解析器对象
		SAXReader reader = new SAXReader();
		// 将xml文档转换为Document的对象
		Document document = reader.read(in);
		// 获取文档的根元素
		Element root = document.getRootElement();
		Iterator i_pe = root.elementIterator();
		MxTabHostContent layout;
		int i = 0;
		String title = null;
		while (i_pe.hasNext()) {
			Element e_pe = (Element) i_pe.next();
			Iterator i_pe1 = e_pe.elementIterator();
			if (!i_pe1.hasNext()) {
				continue;
			}
			layout = new MxTabHostContent(aa);
			layout.setFocusable(true);
			layout.setFocusableInTouchMode(true);
			if (e_pe.attributeValue("title") != null) {
				title = e_pe.attributeValue("title").trim();
			} else {
				title = "汇总";
			}
			if (title.equals("")) {
				title = "汇总";
			}
			aa.hzTab.addTab(aa.hzTab.newTabSpec("hzchild" + i)
					.setIndicator(title).setContent(layout));
			aa.hzTab.setCurrentTab(i);
			i++;
			while (i_pe1.hasNext()) {
				Element e_pe1 = (Element) i_pe1.next();
				String name = e_pe1.attributeValue("name");
				name = name.substring(name.indexOf("::") + 2, name.length());
				int w = (int) (Double.parseDouble(e_pe1
						.elementText("width_attribute")));
				int h = (int) (Double.parseDouble(e_pe1
						.elementText("height_attribute")));
				int x = (int) (Double.parseDouble(e_pe1
						.elementText("x_attribute")));
				int y = (int) (Double.parseDouble(e_pe1
						.elementText("y_attribute")));
				w = (int) (TypedValue.applyDimension(
						TypedValue.COMPLEX_UNIT_DIP, w, aa.getResources()
								.getDisplayMetrics()) * SysData.t_scale);
				h = (int) (TypedValue.applyDimension(
						TypedValue.COMPLEX_UNIT_DIP, h, aa.getResources()
						.getDisplayMetrics()) * SysData.t_scale);
				x = (int) (TypedValue.applyDimension(
						TypedValue.COMPLEX_UNIT_DIP, x, aa.getResources()
						.getDisplayMetrics()) * SysData.t_scale);
				y = (int) (TypedValue.applyDimension(
						TypedValue.COMPLEX_UNIT_DIP, y, aa.getResources()
						.getDisplayMetrics()) * SysData.t_scale);
				// int w = UnitConversionUtil.convertDIP2PX(Double
				// .parseDouble(e_pe1.elementText("width_attribute")));
				// int h = UnitConversionUtil.convertDIP2PX(Double
				// .parseDouble(e_pe1.elementText("height_attribute")));
				// int x = UnitConversionUtil.convertDIP2PX(Double
				// .parseDouble(e_pe1.elementText("x_attribute")));
				// int y = UnitConversionUtil.convertDIP2PX(Double
				// .parseDouble(e_pe1.elementText("y_attribute")));
				// System.out.println(h+"================"+name);
				RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
						w, h);
				layoutParams.topMargin = y;
				layoutParams.leftMargin = x;
				if (name.equals("SelfButton")) {
					if (isVisible(e_pe1)) {
						continue;
					}
					SelfButton but = new SelfButton(aa);
					if (SysData.t_scale < 1) {
						but.setPadding((int) (but.getPaddingLeft() * SysData.t_scale * 0.2f), (int) (but.getPaddingTop() * SysData.t_scale * 0.2f),
								(int) (but.getPaddingRight() * SysData.t_scale * 0.2f), (int) (but.getPaddingBottom() * SysData.t_scale * 0.2f));
					}
					// but.setFocusableInTouchMode(true);
					but.setText(e_pe1.elementText("label_attribute"));
					if (e_pe1.element("click_function") != null) {
						but.setOnClickListener(aa.clickEvent);
						but.clickFun = e_pe1.elementText("click_function")
								.toString();
					}
					if (e_pe1.element("enterKey_attribute") != null) {
						but.nextFocus = e_pe1.elementText("enterKey_attribute")
								.toString().toUpperCase();
					}
					if (e_pe1.element("fontSize_style") != null) {
						but.setTextSize(Float.parseFloat(e_pe1.elementText(
								"fontSize_style").toString()) * SysData.t_scale);
					}
					if (e_pe1.element("key_value") != null) {
						but.setTag(e_pe1.elementText("key_value").toString()
								.trim().toUpperCase());
					}
					// but.setLayoutParams(new
					// AbsoluteLayout.LayoutParams(w,h,x,y));
					layout.addView(but, layoutParams);
				} else if (name.equals("SelfLabel")) {
					if (isVisible(e_pe1)) {
						continue;
					}
					TextView tv = new TextView(aa);
					// tv.setBackgroundColor(Color.GRAY);
					tv.setGravity(Gravity.CENTER_VERTICAL);
					if (e_pe1.element("fontSize_style") != null) {
						tv.setTextSize(Float.parseFloat(e_pe1.elementText(
								"fontSize_style").toString()) * SysData.t_scale);
					}
					tv.setText(e_pe1.elementText("text_attribute"));
					// tv.setLayoutParams(new
					// AbsoluteLayout.LayoutParams(w,h,x,y));
					layout.addView(tv, layoutParams);
				} else if (name.equals("SelfTextInput")) {
					if (!isVisible_attribute(e_pe1, aa)) {
						continue;
					}
					if (e_pe1.attributeValue("isDouble").equals("yes")) {
						SelfTextBut stb = new SelfTextBut(aa);
						if (e_pe1.element("doubleClick_function") != null) {
							stb.setOnClickListener(aa.clickEvent);
							stb.setClickFun(e_pe1
									.elementText("doubleClick_function")
									.toString().toUpperCase());
						}
						// setTextButAtt(stb, e_pe1, aa);
						setTextButAtt((InputInterface) stb, e_pe1, aa);
						layout.addView(stb, layoutParams);
					} else {
						SelfEditText et = new SelfEditText(aa);
						if (e_pe1.element("borderStyle_style") != null) {
							et.showBorder = e_pe1.elementText(
									"borderStyle_style").toString();
						}
						et.setSingleLine(true);
						setTextButAtt((InputInterface) et, e_pe1, aa);
						layout.addView(et, layoutParams);
					}
				} else if (name.equals("SelfTextArea")) {
					if (!isVisible_attribute(e_pe1, aa)) {
						continue;
					}
					SelfEditText area = new SelfEditText(aa);
					if (e_pe1.element("borderStyle_style") != null) {
						area.showBorder = e_pe1
								.elementText("borderStyle_style").toString();
					}
					// setEditTextAtt(area, e_pe1, aa);
					setTextButAtt((InputInterface) area, e_pe1, aa);
					area.setSingleLine(false);
					// if(e_pe1.element("backgroundColor_style") !=
					// null){//backgroundColor_style
					// area.setBackgroundColor(SysUtil.toHex(e_pe1.elementText("backgroundColor_style")
					// .toString()));
					// }
					// if(e_pe1.element("color_style") !=
					// null){//backgroundColor_style
					// area.setTextColor(SysUtil.toHex(e_pe1.elementText("color_style")
					// .toString()));
					// }
					layout.addView(area, layoutParams);
				} else if (name.equals("SelfCheckBox")) {
					// if (isVisible(e_pe1)) {
					// continue;
					// }
					if (!isVisible_attribute(e_pe1, aa)) {
						continue;
					}
					SelfCheckBox box = new SelfCheckBox(aa);
					if (SysData.t_scale < 1) {
						box.setPadding((int)(box.getPaddingLeft() * SysData.t_scale * 0.2f), box.getPaddingTop(), box.getPaddingRight(), box.getPaddingBottom());
					}
					if (e_pe1.element("name_attribute") != null) {
						box.setTag(e_pe1.elementText("name_attribute")
								.toString().trim().toUpperCase());
					}
					if (e_pe1.element("label_attribute") != null) {
						box.setText(e_pe1.elementText("label_attribute")
								.toString());
					}
					if (e_pe1.element("fontSize_style") != null) {
						box.setTextSize(Float.parseFloat(e_pe1.elementText(
								"fontSize_style").toString()) * SysData.t_scale);   //checkbox + 5会变大
					}
					if (e_pe1.element("enabled_attribute") != null) {
						String enabled = e_pe1.elementText("enabled_attribute")
								.toString();
						box.setEnabled(Boolean.parseBoolean(enabled));
					}
					if (e_pe1.element("text_attribute") != null) {
						String funName = e_pe1.elementText("text_attribute")
								.toString().trim().toLowerCase();
						if (dyhs(funName, aa).equals("是")) {
							box.setChecked(true);
						}
					}
					
					layout.addView(box, layoutParams);
				} else if (name.equals("SelfImage")) {
					if (isVisible(e_pe1)) {
						continue;
					}
					SelfImage imageView = new SelfImage(aa);
					if (e_pe1.element("source_attribute") != null) {
						String url = e_pe1.elementText("source_attribute")
								.toString().trim();
						if (url.substring(0, 7).equals("http://")) {
							new Thread(new ImageUrl(imageView, url,
									aa.imgHandler)).start();
						} else if (url.indexOf(".") > 0) {
							new Thread(new ImageUrl(imageView, SysData.url
									.substring(0, SysData.url.lastIndexOf("/"))
									.concat("/").concat(url), aa.imgHandler))
									.start();
						} else if (url.length() > 0) {
							imageView.setTag(url.toUpperCase());
						}
					}
					imageView.setOnClickListener(aa.imgClickEvent);
					layout.addView(imageView, layoutParams);
				} else if (name.equals("SelfHRule") || name.equals("SelfVRule")) {
					if (isVisible(e_pe1)) {
						continue;
					}
					SelfHRule hrule = new SelfHRule(aa);
					if (e_pe1.element("strokeColor_style") != null) {
						// System.out.println();
						hrule.setColor(SysUtil.toHex(e_pe1.elementText(
								"strokeColor_style").toString()));
					}
					layout.addView(hrule, layoutParams);
				} else if (name.equals("AntLine")) {
					if (isVisible(e_pe1)) {
						continue;
					}
					AntLine al = new AntLine(aa);
					if (e_pe1.element("lineColor_attribute") != null) {
						al.setColor(SysUtil.toHex(e_pe1.elementText(
								"lineColor_attribute").toString()));
					}
					if (e_pe1.element("lineThickness_attribute") != null) {
						al.setSize(Integer.parseInt(e_pe1
								.elementText("lineThickness_attribute")) * 2);
					}
					layout.addView(al, layoutParams);
				} else if (name.equals("SelfDateField")) {
					SelfDateField df = new SelfDateField(aa);
					if (e_pe1.element("formatString_attribute") != null) {
						df.formatString = e_pe1
								.elementText("formatString_attribute")
								.toString().trim().toLowerCase();
						if (df.formatString.length() < 1) {
							df.formatString = "yyyy-mm-dd";
						}
						df.formatString = df.formatString.replace("mm", "MM");
					}
					setTextButAtt((InputInterface) df, e_pe1, aa);
					layout.addView(df, layoutParams);
				} else if (name.equals("PhotographUi")) {
					if (isVisible(e_pe1)) {
						continue;
					}
					int hh = (int) (TypedValue.applyDimension(
							TypedValue.COMPLEX_UNIT_DIP, 36, aa.getResources()
							.getDisplayMetrics()) * SysData.t_scale);
					PhotographUi pu = new PhotographUi(aa, h - hh);
					layout.addView(pu, layoutParams);
					pu.setOnClickListener(aa.pzClickEvent);
					pu.setImageOnClickListener(aa.imgClickEvent);
					if (e_pe1.element("name_attribute") != null) {
						pu.setTag(e_pe1.elementText("name_attribute")
								.toString().trim().toUpperCase());
					}
				}
			}
			aa.setTabwidgetAtt(aa.hzTab.getTabWidget());
			aa.hzTab.setCurrentTab(0);
			// break;
		}
	}

	// /* 设置属性 */
	// public static void setEditTextAtt(SelfEditText et, Element e_pe1,
	// DjActivity djActivity) {
	// et.setPadding(0, 0, 0, 0);
	// et.setGravity(Gravity.CENTER_VERTICAL);
	// if (e_pe1.element("name_attribute") != null) {
	// et.setTag(e_pe1.elementText("name_attribute").toString().trim()
	// .toUpperCase());
	// }
	// if (e_pe1.element("enterKey") != null) {
	// et.nextFocus = e_pe1.elementText("enterKey").toString()
	// .toUpperCase();
	// }
	// if (e_pe1.element("fontSize_style") != null) {
	// et.setTextSize(Float.parseFloat(e_pe1.elementText("fontSize_style")
	// .toString()) + 5);
	// }
	// // et.setText(e_pe1.elementText("text_attribute"));
	// boolean b = false;// 判断是否需要加焦点事件
	// if (e_pe1.element("focusOut_function") != null) {
	// et.focusOutFun = e_pe1.elementText("focusOut_function").toString();
	// if (!b) {
	// b = true;
	// }
	// }
	// if (e_pe1.element("focusIn_function") != null) {
	// et.focusInFun = e_pe1.elementText("focusIn_function").toString();
	// if (!b) {
	// b = true;
	// }
	// }
	// if (b) {
	// et.setOnFocusChangeListener(djActivity.focusEvent);
	// }
	// if (e_pe1.element("enabled_attribute") != null) {
	// Boolean enabled = Boolean.parseBoolean(e_pe1.elementText(
	// "enabled_attribute").toString());
	// et.setEnabled(enabled);
	// if (!enabled) {
	// if (e_pe1.element("backgroundColor_style") != null) {//
	// backgroundColor_style
	// et.setBackgroundDrawable(SysUtil.GradientDrawable(e_pe1
	// .elementText("backgroundColor_style").toString()));
	// }
	// }
	// }
	// if (e_pe1.element("text_attribute") != null) {
	// String funName = e_pe1.elementText("text_attribute").toString()
	// .trim();
	// DjMenuFun menufun = new DjMenuFun();
	// Class cla = menufun.getClass();
	// try {
	// Method method = cla.getDeclaredMethod(funName);
	// if (method != null) {
	// et.setText(method.invoke(menufun).toString());
	// }
	// } catch (Exception e) {
	// et.setText(funName);
	// }
	// }
	// }
	public static boolean isVisible(Element e_pe1) {
		boolean b = false;
		if (e_pe1.element("visible_attribute") != null) {
			if (e_pe1.elementText("visible_attribute").toString().trim()
					.equals("false")) {
				b = true;
			} else {
				b = false;
			}
		}
		return b;
	}

	/* 设置属性 */
	public static void setTextButAtt(InputInterface et, Element e_pe1,
			DjActivity djActivity) {
		et.setPadding(0, 0, 0, 0);
		et.setGravity(Gravity.CENTER_VERTICAL);
		if (e_pe1.element("name_attribute") != null) {
			et.setTag(e_pe1.elementText("name_attribute").toString().trim()
					.toUpperCase());
		}
		if (e_pe1.element("enterKey") != null) {
			et.setNextFocus(e_pe1.elementText("enterKey").toString()
					.toUpperCase());
		}
		if (e_pe1.element("fontSize_style") != null) {
			et.setTextSize(Float.parseFloat(e_pe1.elementText("fontSize_style")
					.toString()) * SysData.t_scale + 5);
		}
		if (e_pe1.element("closeKeyBoard") != null) {
			boolean closeKeyBoard = Boolean.parseBoolean(e_pe1
					.elementText("closeKeyBoard"));
			et.setCloseKeyBoard(closeKeyBoard);
			if (closeKeyBoard) {
				et.setInputType(InputType.TYPE_NULL);
			}
		}
		// if(e_pe1.element("doubleClick_function") != null){
		// et.setOnClickListener(djActivity.clickEvent);
		// et.setClickFun(e_pe1.elementText("doubleClick_function").toString().toUpperCase());
		// }
		// et.setText(e_pe1.elementText("text_attribute"));
		// boolean b = false;// 判断是否需要加焦点事件
		if (e_pe1.element("focusOut_function") != null) {
			et.setFocusOutFun(e_pe1.elementText("focusOut_function").toString());
			// if (!b) {
			// b = true;
			// }
		}
		if (e_pe1.element("focusIn_function") != null) {
			et.setFocusInFun(e_pe1.elementText("focusIn_function").toString());
			// if (!b) {
			// b = true;
			// }
		}
		// if (b) {
		et.setOnFocusChangeListener(djActivity.focusEvent);
		// }
		if (e_pe1.element("enabled_attribute") != null) {
			Boolean enabled = Boolean.parseBoolean(e_pe1.elementText(
					"enabled_attribute").toString());
			et.setEnabled(enabled);
			// if (!enabled) {
			// }
		}
		if (e_pe1.element("backgroundColor_style") != null) {// backgroundColor_style
			et.setBackgroundDrawable(SysUtil.GradientDrawable(e_pe1
					.elementText("backgroundColor_style").toString()));
		} else {
			et.setBackgroundDrawable(SysUtil.GradientDrawable());
		}
		if (e_pe1.element("text_attribute") != null) {
			String funName = e_pe1.elementText("text_attribute").toString()
					.trim().toLowerCase();
			et.setText(dyhs(funName, djActivity));
		}
		if (e_pe1.element("isValue_attribute") != null) {
			et.setIsNull(Boolean.parseBoolean(e_pe1
					.elementText("isValue_attribute")));
		}
		if (e_pe1.element("label_attribute") != null) {
			et.setLabel(e_pe1.elementText("label_attribute").toString().trim());
		}
		if (e_pe1.element("label_attribute") != null) {
			et.setLabel(e_pe1.elementText("label_attribute").toString().trim());
		}
		if (e_pe1.element("color_style") != null) {
			et.setTextColor(SysUtil.toHex(e_pe1.elementText("color_style")
					.toString().trim()));
		}
		// if (e_pe1.element("fdtype")!= null) {
		// String fdtype=e_pe1.elementText("fdtype").toString().trim();
		// if(fdtype.equals("整数")){
		// et.setDefaultValue("0");
		// }else if(fdtype.equals("实数")||fdtype.equals("浮点")){
		// et.setDefaultValue("0.00");
		// }
		// }
	}

	public static String dyhs(String funName, DjActivity activity) {
		String val = "";
		DjMenuFun menufun = new DjMenuFun();
		Class cla = menufun.getClass();
		try {
			Method method = cla.getDeclaredMethod(funName, DjActivity.class);
			if (method != null) {
				// if(method.getGenericParameterTypes().length>0){
				val = method.invoke(menufun, new Object[] { activity })
						.toString();
				// }else{
				// val = method.invoke(menufun).toString();
				// }
			} else {
				val = funName;
			}
		} catch (Exception e) {
			// e.printStackTrace();
			val = funName;
		}
		return val;
	}

	/* 解析更新xml */
	public static UpdataInfo parserXml(InputStream in, String version)
			throws DocumentException {
		version = version.substring(0, 1).toUpperCase();
		// 产生一个解析器对象
		SAXReader reader = new SAXReader();
		reader.setEncoding("UTF-8");
		// 将xml文档转换为Document的对象
		Document document = reader.read(in);
		// 获取文档的根元素
		Element root = document.getRootElement();
		UpdataInfo info = null;
		List<Element> list = root.elements();
		if (list != null) {
			for (int i = 0; i < list.size(); i++) {
				root = list.get(i);
				if (root.getName().toUpperCase().equals("PDA")) {
					Iterator i_pe = root.elementIterator();
					if (root.attributeValue("model").toUpperCase()
							.equals(version)) {
						info = gerUpdataInfo(i_pe);
						break;
					}
				}
			}
		}
		return info;
	}

	public static UpdataInfo gerUpdataInfo(Iterator i_pe) {
		String name = null;
		UpdataInfo info = new UpdataInfo();// 实体
		while (i_pe.hasNext()) {
			Element e_pe = (Element) i_pe.next();
			name = e_pe.getName();
			if ("version".equals(name)) {
				info.setVersion(e_pe.getText()); // 获取版本号
			} else if ("url".equals(name)) {
				info.setUrl(e_pe.getText()); // 获取要升级的APK文件
			} else if ("description".equals(name)) {
				info.setDescription(e_pe.getText()); // 获取该文件的信息
			}
		}
		return info;
	}

	public static boolean isVisible_attribute(Element e_pe11,
			DjActivity djActivity) {
		boolean isVisible = true;
		if (e_pe11.element("visible_attribute") != null) {
			if (e_pe11.elementText("visible_attribute").toString().trim()
					.equals("false")) {
				isVisible = false;
				String val = "";
				if (e_pe11.element("text_attribute") != null) {
					String funName = e_pe11.elementText("text_attribute")
							.toString().trim();
					val = dyhs(funName, djActivity);
				}
				// if(val==null||val.length()==0){
				// if (e_pe11.element("fdtype")!= null) {
				// String fdtype=e_pe11.elementText("fdtype").toString().trim();
				// if(fdtype.equals("整数")){
				// val="0";
				// }else if(fdtype.equals("实数")||fdtype.equals("浮点")){
				// val="0.00";
				// }else{
				// val="";
				// }
				// }
				// }
				if (e_pe11.element("name_attribute") != null) {
					djActivity.pageMap.put(e_pe11.elementText("name_attribute")
							.toString().trim().toUpperCase(), val);
				}
			}
		}
		return isVisible;
	}
}
