package cn.myapps.support.weixin.weioa365.controller;

import cn.myapps.authtime.common.service.AuthTimeServiceManager;
import cn.myapps.authtime.department.model.DepartmentVO;
import cn.myapps.authtime.department.service.DepartmentProcess;
import cn.myapps.authtime.domain.model.DomainVO;
import cn.myapps.authtime.domain.service.DomainProcess;
import cn.myapps.authtime.fieldextends.model.FieldExtendsVO;
import cn.myapps.authtime.fieldextends.service.FieldExtendsProcess;
import cn.myapps.authtime.user.model.UserDepartmentRoleSet;
import cn.myapps.authtime.user.model.UserVO;
import cn.myapps.authtime.user.service.UserProcess;
import cn.myapps.authtime.workcalendar.calendar.model.CalendarVO;
import cn.myapps.authtime.workcalendar.calendar.service.CalendarProcess;
import cn.myapps.common.Environment;
import cn.myapps.common.data.ParamsTable;
import cn.myapps.common.model.application.Application;
import cn.myapps.common.model.role.Role;
import cn.myapps.common.util.Base64Util;
import cn.myapps.common.util.StringUtil;
import cn.myapps.constans.Web;
import cn.myapps.designtime.role.service.RoleDesignTimeService;
import cn.myapps.util.ProcessFactory;
import it.sauronsoftware.jave.*;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.codehaus.jackson.map.annotate.JsonSerialize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.math.MathContext;
import java.net.URL;
import java.net.URLEncoder;
import java.util.List;
import java.util.*;

@RestController(value = "MyappsServiceAction")
@RequestMapping(value = "/weioa365/services")
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
public class MyappsServiceController {

	private static final String weioa365_addr = "https://yun.weioa365.com/{site_id}";

	protected static final String ACTION_RESULT_KEY = "status";
	protected static final int ACTION_RESULT_VALUE_SUCCESS = 1;
	protected static final int ACTION_RESULT_VALUE_FAULT = 0;

	protected static final String ACTION_MESSAGE_KEY = "message";
	protected static final String ACTION_DATA_KEY = "data";

	protected ParamsTable params;

	@Autowired
	protected HttpServletRequest request;

	@Autowired
	protected HttpSession session;

	// 灏嗕細琚玈truts2搴忓垪鍖栦负JSON瀛楃涓茬殑瀵硅薄,鐢ㄦ潵浣滀负鎺у埗灞傝繑鍥炵粨鏋滅殑瀹瑰櫒
	protected Map<String, Object> dataMap = new HashMap<String, Object>();

	/**
	 * 鑾峰彇浼佷笟鍩熶笅鐨勬墍鏈夐儴闂ㄩ泦鍚�
	 * 
	 * @return
	 */
	@RequestMapping(value = "/getDepartments.action")
	public Map<String, Object> getDepartments() {
		try {
			Collection<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
			ParamsTable params = getParams();
			String siteId = params.getParameterAsString("site_id");
			String domainId = params.getParameterAsString("domain_id");

			DepartmentProcess process = AuthTimeServiceManager.departmentRuntimeService();
			Collection<DepartmentVO> depts = new ArrayList<DepartmentVO>();
//			Map<String,Object> sqlParameterMap = new HashMap<String,Object>();
//			String hql = "from " + DepartmentVO.class.getName() + " vo where vo.domain.id = :domainid " 
//			+ " and vo.valid = 1 order by vo.level asc,vo.orderByNo";
//			sqlParameterMap.put("domainid", domainId);
//			depts.addAll(process.doQueryByHQL(hql, 1, Integer.MAX_VALUE,sqlParameterMap));
			depts.addAll(process.doQueryByDomainAndValid(domainId, 1));
			for (Iterator<DepartmentVO> iterator = depts.iterator(); iterator.hasNext();) {
				DepartmentVO dept = iterator.next();
				list.add(department2Map(dept));
			}

			return addActionResult(true, "", list);
		} catch (Exception e) {
			e.printStackTrace();
			return addActionResult(false, e.getMessage(), null);
		}
	}

	@RequestMapping(value = "/updateDepartment.action")
	public Map<String, Object> updateDepartment() {
		try {
			DepartmentProcess process = AuthTimeServiceManager.departmentRuntimeService();
			ParamsTable params = getParams();
			String siteId = params.getParameterAsString("site_id");
			String domainId = params.getParameterAsString("domain_id");

			String postDate = getPostDataAsString();

			if (!StringUtil.isBlank(postDate)) {
				JSONObject dept = JSONObject.fromObject(postDate);
				String id = dept.getString("id");
				DepartmentVO vo = (DepartmentVO) process.doView(id);
				if (vo != null) {
					vo.setName(dept.getString("name"));
					vo.setWeixinDeptId(dept.getString("weixinDeptId"));
					String superior = dept.getString("superior");
					if (!StringUtil.isBlank(superior)) {
						DepartmentVO superiorVO = (DepartmentVO) process.doView(superior);
						vo.setSuperior(superiorVO);
					}
					process.doUpdate(vo);
				}

			}
			return addActionResult(true, "", "success");
		} catch (Exception e) {
			e.printStackTrace();
			return addActionResult(false, e.getMessage(), null);
		}
	}

	@RequestMapping(value = "/createDepartment.action")
	public Map<String, Object> createDepartment() {
		try {
			DepartmentProcess process = AuthTimeServiceManager.departmentRuntimeService();
			DomainProcess domainProcess = AuthTimeServiceManager.domainRuntimeService();

			ParamsTable params = getParams();
			String siteId = params.getParameterAsString("site_id");
			String domainId = params.getParameterAsString("domain_id");

			DomainVO domain = (DomainVO) domainProcess.doView(domainId);

			String postDate = getPostDataAsString();

			if (!StringUtil.isBlank(postDate)) {
				JSONObject dept = JSONObject.fromObject(postDate);
				String id = dept.getString("id");
				DepartmentVO d = new DepartmentVO();
				d.setId(id);
				d.setName(dept.getString("name"));
				d.setLevel(dept.getInt("level"));
				d.setDomain(domain);
				d.setDomainid(domainId);
				d.setWeixinDeptId(dept.getString("weixinDeptId"));
				String superior = dept.getString("superior");
				if (!StringUtil.isBlank(superior)) {
					DepartmentVO superiorVO = (DepartmentVO) process.doView(superior);
					d.setSuperior(superiorVO);
				}
				process.doCreate(d);

			}
			return addActionResult(true, "", "success");
		} catch (Exception e) {
			e.printStackTrace();
			return addActionResult(false, e.getMessage(), null);
		}
	}

