package net.wicp.tams.duckula.ops.pages;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.tapestry5.SymbolConstants;
import org.apache.tapestry5.annotations.Environmental;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.commons.Messages;
import org.apache.tapestry5.http.services.Request;
import org.apache.tapestry5.http.services.RequestGlobals;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.ioc.annotations.InjectService;
import org.apache.tapestry5.ioc.annotations.Symbol;
import org.apache.tapestry5.services.javascript.JavaScriptSupport;
import org.apache.tapestry5.util.TextStreamResponse;

import net.wicp.tams.common.Result;
import net.wicp.tams.common.apiext.DateUtil;
import net.wicp.tams.common.apiext.NumberUtil;
import net.wicp.tams.common.apiext.StringUtil;
import net.wicp.tams.common.apiext.json.EasyUiAssist;
import net.wicp.tams.common.callback.IConvertValue;
import net.wicp.tams.common.callback.impl.convertvalue.ConvertValueEnum;
import net.wicp.tams.component.services.ISupportedLocales;
import net.wicp.tams.component.tools.TapestryAssist;

@SuppressWarnings("rawtypes")
public abstract class ParentPage {

	@InjectService("locales")
	protected ISupportedLocales supportedLocales;

	@Inject
	protected Request request;

	@Inject
	protected RequestGlobals requestGlobals;

	@Inject
	protected Messages messages;// 国际化

	@Environmental
	protected JavaScriptSupport javaScriptSupport;

	@Inject
	@Symbol(SymbolConstants.CONTEXT_PATH)
	@Property
	protected String contextPath;
	
	@Inject
	protected ServletContext servletContext;

	@Property
	protected String lan = supportedLocales.getCurLocale().getLanguage();// 当前选择语言

	/****
	 * 国际化方法 可以把数据库取出来的值进行国际化 eg:${L('order.channel')}
	 *
	 * @param path 要国际化的值所在的路径
	 * @return
	 */
	public String L(String path) {
		try {
			Object obj = PropertyUtils.getProperty(this, path);
			String objkey = String.valueOf(obj);
			if (StringUtil.isNull(objkey)) {
				return "";
			}
			return messages.get(objkey);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return path;
	}

	/****
	 * 对具的key值进行国际化，可以支持传参数,eg:${LK('Tmall',['aaa','bbb'])}
	 *
	 * @param key   国际化的key值
	 * @param param 所带的参数
	 * @return
	 */
	public String LK(String key, Object... param) {
		return TapestryAssist.LK(messages, key, param);
	}

	/***
	 * 把某个时间字段格式化为yyyy-MM-dd HH:mm:ss
	 *
	 * @param path 要格式化的值所在的路径
	 * @return
	 */
	public String T(String path) {
		return DateUtil.formatDate(this, path, null, true);
	}

	/****
	 * 把某个时间字段格式化为yyyy-MM-dd
	 *
	 * @param path 要格式化的值所在的路径
	 * @return
	 */
	public String D(String path) {
		return DateUtil.formatDate(this, path, null, false);
	}

	/****
	 * 金钱格式化
	 *
	 * @param path
	 * @return
	 */
	public String M(String value) {
		if (StringUtil.isNull(value)) {
			return "";
		}
		try {
			BigDecimal retObj = NumberUtil.handleScale(value, 2);
			return String.valueOf(retObj);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "";
	}

	protected final IConvertValue I18NConvert = new IConvertValue<String>() {
		@Override
		public String getStr(String key) {
			if (StringUtil.isNull(key) || !messages.contains(key)) {
				return key;
			}
			return messages.get(key);
		}
	};

	/***
	 * 此处如果没有缓存将非常慢 optionItem的国际化解析
	 */
	// protected final IConvertValue optConvert = new
	// ConvertValueOpt(supportedLocales);

	/****
	 * 支持国际化 的grid
	 *
	 * @param fromList
	 * @param titles
	 * @param recordNum
	 * @param convertTitles 需要国际化的列会新增一列，规则为 列名+1
	 * @return
	 */
	protected final String getJsonForGridForI18n(List<?> fromList, String[] titles, long recordNum,
			String... convertTitles) {
		IConvertValue[] convert = null;
		if (org.apache.commons.lang3.ArrayUtils.isNotEmpty(convertTitles)) {
			// titles=org.apache.commons.lang3.ArrayUtils.addAll(titles,
			// convertTitles);
			convert = new IConvertValue[titles.length + convertTitles.length];
			for (int i = 0; i < convertTitles.length; i++) {
				String title1 = String.format("%s,%s", convertTitles[i], convertTitles[i] + "1");
				org.apache.commons.lang3.ArrayUtils.add(titles, title1);
				convert[titles.length + i] = I18NConvert;
			}
		}
		return EasyUiAssist.getJsonForGrid(fromList, titles, convert, recordNum);
	}

	/****
	 * 支持国际化的grid
	 *
	 * @param fromList
	 * @param recordNum
	 * @param convertTitles 需要国际化的列会新增一列，规则为 列名+1
	 * @return
	 */
	protected final String getJsonForGridAliasForI18n(List<?> fromList, long recordNum, String... convertTitles) {
		if (ArrayUtils.isNotEmpty(convertTitles)) {
			Map<String, IConvertValue> convertsMap = new HashMap<String, IConvertValue>();
			String[] alisAry = new String[convertTitles.length];
			for (int i = 0; i < convertTitles.length; i++) {
				String title = convertTitles[i];
				String titleAlis = title + "1";
				alisAry[i] = String.format("%s,%s", title, titleAlis);
				convertsMap.put(titleAlis, I18NConvert);
			}
			return EasyUiAssist.getJsonForGridAlias2(fromList, alisAry, convertsMap, recordNum);
		} else {
			return EasyUiAssist.getJsonForGridAlias(fromList, recordNum);
		}
	}

	/****
	 * 把指定的Str作为流返回
	 *
	 * @param str
	 * @return
	 */
	protected TextStreamResponse retStream(String str) {
		return TapestryAssist.getTextStreamResponse(str);
	}

	/***
	 * 返回空的grid数据流
	 *
	 * @return
	 */
	protected TextStreamResponse retStreamEmpty() {
		return retStream(EasyUiAssist.getJsonForGridEmpty());
	}

	/***
	 * 得到枚举型的转换器
	 *
	 * @param entityClass
	 * @return
	 */
	protected IConvertValue proEnumConvert(Class entityClass) {
		return new ConvertValueEnum(entityClass, supportedLocales.getCurLocale().getLanguage());
	}

	protected TextStreamResponse retSuccInfo() {
		return TapestryAssist.getTextStreamResponse(Result.getSuc());
	}

	protected TextStreamResponse retErrorInfo() {
		return retErrorInfo(null);
	}

	protected TextStreamResponse retErrorInfo(String errmsg) {
		if (StringUtil.isNull(errmsg)) {
			errmsg = "common.hint.error";
		}
		return TapestryAssist.getTextStreamResponse(Result.getError(errmsg));
	}

	/****
	 * 如 itemName 返回 "itemName_zh,itemName"
	 *
	 * @param colName
	 * @return
	 */
	public String getColLan(String colName) {
		String lan = supportedLocales.getCurLocale().getLanguage().substring(0, 1).toUpperCase()
				+ supportedLocales.getCurLocale().getLanguage().substring(1);
		return String.format("%s%s,%s", colName, lan, colName);
	}

}
