package com.jw.app.business.portlet;

import java.io.IOException;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.commons.codec.binary.Base64;

import com.gaowj.business.exception.BusinessException;
import com.gaowj.business.util.Encipher;
import com.gaowj.business.util.SessionUtil;
import com.jw.app.business.PortletBusiness;
import com.jw.app.business.utils.QueryParamUtil;

public class PortletBusinessImpl implements PortletBusiness {

	/**
	 * 默认模板的标识符
	 */
	private static final String DEFAULT = "default";

	private PortletDAO portletDAO;

	public PortletDAO getPortletDAO() {
		return portletDAO;
	}

	public void setPortletDAO(PortletDAO portletDAO) {
		this.portletDAO = portletDAO;
	}

	@Override
	public List<Map<String, Object>> list_portlet_template_by_user(Map<String, Object> query) throws BusinessException {
		List<Map<String, Object>> listData = null;
		try {
			query.put("USER_ID", SessionUtil.getEmid());
			Map<String, Object> m=SessionUtil.getSessionUser();
			query.put("G_ID", m.get("EMDEPART"));
			//通过G_ID和COLUMN_ID过滤下
			listData = QueryParamUtil.ClobToString(portletDAO.list_portlet_template_user(query));
			if (listData.size() == 0) {
				// 如果当前登陆人还没有设置自定义的资源，则显示默认的资源
				query.put("USER_ID", DEFAULT);
				listData = QueryParamUtil.ClobToString(portletDAO.list_portlet_template_user(query));
			}
			manageMap(listData);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return listData;
	}

	/**
	 * 处理特殊信息
	 * 
	 * @param listData
	 */
	private void manageMap(List<Map<String, Object>> listData) {
		for (Map<String, Object> map : listData) {
			if ("5".equals(map.get("P_TYPE"))) {
				// 如果是内容发布，则将内容发布的信息传回去
				Map<String, Object> contentQuery = new HashMap<String, Object>();
				contentQuery.put("PORTAL_ID", map.get("PORTLET_ID"));
				List<Map<String, Object>> listInfo = portletDAO.list_portlet_content(contentQuery);
				map.put("INFOS", listInfo);
			} else if ("4".equals(map.get("P_TYPE"))) {
				// 如果是模拟登陆，则把登录的url和用户密码传回去
				Map<String, Object> appQuery = new HashMap<String, Object>();
				// 当前登陆人，当前需要模拟登录的APP_ID
				appQuery.put("APP_ID", map.get("APP_ID"));
				appQuery.put("USER_ID", SessionUtil.getEmid());
				List<Map<String, Object>> listWebInfo = portletDAO.list_app_acount(appQuery);
				if (listWebInfo.size() > 0) {
					Map<String,Object> webInfo=listWebInfo.get(0);
					//将登陆密码临时修改为base64编码传给前台
					String userPwd=webInfo.get("USER_PWD").toString();
					userPwd=Encipher.DecodePasswd(userPwd);
					byte[] result = Base64.encodeBase64(userPwd.getBytes());
					webInfo.put("USER_PWD",new String(result));
					map.put("WEB_INFO", webInfo);
				}
			}
		}
	}

	@Override
	public List<Map<String, Object>> list_portlet_columns(Map<String, Object> query) throws BusinessException {
		List<Map<String, Object>> listData = null;
		try {
			listData = QueryParamUtil.ClobToString(portletDAO.list_portlet_columns(query));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return listData;
	}

	@Override
	public List<Map<String, Object>> list_portlet_template(Map<String, Object> query) throws BusinessException {
		List<Map<String, Object>> listData = null;
		try {
			Map<String, Object> m=SessionUtil.getSessionUser();
			query.put("G_ID", m.get("EMDEPART"));
			listData = QueryParamUtil.ClobToString(portletDAO.list_portlet_template(query));
			manageMap(listData);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return listData;
	}

	@Override
	public void saveLayout(String columnsId, List<Map<String, Object>> list) throws BusinessException {
		String userId = SessionUtil.getEmid();
		List<Map<String, Object>> listData = null;
		try {
			Map<String, Object> query = new HashMap<String, Object>();
			query.put("USER_ID", userId);
			query.put("COLUMN_ID", columnsId);
			listData = QueryParamUtil.ClobToString(portletDAO.list_portlet_template_user(query));
			if (listData.size() == 0) {
				// 如果当前登陆人没有设置自己的模板布局，则查询默认的布局
				query.put("USER_ID", DEFAULT);
				listData = QueryParamUtil.ClobToString(portletDAO.list_portlet_template_user(query));
			}

			// 验证用户传过来的布局和数据库中的布局是否一致，默认为一致
			boolean same = true;
			if (listData.size() != list.size()) {
				same = false;
			} else {
				// 长度一致的情况下，判断每一个索引所在位置的portletId是否一致
				for (int i = 0; i < listData.size(); i++) {
					// 只要有一个不满足，则设置same为false
					if (!listData.get(i).get("PORTLET_ID").equals(list.get(i).get("PORTLET_ID"))) {
						same = false;
						break;
					}
				}
			}
			if (!same) {
				// 如果不一致，则将用户的自定义模板布局删除，重新添加新布局进行保存
				//1.先做查询
				query.put("USER_ID", userId);
				List<Map<String, Object>> list_select_template  =  QueryParamUtil.ClobToString(portletDAO.list_portlet_template_user(query));
				for(Map<String, Object> select : list_select_template){
					//2.再遍历删除
					Map<String, Object> deleteQuery = new HashMap<String, Object>();
					deleteQuery.put("ID", select.get("id"));
					portletDAO.delete_portlet_template_user(deleteQuery);
				}
				// 重新添加
				int index = 0;
				SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				String now = formatter.format(new Date());
				for (Map<String, Object> map : list) {
					map.put("ID", UUID.randomUUID().toString());
					map.put("USER_ID", userId);
					map.put("ORDER_NUM", index++);
					map.put("IS_DELETE", 0);
					map.put("CREATE_USER", userId);
					map.put("CREATE_TIME", now);
					map.put("COLUMN_ID",columnsId);
					portletDAO.insert_portlet_template_user(mapToList(map));
				}
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private List<Map<String, Object>> mapToList(Map<String, Object> map) {
		List<Map<String, Object>> entity = new ArrayList<Map<String, Object>>();
		for (Map.Entry<String, Object> entry : map.entrySet()) {
			Map<String, Object> field = new HashMap<String, Object>();
			field.put("key", entry.getKey());
			field.put("value", entry.getValue());
			entity.add(field);
		}
		return entity;
	}

}