	@RequestMapping(value = "/updateDepartments.action")
	public Map<String, Object> updateDepartments() {
		try {
			DepartmentProcess process = AuthTimeServiceManager.departmentRuntimeService();
			ParamsTable params = getParams();
			String siteId = params.getParameterAsString("site_id");
			String domainId = params.getParameterAsString("domain_id");

			String postDate = getPostDataAsString();

			if (!StringUtil.isBlank(postDate)) {
				try {
					JSONArray arr = cn.myapps.util.json.JsonTmpUtil.fromObject(postDate);
					for (Iterator<JSONObject> iterator = arr.iterator(); iterator.hasNext(); ) {
						JSONObject dept = (JSONObject) iterator.next();
						String id = dept.getString("id");
						DepartmentVO vo = (DepartmentVO) process.doView(id);
						if (vo == null)
							continue;
						vo.setName(dept.getString("name"));
						vo.setWeixinDeptId(dept.getString("weixinDeptId"));
						String superior = dept.getString("superior");
						if (!StringUtil.isBlank(superior)) {
							DepartmentVO superiorVO = (DepartmentVO) process.doView(superior);
							vo.setSuperior(superiorVO);
						}
						process.doUpdate(vo);
					}
				}
				catch (Exception ex) {
					ex.printStackTrace();
				}
			}
			return addActionResult(true, "", "success");
		} catch (Exception e) {
			e.printStackTrace();
			return addActionResult(false, e.getMessage(), null);
		}
	}

	@RequestMapping(value = "/getDepartmentsByLevel.action")
	public Map<String, Object> getDepartmentsByLevel() {
		try {
			Collection<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
			ParamsTable params = getParams();
			String siteId = params.getParameterAsString("site_id");
			String domainId = params.getParameterAsString("domain_id");
			int level = params.getParameterAsInteger("level");

			DepartmentProcess process = AuthTimeServiceManager.departmentRuntimeService();
			Collection<DepartmentVO> depts = new ArrayList<DepartmentVO>();
			depts.addAll(process.getDepartmentByLevel(level, domainId));
			for (Iterator<DepartmentVO> iterator = depts.iterator(); iterator.hasNext();) {
				DepartmentVO dept = iterator.next();
				list.add(department2Map(dept));
			}

			return addActionResult(true, "", list);
		} catch (Exception e) {
			e.printStackTrace();
			return addActionResult(false, e.getMessage(), null);
		}
	}

	@RequestMapping(value = "/getDepartmentsByLevelAndName.action")
	public Map<String, Object> getDepartmentsByLevelAndName() {
		try {
			Collection<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
			ParamsTable params = getParams();
			String siteId = params.getParameterAsString("site_id");
			String domainId = params.getParameterAsString("domain_id");
			String postDate = getPostDataAsString();
			if (!StringUtil.isBlank(postDate)) {
				JSONObject jo = JSONObject.fromObject(postDate);
				Map<String, Object> map = (Map<String, Object>) JSONObject.toBean(jo, Map.class);
				params.putAll(map);
			}

			int level = Integer.valueOf(params.getParameterAsString("level"));
			String name = params.getParameterAsString("name");

			DepartmentProcess process = AuthTimeServiceManager.departmentRuntimeService();
			Collection<DepartmentVO> depts = new ArrayList<DepartmentVO>();
			depts.add(process.getDepartmentByNameAndLevel(name, level, domainId));
			for (Iterator<DepartmentVO> iterator = depts.iterator(); iterator.hasNext();) {
				DepartmentVO dept = iterator.next();
				list.add(department2Map(dept));
			}

			return addActionResult(true, "", list);
		} catch (Exception e) {
			e.printStackTrace();
			return addActionResult(false, e.getMessage(), null);
		}
	}

	@RequestMapping(value = "/getDepartmentsByParams.action")
	public Map<String, Object> getDepartmentsByParams() {
		try {
			Collection<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
			ParamsTable params = getParams();
			String siteId = params.getParameterAsString("site_id");
			String domainId = params.getParameterAsString("domain_id");

			String postDate = getPostDataAsString();
			if (!StringUtil.isBlank(postDate)) {
				JSONObject jo = JSONObject.fromObject(postDate);
				Map<String, Object> map = (Map<String, Object>) JSONObject.toBean(jo, Map.class);
				params.putAll(map);
			}

			params.setParameter("t_domain.id", domainId);
			DepartmentProcess process = AuthTimeServiceManager.departmentRuntimeService();
			Collection<DepartmentVO> depts = new ArrayList<DepartmentVO>();
			String application = params.getParameterAsString("application");
			depts.addAll(process.doQueryByDomainAndApplication(domainId,application));
			for (Iterator<DepartmentVO> iterator = depts.iterator(); iterator.hasNext();) {
				DepartmentVO dept = iterator.next();
				list.add(department2Map(dept));
			}
			return addActionResult(true, "", list);
		} catch (Exception e) {
			e.printStackTrace();
			return addActionResult(false, e.getMessage(), null);
		}
	}

	@RequestMapping(value = "/getUsersByParams.action")
	public Map<String, Object> getUsersByParams() {
		try {
			Collection<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
			ParamsTable params = getParams();
			String siteId = params.getParameterAsString("site_id");
			String domainId = params.getParameterAsString("domain_id");
			params.setParameter("t_domainid", domainId);
			String postDate = getPostDataAsString();
			if (!StringUtil.isBlank(postDate)) {
				JSONObject jo = JSONObject.fromObject(postDate);
				Map<String, Object> map = (Map<String, Object>) JSONObject.toBean(jo, Map.class);
				params.putAll(map);
			}

			UserProcess process = AuthTimeServiceManager.userRuntimeService();
			Collection<UserVO> users = new ArrayList<UserVO>();
			String status = params.getParameterAsString("sm_dimission");
			String superior = params.getParameterAsString("t_superior");
			String _currpage = params.getParameterAsString("_currpage");
			String _pagelines = params.getParameterAsString("_pagelines");
			int page = (_currpage != null && _currpage.length() > 0) ? Integer.parseInt(_currpage) : 1;
			int lines = (_pagelines != null && _pagelines.length() > 0) ? Integer.parseInt(_pagelines) : Integer.MAX_VALUE;
			users.addAll(process.doQueryLikeStatusLikeSuperior(domainId,status,superior,page,lines));
			for (Iterator<UserVO> iterator = users.iterator(); iterator.hasNext();) {
				UserVO u = iterator.next();
				list.add(user2Map(u));
			}
			return addActionResult(true, "", list);
		} catch (Exception e) {
			e.printStackTrace();
			return addActionResult(false, e.getMessage(), null);
		}
	}

	@RequestMapping(value = "/updateUser.action")
	public Map<String, Object> updateUser() {
		try {
			UserProcess process = AuthTimeServiceManager.userRuntimeService();
			ParamsTable params = getParams();
			String siteId = params.getParameterAsString("site_id");
			String domainId = params.getParameterAsString("domain_id");

			String postDate = getPostDataAsString();

			if (!StringUtil.isBlank(postDate)) {
				JSONObject user = JSONObject.fromObject(postDate);
				String id = user.getString("id");
				UserVO vo = (UserVO) process.doView(id);
				if (vo != null) {
					vo.setName(user.getString("name"));
					vo.setEmail(user.getString("email"));
					vo.setTelephone(user.getString("telephone"));
					vo.setAvatar(user.getString("avatar"));

					// 鏇存柊鎷撳睍瀛楁
					if (!StringUtils.isBlank(user.getString("extattr"))) {

						FieldExtendsProcess fieldExtendsProcess = (FieldExtendsProcess) ProcessFactory
								.createProcess(FieldExtendsProcess.class);
						List<FieldExtendsVO> fieldExtendses = fieldExtendsProcess.queryFieldExtendsByTable(domainId,
								FieldExtendsVO.TABLE_USER);
						List<FieldExtendsVO> fes = new ArrayList<FieldExtendsVO>();
						for (int i = 0; i < fieldExtendses.size(); i++) {
							FieldExtendsVO fevo = fieldExtendses.get(i);
							if (fevo != null && fevo.getEnabel()) {
								fes.add(fevo);
							}
						}

						if (user.containsKey("extattr") && !fes.isEmpty()) {
							JSONObject extattr = JSONObject.fromObject(user.getString("extattr"));
							JSONArray attrs = extattr.getJSONArray("attrs");
							for (Iterator<FieldExtendsVO> iterator3 = fes.iterator(); iterator3.hasNext();) {
								FieldExtendsVO fe = iterator3.next();
								String name = fe.getLabel();
								for (Iterator<JSONObject> iterator4 = attrs.iterator(); iterator4.hasNext();) {
									JSONObject attr = iterator4.next();
									if (name.equals(attr.getString("name"))) {
										String fieldName = fe.getName();
										fieldName = fieldName.replaceFirst("f", "F");
										Method method = UserVO.class.getMethod("set" + fieldName, String.class);
										method.invoke(vo, attr.getString("value"));
										break;
									}
								}
							}
						}
					}
					process.doUpdate(vo);
				}

			}
			return addActionResult(true, "", "success");
		} catch (Exception e) {
			e.printStackTrace();
			return addActionResult(false, e.getMessage(), null);
		}
	}

	@RequestMapping(value = "/createUser.action")
	public Map<String, Object> createUser() {
		try {
			UserProcess process = AuthTimeServiceManager.userRuntimeService();
			DepartmentProcess deptprocess = AuthTimeServiceManager.departmentRuntimeService();
			DomainProcess domainProcess = AuthTimeServiceManager.domainRuntimeService();
			CalendarProcess calendarProcess = (CalendarProcess) ProcessFactory.createProcess(CalendarProcess.class);

			ParamsTable params = getParams();
			String siteId = params.getParameterAsString("site_id");
			String domainId = params.getParameterAsString("domain_id");

			DomainVO domain = (DomainVO) domainProcess.doView(domainId);
//			Map<String,Object> sqlParameterMap = new HashMap<String,Object>();
//			String hql = "from " + CalendarVO.class.getName()
//					+ " vo where vo.name='Standard_Calendar' and vo.domainid = :domainid ";
//			sqlParameterMap.put("domainid", domain.getId());
			List<CalendarVO> calendars = (List<CalendarVO>) calendarProcess.doQueryByNameAndDomain("Standard_Calendar",domain.getId(),1, 1);
			CalendarVO calendar = calendars.isEmpty() ? null : calendars.get(0);

			FieldExtendsProcess fieldExtendsProcess = (FieldExtendsProcess) ProcessFactory
					.createProcess(FieldExtendsProcess.class);
			List<FieldExtendsVO> fieldExtendses = fieldExtendsProcess.queryFieldExtendsByTable(domain.getId(),
					FieldExtendsVO.TABLE_USER);
			List<FieldExtendsVO> fes = new ArrayList<FieldExtendsVO>();

			for (int i = 0; i < fieldExtendses.size(); i++) {
				FieldExtendsVO fevo = fieldExtendses.get(i);
				if (fevo != null && fevo.getEnabel()) {
					fes.add(fevo);
				}
			}

			String postDate = getPostDataAsString();

			if (!StringUtil.isBlank(postDate)) {
				JSONObject u = JSONObject.fromObject(postDate);
				String id = u.getString("id");
				UserVO user = new UserVO();
				user.setId(id);
				user.setName(u.getString("name"));
				user.setTelephone(u.getString("telephone"));
				user.setEmail(u.getString("email"));
				user.setAvatar(u.getString("avatar"));
				user.setLoginno(u.getString("loginno"));
				user.setLoginpwd(u.getString("loginpwd"));
				user.setDomainid(domainId);
				String deptId = u.getString("defaultDepartment");
				if (!StringUtil.isBlank(deptId)) {
					Collection<UserDepartmentRoleSet> depts = user.getUserDepartmentRoleSets();
					UserDepartmentRoleSet set = new UserDepartmentRoleSet(id, deptId,"");
					depts.add(set);
					user.setUserDepartmentRoleSets(depts);
					user.setDefaultDepartment(deptId);
				}

				// 璁剧疆鎷撳睍瀛楁
				if (u.containsKey("extattr")) {
					JSONObject extattr = u.getJSONObject("extattr");
					if (extattr != null) {
						if (!fes.isEmpty()) {
							JSONArray attrs = extattr.getJSONArray("attrs");
							for (Iterator<FieldExtendsVO> iterator3 = fes.iterator(); iterator3.hasNext();) {
								FieldExtendsVO fe = iterator3.next();
								String name = fe.getLabel();
								for (Iterator<JSONObject> iterator4 = attrs.iterator(); iterator4.hasNext();) {
									JSONObject attr = iterator4.next();
									if (name.equals(attr.getString("name"))) {
										String fieldName = fe.getName();
										fieldName = fieldName.replaceFirst("f", "F");
										Method method = UserVO.class.getMethod("set" + fieldName, String.class);
										method.invoke(user, attr.getString("value"));
										break;
									}
								}
							}
						}
					}
				}

				// 璁剧疆榛樿瑙掕壊
				RoleDesignTimeService roleService = AuthTimeServiceManager.roleRuntimeService();
				Collection<Application> apps = domain.getApplications();

				for (Iterator<Application> app_its = apps.iterator(); app_its.hasNext();) {
					Application app = app_its.next();
					if (app.isActivated()) {
						// 鑾峰彇杞欢涓嬬郴缁熼粯璁よ鑹�
						Collection<Role> roles = roleService.getDefaultRolesByApplication(app.getApplicationid());
						if (roles != null && roles.size() > 0) {
							for (Iterator<Role> it = roles.iterator(); it.hasNext();) {
								Role role = it.next();
								UserDepartmentRoleSet set = new UserDepartmentRoleSet(user.getId(),"", role.getId());
								user.getUserDepartmentRoleSets().add(set);
							}
						}
					}
				}

				user.setCalendarType(calendar != null ? calendar.getId() : null);
				process.doCreate(user);

			}
			return addActionResult(true, "", "success");
		} catch (Exception e) {
			e.printStackTrace();
			return addActionResult(false, e.getMessage(), null);
		}
	}

	/**
	 * 鑾峰彇榛樿濂椾欢搴旂敤鑿滃崟
	 * 
	 * @return
	 */
	@RequestMapping(value = "/getDefaultAppMenus.action")
	public Map<String, Object> getDefaultAppMenus() {
		try {
			String redirect_uri = null;
			ParamsTable params = getParams();
			String siteId = params.getParameterAsString("site_id");
			String domainId = params.getParameterAsString("domain_id");
			Map<String, JSONArray> agentMemus = new LinkedHashMap<String, JSONArray>();

			JSONArray txlMenu = new JSONArray();
			JSONObject txlItem1 = new JSONObject();
			txlItem1.put("name", "通讯录");
			txlItem1.put("type", "view");
			txlItem1.put("url",
					"https://open.weixin.qq.com/connect/oauth2/authorize?appid={appid}&redirect_uri={client_addr}/contacts/index.jsp?SET_COOKIE_SITEID={site_id}&response_type=code&scope=snsapi_base&state={domainId}#wechat_redirect");
			txlMenu.add(txlItem1);

			JSONObject txlItem2 = new JSONObject();
			txlItem2.put("name", "常用");
			txlItem2.put("type", "view");
			txlItem2.put("url",
					"https://open.weixin.qq.com/connect/oauth2/authorize?appid={appid}&redirect_uri={client_addr}/contacts/index.jsp?action=favoriteContacts&SET_COOKIE_SITEID={site_id}&response_type=code&scope=snsapi_base&state={domainId}#wechat_redirect");
			txlMenu.add(txlItem2);

			agentMemus.put("tj99c93073961f81501", txlMenu);

			JSONArray kqMenu = new JSONArray();
			JSONObject kqItem1 = new JSONObject();
			kqItem1.put("name", "签到");
			kqItem1.put("type", "view");
			kqItem1.put("url",
					"https://open.weixin.qq.com/connect/oauth2/authorize?appid={appid}&redirect_uri={client_addr}/attendance/sign.jsp?action=signin&SET_COOKIE_SITEID={site_id}&response_type=code&scope=snsapi_base&state={domainId}#wechat_redirect");
			kqMenu.add(kqItem1);

			JSONObject kqItem2 = new JSONObject();
			kqItem2.put("name", "签退");
			kqItem2.put("type", "view");
			kqItem2.put("url",
					"https://open.weixin.qq.com/connect/oauth2/authorize?appid={appid}&redirect_uri={client_addr}/attendance/sign.jsp?action=signout&SET_COOKIE_SITEID={site_id}&response_type=code&scope=snsapi_base&state={domainId}#wechat_redirect");
			kqMenu.add(kqItem2);

			JSONObject kqItem3 = new JSONObject();
			kqItem3.put("name", "考勤记录");
			kqItem3.put("type", "view");
			kqItem3.put("url",
					"https://open.weixin.qq.com/connect/oauth2/authorize?appid={appid}&redirect_uri={client_addr}/attendance/wap/record.jsp?SET_COOKIE_SITEID={site_id}&response_type=code&scope=snsapi_base&state={domainId}#wechat_redirect");
			kqMenu.add(kqItem3);

			// Map<String, String> kqMenu = new LinkedHashMap<String, String>();
			// kqMenu.put("绛惧埌",
			// "https://open.weixin.qq.com/connect/oauth2/authorize?appid={appid}&redirect_uri={client_addr}/attendance/sign.jsp?action=signin&SET_COOKIE_SITEID={site_id}&response_type=code&scope=snsapi_base&state={domainId}#wechat_redirect");
			// kqMenu.put("绛鹃��",
			// "https://open.weixin.qq.com/connect/oauth2/authorize?appid={appid}&redirect_uri={client_addr}/attendance/sign.jsp?action=signout&SET_COOKIE_SITEID={site_id}&response_type=code&scope=snsapi_base&state={domainId}#wechat_redirect");
			// kqMenu.put("鑰冨嫟璁板綍",
			// "https://open.weixin.qq.com/connect/oauth2/authorize?appid={appid}&redirect_uri={client_addr}/attendance/record.jsp?SET_COOKIE_SITEID={site_id}&response_type=code&scope=snsapi_base&state={domainId}#wechat_redirect");
			agentMemus.put("tj79858601a04b1a524", kqMenu);

			JSONArray pmMenu = new JSONArray();
			JSONObject pmItem1 = new JSONObject();
			pmItem1.put("name", "新建任务");
			pmItem1.put("type", "view");
			pmItem1.put("url",
					"https://open.weixin.qq.com/connect/oauth2/authorize?appid={appid}&redirect_uri={client_addr}/pm/wap/index.jsp?action=createTask&SET_COOKIE_SITEID={site_id}&response_type=code&scope=snsapi_base&state={domainId}#wechat_redirect");
			pmMenu.add(pmItem1);

			JSONObject pmItem2 = new JSONObject();
			pmItem2.put("name", "任务中心");
			pmItem2.put("type", "view");
			pmItem2.put("url",
					"https://open.weixin.qq.com/connect/oauth2/authorize?appid={appid}&redirect_uri={client_addr}/pm/wap/index.jsp?action=taskList&SET_COOKIE_SITEID={site_id}&response_type=code&scope=snsapi_base&state={domainId}#wechat_redirect");
			pmMenu.add(pmItem2);

			JSONObject pmItem3 = new JSONObject();
			pmItem3.put("name", "项目");
			pmItem3.put("type", "view");
			pmItem3.put("url",
					"https://open.weixin.qq.com/connect/oauth2/authorize?appid={appid}&redirect_uri={client_addr}/pm/wap/index.jsp?action=project&SET_COOKIE_SITEID={site_id}&response_type=code&scope=snsapi_base&state={domainId}#wechat_redirect");
			pmMenu.add(pmItem3);

			agentMemus.put("tj79858601a04b1a523", pmMenu);

			JSONArray erpMenu = new JSONArray();
			JSONObject erpItem1 = new JSONObject();
			erpItem1.put("name", "报表");
			erpItem1.put("type", "view");
			erpItem1.put("url",
					"https://open.weixin.qq.com/connect/oauth2/authorize?appid={appid}&redirect_uri={client_addr}/extendedReport/erpReport/index.jsp?SET_COOKIE_SITEID={site_id}&response_type=code&scope=snsapi_base&state={domainId}#wechat_redirect");
			erpMenu.add(erpItem1);

			JSONObject erpItem2 = new JSONObject();
			erpItem2.put("name", "数据查询");
			erpItem2.put("type", "view");
			erpItem2.put("url",
					"https://open.weixin.qq.com/connect/oauth2/authorize?appid={appid}&redirect_uri={client_addr}/extendedReport/erpSearch/searchDept.jsp?SET_COOKIE_SITEID={site_id}&response_type=code&scope=snsapi_base&state={domainId}#wechat_redirect");
			erpMenu.add(erpItem2);

			JSONObject erpItem3 = new JSONObject();
			erpItem3.put("name", "订单");

			JSONArray erpItem3_subMenus = new JSONArray();
			JSONObject erpItem3_subItem1 = new JSONObject();
			erpItem3_subItem1.put("name", "采购订单");
			erpItem3_subItem1.put("type", "view");
			erpItem3_subItem1.put("url",
					"https://open.weixin.qq.com/connect/oauth2/authorize?appid={appid}&redirect_uri={client_addr}/extendedReport/erpOrder/orderPurchase.jsp?SET_COOKIE_SITEID={site_id}&response_type=code&scope=snsapi_base&state={domainId}#wechat_redirect");
			erpItem3_subMenus.add(erpItem3_subItem1);
			JSONObject erpItem3_subItem2 = new JSONObject();
			erpItem3_subItem2.put("name", "销售订单");
			erpItem3_subItem2.put("type", "view");
			erpItem3_subItem2.put("url",
					"https://open.weixin.qq.com/connect/oauth2/authorize?appid={appid}&redirect_uri={client_addr}/extendedReport/erpOrder/orderSale.jsp?SET_COOKIE_SITEID={site_id}&response_type=code&scope=snsapi_base&state={domainId}#wechat_redirect");
			erpItem3_subMenus.add(erpItem3_subItem2);

			erpItem3.put("sub_button", erpItem3_subMenus);
			erpMenu.add(erpItem3);

			agentMemus.put("tj79858601a04b1a525", erpMenu);

			JSONArray oaMenu = new JSONArray();
			JSONObject oaItem1 = new JSONObject();
			oaItem1.put("name", "进入系统");
			oaItem1.put("type", "view");
			oaItem1.put("url",
					"https://open.weixin.qq.com/connect/oauth2/authorize?appid={appid}&redirect_uri={client_addr}/portal/index.html?application=11de-f053-df18d577-aeb6-19a7865cfdb6&SET_COOKIE_SITEID={site_id}&response_type=code&scope=snsapi_base&state={domainId}#wechat_redirect");
			oaMenu.add(oaItem1);

			agentMemus.put("tj79858601a04b1a521", oaMenu);

			JSONArray crmMenu = new JSONArray();
			JSONObject crmItem1 = new JSONObject();
			crmItem1.put("name", "进入系统");
			crmItem1.put("type", "view");
			crmItem1.put("url",
					"https://open.weixin.qq.com/connect/oauth2/authorize?appid={appid}&redirect_uri={client_addr}/portal/index.html?application=11e6-429d-dd7a3284-86a2-074015f7cc96&SET_COOKIE_SITEID={site_id}&response_type=code&scope=snsapi_base&state={domainId}#wechat_redirect");
			crmMenu.add(crmItem1);

			agentMemus.put("tj26a121bfc140b42d6", crmMenu);

			JSONArray xmglMenu = new JSONArray();
			JSONObject xmglItem1 = new JSONObject();
			// xmglItem1.put("name", "鏂板缓鏃ユ姤");
			xmglItem1.put("name", "进入系统");
			xmglItem1.put("type", "view");
			// redirect_uri =
			// URLEncoder.encode((weioa365_addr+"/portal/dynaform/document/newWithPermission.action?_formid=11e6-27bc-7bd880cf-a1cc-0ff3b6c87f18&_isJump=1&application=11e6-2d1c-908d1c9b-abde-35dbfa83876a&_resourceid=11e6-3119-2a152176-bd0b-3f8085c95eef&SET_COOKIE_SITEID={site_id}").replace("{site_id}",
			// Environment.getMACAddress()),"utf-8");
			xmglItem1.put("url",
					"https://open.weixin.qq.com/connect/oauth2/authorize?appid={appid}&redirect_uri={client_addr}/portal/index.html?application=11e6-2d1c-908d1c9b-abde-35dbfa83876a&SET_COOKIE_SITEID={site_id}&response_type=code&scope=snsapi_base&state={domainId}#wechat_redirect");
			// xmglItem1.put("url","https://open.weixin.qq.com/connect/oauth2/authorize?appid={appid}&redirect_uri="+redirect_uri+"&response_type=code&scope=snsapi_base&state={domainId}#wechat_redirect");
			xmglMenu.add(xmglItem1);

			agentMemus.put("tje841b64d2ee8024111", xmglMenu);

			JSONArray qmMenu = new JSONArray();
			JSONObject qmItem1 = new JSONObject();
			qmItem1.put("name", "待填写");
			qmItem1.put("type", "view");
			redirect_uri = URLEncoder.encode((weioa365_addr + "/qm/wap/pendlist.jsp?SET_COOKIE_SITEID={site_id}")
					.replace("{site_id}", Environment.getMACAddress()), "utf-8");
			qmItem1.put("url", "https://open.weixin.qq.com/connect/oauth2/authorize?appid={appid}&redirect_uri="
					+ redirect_uri + "&response_type=code&scope=snsapi_base&state={domainId}#wechat_redirect");
			qmMenu.add(qmItem1);

			JSONObject qmItem2 = new JSONObject();
			qmItem2.put("name", "问卷中心");
			qmItem2.put("type", "view");
			redirect_uri = URLEncoder.encode((weioa365_addr + "/qm/wap/center.jsp?SET_COOKIE_SITEID={site_id}")
					.replace("{site_id}", Environment.getMACAddress()), "utf-8");
			qmItem2.put("url", "https://open.weixin.qq.com/connect/oauth2/authorize?appid={appid}&redirect_uri="
					+ redirect_uri + "&response_type=code&scope=snsapi_base&state={domainId}#wechat_redirect");
			qmMenu.add(qmItem2);

			agentMemus.put("tje841b64d2ee8024112", qmMenu);

			JSONArray km = new JSONArray();
			JSONObject kmItem1 = new JSONObject();
			kmItem1.put("name", "进入系统");
			kmItem1.put("type", "view");
			kmItem1.put("url",
					"https://open.weixin.qq.com/connect/oauth2/authorize?appid={appid}&redirect_uri={client_addr}/km/wap/index.jsp?SET_COOKIE_SITEID={site_id}&response_type=code&scope=snsapi_base&state={domainId}#wechat_redirect");
			km.add(kmItem1);

			agentMemus.put("tje841b64d2ee8024113", km);

			return addActionResult(true, "", agentMemus);
		} catch (Exception e) {
			e.printStackTrace();
			return addActionResult(false, e.getMessage(), null);
		}
	}

	@RequestMapping(value = "/updateWeixinProxyType.action")
	public Map<String, Object> updateWeixinProxyType() {
		try {
			DomainProcess process = AuthTimeServiceManager.domainRuntimeService();
			ParamsTable params = getParams();
			String siteId = params.getParameterAsString("site_id");
			String domainId = params.getParameterAsString("domain_id");
			String weixinProxyType = params.getParameterAsString("weixinProxyType");

			DomainVO vo = (DomainVO) process.doView(domainId);
			if (vo != null) {
				vo.setWeixinProxyType(weixinProxyType);
				process.doUpdate(vo);
			}
			return addActionResult(true, "", "success");
		} catch (Exception e) {
			e.printStackTrace();
			return addActionResult(false, e.getMessage(), null);
		}
	}

	@RequestMapping(value = "/upload.action")
	public Map<String, Object> upload() {
		InputStream is = null;
		FileOutputStream os = null;
		try {
			ParamsTable params = getParams();
			String fileName = this.request.getSession().getServletContext()
					.getRealPath(params.getParameterAsString("fileName"));
			String base64File = getPostDataAsString();
			if (!StringUtils.isBlank(base64File)) {
//				byte[] data = new sun.misc.BASE64Decoder().decodeBuffer(base64File);
				byte[] data = Base64Util.decodeByte(base64File);
				os = new FileOutputStream(fileName);
				os.write(data);
				os.close();

				if (fileName.toLowerCase().endsWith(".amr")) {
					changeToMp3(fileName, fileName.replace(".amr", ".mp3"));
				}
			}
			return addActionResult(true, "", "success");
		} catch (Exception e) {
			e.printStackTrace();
			return addActionResult(false, e.getMessage(), null);
		}
	}

	/**
	 * 灏嗗井淇″ご鍍忓浘鐗囧帇缂�
	 * 
	 * @return
	 */
	@RequestMapping(value = "/imgCompress.action")
	public Map<String, Object> imgCompress() {
		try {
			ParamsTable params = getParams();
			String userId = params.getParameterAsString("userId");
			String imgUri = params.getParameterAsString("imgUri");
			if (!StringUtil.isBlank(userId)) {
				scaleImageWithParams(imgUri, userId, 100, 100, true, "jpg");
				return addActionResult(true, "", "success");
			} else {
				return addActionResult(false, "", null);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return addActionResult(false, e.getMessage(), null);
		}
	}

	/***
	 * 灏嗗浘鐗囩缉鏀惧埌鎸囧畾鐨勯珮搴︽垨鑰呭搴�
	 * 
	 * @param imgUri
	 *            鍥剧墖婧愬湴鍧�
	 * @param userId
	 *            鐢ㄦ埛id
	 * @param width
	 *            缂╂斁鍚庣殑瀹藉害
	 * @param height
	 *            缂╂斁鍚庣殑楂樺害
	 * @param auto
	 *            鏄惁鑷姩淇濇寔鍥剧墖鐨勫師楂樺姣斾緥
	 * @param format
	 *            鍥惧浘鐗囨牸寮� 渚嬪 jpg
	 */
	public static void scaleImageWithParams(String imgUri, String userId, int width, int height, boolean auto,
			String format) {

		try {
			URL url = new URL(imgUri);
			BufferedImage bufferedImage = ImageIO.read(url);
			if (auto) {
				ArrayList<Integer> paramsArrayList = getAutoWidthAndHeight(bufferedImage, width, height);
				width = paramsArrayList.get(0);
				height = paramsArrayList.get(1);
			}

			Image image = bufferedImage.getScaledInstance(width, height, Image.SCALE_DEFAULT);
			BufferedImage outputImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
			Graphics graphics = outputImage.getGraphics();
			graphics.drawImage(image, 0, 0, null);
			graphics.dispose();

			String contextPath = Environment.getInstance().getRealPath("\\uploads\\avatar\\");
			// 鍒涘缓瀛樺偍鏂囦欢澶�
			File file = new File(contextPath);
			if (!file.exists() && !file.isDirectory()) {
				file.mkdir();
			}
			String fileName = userId + "." + format;
			ImageIO.write(outputImage, format, new File(contextPath + fileName));
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * 灏哾ouble绫诲瀷鐨勬暟鎹浆鎹负int锛屽洓鑸嶄簲鍏ュ師鍒�
	 * 
	 * @param sourceDouble
	 * @return
	 */
	private static int parseDoubleToInt(double sourceDouble) {
		int result = 0;
		result = (int) sourceDouble;
		return result;
	}

	/***
	 * 
	 * @param bufferedImage
	 *            瑕佺缉鏀剧殑鍥剧墖瀵硅薄
	 * @param width_scale
	 *            瑕佺缉鏀惧埌鐨勫搴�
	 * @param height_scale
	 *            瑕佺缉鏀惧埌鐨勯珮搴�
	 * @return 涓�涓泦鍚堬紝绗竴涓厓绱犱负瀹藉害锛岀浜屼釜鍏冪礌涓洪珮搴�
	 */
	private static ArrayList<Integer> getAutoWidthAndHeight(BufferedImage bufferedImage, int width_scale,
			int height_scale) {
		ArrayList<Integer> arrayList = new ArrayList<Integer>();
		int width = bufferedImage.getWidth();
		int height = bufferedImage.getHeight();
		double scale_w = getDot2Decimal(width_scale, width);

		double scale_h = getDot2Decimal(height_scale, height);
		if (scale_w < scale_h) {
			arrayList.add(parseDoubleToInt(scale_w * width));
			arrayList.add(parseDoubleToInt(scale_w * height));
		} else {
			arrayList.add(parseDoubleToInt(scale_h * width));
			arrayList.add(parseDoubleToInt(scale_h * height));
		}
		return arrayList;

	}

	/***
	 * 杩斿洖涓や釜鏁癮/b鐨勫皬鏁扮偣鍚庝笁浣嶇殑琛ㄧず
	 * 
	 * @param a
	 * @param b
	 * @return
	 */
	public static double getDot2Decimal(int a, int b) {

		BigDecimal bigDecimal_1 = new BigDecimal(a);
		BigDecimal bigDecimal_2 = new BigDecimal(b);
		BigDecimal bigDecimal_result = bigDecimal_1.divide(bigDecimal_2, new MathContext(4));
		Double double1 = new Double(bigDecimal_result.toString());
		return double1;
	}

	/**
	 * 鎶奱mr鏍煎紡鐨勮闊宠浆鎹㈡垚MP3 @Title: changeToMp3 @Description:
	 * (鎶奱mr鏍煎紡鐨勮闊宠浆鎹㈡垚MP3) @author pll @param @param sourcePath
	 * amr鏍煎紡鏂囦欢璺緞 @param @param targetPath 瀛樻斁mp3鏍煎紡鏂囦欢璺緞 @return void 杩斿洖绫诲瀷 @throws
	 */
	private void changeToMp3(String sourcePath, String targetPath) {
		File source = new File(sourcePath);
		File target = new File(targetPath);
		AudioAttributes audio = new AudioAttributes();
		Encoder encoder = new Encoder();

		audio.setCodec("libmp3lame");
		EncodingAttributes attrs = new EncodingAttributes();
		attrs.setFormat("mp3");
		attrs.setAudioAttributes(audio);
		try {
			encoder.encode(source, target, attrs);
		} catch (IllegalArgumentException e) {
		} catch (InputFormatException e) {
		} catch (EncoderException e) {
		}
	}

	private Map<String, Object> department2Map(DepartmentVO dept) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("id", dept.getId());
		map.put("name", dept.getName());
		map.put("superior", dept.getSuperior() != null ? dept.getSuperior().getId() : "");
		map.put("level", dept.getLevel());
		map.put("weixinDeptId", StringUtil.isBlank(dept.getWeixinDeptId()) ? "" : dept.getWeixinDeptId());
		map.put("valid", dept.getValid());
		return map;
	}

	private Map<String, Object> user2Map(UserVO u) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("id", u.getId());
		map.put("name", u.getName());
		map.put("loginno", u.getLoginno());
		map.put("telephone", StringUtil.isBlank(u.getTelephone()) ? "" : u.getTelephone());
		map.put("email", StringUtil.isBlank(u.getEmail()) ? "" : u.getEmail());
		map.put("defaultDepartment", StringUtil.isBlank(u.getDefaultDepartment()) ? "" : u.getDefaultDepartment());
		map.put("superior", u.getSuperior() != null ? u.getSuperior().getId() : "");
		map.put("avatar", StringUtil.isBlank(u.getAvatar()) ? "" : u.getAvatar());
		map.put("level", u.getLevel());
		map.put("status", u.getStatus());

		// 閮ㄩ棬瀛楁
		JSONArray departments = new JSONArray();
		Collection<DepartmentVO> _departments = u.getDepartments();
		if (!_departments.isEmpty()) {
			for (DepartmentVO dept : _departments) {
				if (!StringUtil.isBlank(dept.getWeixinDeptId())) {
					departments.add(dept.getId());
				}
			}
		}
		map.put("departments", departments.toString());

		// 鎷撳睍瀛楁
		FieldExtendsProcess fieldExtendsProcess = (FieldExtendsProcess) ProcessFactory
				.createProcess(FieldExtendsProcess.class);
		List<FieldExtendsVO> fieldExtendses = fieldExtendsProcess.queryFieldExtendsByTable(u.getDomain().getId(),
				FieldExtendsVO.TABLE_USER);
		List<FieldExtendsVO> fes = new ArrayList<FieldExtendsVO>();
		for (int i = 0; i < fieldExtendses.size(); i++) {
			FieldExtendsVO fevo = fieldExtendses.get(i);
			if (fevo != null && fevo.getEnabel()) {
				fes.add(fevo);
			}
		}
		// 娣诲姞鎷撳睍瀛楁鍊�
		JSONObject extattr = new JSONObject();
		if (!fes.isEmpty()) {
			JSONArray attrs = new JSONArray();
			JSONObject attr;
			for (Iterator<FieldExtendsVO> _iter = fes.iterator(); _iter.hasNext();) {
				FieldExtendsVO fe = _iter.next();
				String label = fe.getLabel();
				String fieldName = fe.getName();
				String _fieldName = fieldName.replaceFirst("f", "F");
				Method method = UserVO.class.getMethod("get" + _fieldName, null);
				Object value = method.invoke(u, null);
				if (value != null) {
					attr = new JSONObject();
					attr.put("name", label);
					attr.put("value", value.toString());
					attrs.add(attr);
				} else {
					attr = new JSONObject();
					attr.put("name", label);
					attr.put("value", "");
					attrs.add(attr);
				}
			}
			extattr.put("attrs", attrs);
			if (extattr != null && extattr.getJSONArray("attrs").size() > 0) { // 鏍￠獙鏄惁鐪熺殑瀛樺湪鎷撳睍瀛楁
				map.put("extattr", extattr.toString());
			}
		}

		return map;
	}

	private String getPostDataAsString() {
		StringBuffer info = new java.lang.StringBuffer();
		try {
			HttpServletRequest request = this.request;
			InputStream in = request.getInputStream();
			BufferedInputStream buf = new BufferedInputStream(in);
			byte[] buffer = new byte[1024];
			int iRead;
			while ((iRead = buf.read(buffer)) != -1) {
				info.append(new String(buffer, 0, iRead, "UTF-8"));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return info.toString();
	}

	/**
	 * 鑾峰彇浼佷笟鍩熶笅鐨勬墍鏈夌敤鎴烽泦鍚�
	 * 
	 * @return
	 */
	public Map<String, Object> getUsers() {
		try {
			Collection<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
			ParamsTable params = getParams();
			String siteId = params.getParameterAsString("site_id");
			String domainId = params.getParameterAsString("domain_id");

			UserProcess userPorcess = AuthTimeServiceManager.userRuntimeService();
			Collection<UserVO> user = userPorcess.queryByDomain(domainId);
			
			for (Iterator<UserVO> iterator = user.iterator(); iterator.hasNext();) {
				UserVO u = iterator.next();
				if (u.getStatus()==1) {
					Map<String, Object> map = new HashMap<String, Object>();
					map.put("id", u.getId());
					map.put("name", u.getName());
					map.put("superior", u.getSuperior().getId());
					map.put("level", u.getLevel());
					list.add(map);					
				}
			}

			return addActionResult(true, "", list);
		} catch (Exception e) {
			e.printStackTrace();
			return addActionResult(false, e.getMessage(), null);
		}
	}

	public ParamsTable getParams() {
		// if (params == null) {

		ParamsTable params = ParamsTable.convertHTTP(this.request);

		params.setSessionid(this.request.getSession().getId());

		if (params.getParameter("_pagelines") == null) {
			params.setParameter("_pagelines", Web.DEFAULT_LINES_PER_PAGE);
		}
		// }

		return params;
	}

	public ParamsTable getParams(HttpServletRequest request) {
		// if (params == null) {
		params = ParamsTable.convertHTTP(request);

		params.setSessionid(request.getSession().getId());

		if (params.getParameter("_pagelines") == null) {
			params.setParameter("_pagelines", Web.DEFAULT_LINES_PER_PAGE);
		}
		// }
		return params;
	}

	/**
	 * Struts2搴忓垪鍖栨寚瀹氬睘鎬ф椂锛屽繀椤绘湁璇ュ睘鎬х殑getter鏂规硶
	 * 
	 * @return
	 */
	public Map<String, Object> getDataMap() {
		return dataMap;
	}

	/**
	 * 娣诲姞Action澶勭悊缁撴灉
	 * 
	 * @param isSuccess
	 *            鏄惁鎴愬姛澶勭悊
	 * @param message
	 *            杩斿洖娑堟伅
	 * @param data
	 *            杩斿洖鏁版嵁
	 */
	public Map<String, Object> addActionResult(boolean isSuccess, String message, Object data) {
		dataMap.put(ACTION_RESULT_KEY, isSuccess ? ACTION_RESULT_VALUE_SUCCESS : ACTION_RESULT_VALUE_FAULT);
		dataMap.put(ACTION_MESSAGE_KEY, message);
		if (data != null) {
			dataMap.put(ACTION_DATA_KEY, data);
		}
		return dataMap;
	}

}
