package com.uas.account.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.uas.account.AccountConfig;
import com.uas.account.ResultWrap;
import com.uas.account.entity.*;
import com.uas.account.support.Page;
import com.uas.sso.SSOHelper;
import com.uas.sso.SSOToken;
import com.uas.sso.common.util.HttpUtil;
import com.uas.sso.common.util.HttpUtil.ResponseWrap;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * 客户端使用，操作企业资料、用户资料
 *
 * @author yingp
 *
 */
public class AccountUtils {

	/**
	 * 修改用户信息
	 *
	 * @param user
	 * @param userDetail
	 * @return
	 * @throws Exception
	 */
	public static List<User> saveUser(User user, UserDetail userDetail) throws Exception {
		String saveUrl = AccountConfig.getUserSaveUrl();
		if (!StringUtils.isEmpty(saveUrl)) {
			JSONObject formData = new JSONObject();
			if (userDetail != null) {
				formData = JSON.parseObject(JSON.toJSONString(userDetail));
			}
			if (user != null) {
				if (user.getUid() == null) {
					user.setUid(userDetail.getMobile());
				}
				if (user.getSecondUID() == null) {
					user.setSecondUID(userDetail.getEmail());
				}
				if (user.getAppId() != null && user.getDialectUID() != null) {
					if (user.getAppId().equals("b2b") || user.getAppId().equals("mall")) {
						user.setSalt(user.getDialectUID());
					}
				}
				formData.putAll(JSON.parseObject(JSON.toJSONString(user)));
			}
			ResponseWrap res = HttpUtil.doPost(saveUrl, formData);
			if (!res.isSuccess())
				throw new Exception(res.getContent());
			else {
				ResultWrap result = JSON.parseObject(res.getContent(), ResultWrap.class);
				if (result.isError()) {
					throw new Exception(result.getErrMsg());
				} else {
					return JSON.parseArray(JSON.toJSONString(result.getContent()), User.class);
				}
			}
		}
		return null;
	}

	/**
	 * 修改用户信息
	 *
	 * @param dialectUID
	 *            个人唯一标识
	 * @param spaceDialectUID
	 *            企业唯一标识
	 * @param userDetail
	 *            个人详细信息
	 * @return
	 * @throws Exception
	 */
	public static List<User> saveUser(Object dialectUID, Object spaceDialectUID, UserDetail userDetail) throws Exception {
		User user = new User();
		user.setAppId(SSOHelper.getSSOService().getConfig().getAppName());
		user.setDialectUID(dialectUID.toString());
		if (spaceDialectUID != null) {
			user.setSpaceDialectUID(spaceDialectUID.toString());
		}
		return saveUser(user, userDetail);
	}

	/**
	 * 保存与当前应用无关的用户信息，借用appId=sso
	 *
	 * @param uid
	 * @param spaceUID
	 * @param userDetail
	 * @return
	 * @throws Exception
	 */
	public static List<User> saveCustUser(Object uid, Object spaceUID, UserDetail userDetail) throws Exception {
		User user = new User();
		user.setAppId(AccountConfig.ACCOUNT_CENTER);
		user.setDialectUID(uid.toString());
		user.setSpaceUID(spaceUID.toString());
		return saveUser(user, userDetail);
	}

	/**
	 * 添加用户信息
	 *
	 * @param dialectUID
	 *            个人唯一标识
	 * @param spaceDialectUID
	 *            企业唯一标识
	 * @param userDetail
	 *            个人详细信息
	 * @param noEncryPwd
	 *            明文密码
	 * @return
	 * @throws Exception
	 */
	public static List<User> addUser(Object dialectUID, Object spaceDialectUID, UserDetail userDetail, String noEncryPwd) throws Exception {
		User user = new User();
		user.setAppId(SSOHelper.getSSOService().getConfig().getAppName());
		user.setDialectUID(dialectUID.toString());
		if (spaceDialectUID != null) {
			user.setSpaceDialectUID(spaceDialectUID.toString());
		}
		user.setPassword(noEncryPwd);
		return saveUser(user, userDetail);
	}

	public static List<UserSpace> saveUserSpace(UserSpace space, UserSpaceDetail spaceDetail) throws Exception {
		String saveUrl = AccountConfig.getSpaceSaveUrl();
		if (!StringUtils.isEmpty(saveUrl)) {
			JSONObject formData = new JSONObject();
			if (spaceDetail != null) {
				formData = JSON.parseObject(JSON.toJSONString(spaceDetail));
			}
			if (space != null) {
				if (space.getUid() == null) {
					space.setUid(spaceDetail.getBusinessCode());
				}
				formData.putAll(JSON.parseObject(JSON.toJSONString(space)));
			}
			ResponseWrap res = HttpUtil.doPost(saveUrl, formData);
			if (!res.isSuccess())
				throw new Exception(res.getContent());
			else {
				ResultWrap result = JSON.parseObject(res.getContent(), ResultWrap.class);
				if (result.isError()) {
					throw new Exception(result.getErrMsg());
				} else {
					return JSON.parseArray(JSON.toJSONString(result.getContent()), UserSpace.class);
				}
			}
		}
		return null;
	}

	public static List<UserSpace> saveUserSpace(Object dialectUID, UserSpaceDetail spaceDetail) throws Exception {
		UserSpace userSpace = new UserSpace();
		userSpace.setAppId(SSOHelper.getSSOService().getConfig().getAppName());
		userSpace.setDialectUID(dialectUID.toString());
		return saveUserSpace(userSpace, spaceDetail);
	}

	/**
	 * 解除绑定的应用
	 * 
	 * @param userSpace
	 * @throws Exception
	 */
	public static void unbindUserSpace(UserSpace userSpace) throws Exception {
		String saveUrl = AccountConfig.getSpaceSaveUrl();
		if (!StringUtils.isEmpty(saveUrl)) {
			JSONObject formData = JSON.parseObject(JSON.toJSONString(userSpace));
			formData.put("_operate", "unbind");
			ResponseWrap res = HttpUtil.doPost(saveUrl, formData);
			if (!res.isSuccess())
				throw new Exception(res.getContent());
		}
	}

	/**
	 * 解除绑定的应用
	 * 
	 * @param uid
	 * @throws Exception
	 */
	public static void unbindUserSpace(String uid) throws Exception {
		unbindUserSpace(SSOHelper.getSSOService().getConfig().getAppName(), uid);
	}

	/**
	 * 解除绑定的应用
	 * 
	 * @param appId
     * @param uid
	 * @throws Exception
	 */
	public static void unbindUserSpace(String appId, String uid) throws Exception {
		UserSpace userSpace = new UserSpace();
		userSpace.setAppId(appId);
		userSpace.setUid(uid);
		unbindUserSpace(userSpace);
	}

	/**
	 * 解除绑定的云账号
	 *
	 * @param user
	 * @throws Exception
	 */
	public static void unbindUser(User user) throws Exception {
		String saveUrl = AccountConfig.getUserSaveUrl();
		if (!StringUtils.isEmpty(saveUrl)) {
			JSONObject formData = JSON.parseObject(JSON.toJSONString(user));
			formData.put("_operate", "unbind");
			ResponseWrap res = HttpUtil.doPost(saveUrl, formData);
			if (!res.isSuccess())
				throw new Exception(res.getContent());
		}
	}

	/**
	 * 解除绑定的云账号
	 *
	 * @param dialectUID
     * @param spaceDialectUID
	 * @throws Exception
	 */
	public static void unbindUser(Object dialectUID, Object spaceDialectUID) throws Exception {
		User user = new User();
		user.setAppId(SSOHelper.getSSOService().getConfig().getAppName());
		user.setDialectUID(dialectUID.toString());
		if (spaceDialectUID != null) {
			user.setSpaceDialectUID(spaceDialectUID.toString());
		}
		unbindUser(user);
	}

	/**
	 * 校验密码
	 *
	 * @param user
	 * @throws Exception
	 */
	public static boolean checkPassword(User user) throws Exception {
		String saveUrl = AccountConfig.getUserSaveUrl();
		if (!StringUtils.isEmpty(saveUrl)) {
			JSONObject formData = JSON.parseObject(JSON.toJSONString(user));
			formData.put("_operate", "check");
			ResponseWrap res = HttpUtil.doGet(saveUrl, formData);
			if (!res.isSuccess())
				throw new Exception(res.getContent());
			else {
				ResultWrap result = JSON.parseObject(res.getContent(), ResultWrap.class);
				if (!result.isSuccess())
					throw new Exception(result.getErrMsg());
				else
					return true;
			}
		}
		return false;
	}

	/**
	 * 校验密码
	 *
	 * @param dialectUID
	 * @param spaceDialectUID
	 * @param password
	 * @throws Exception
	 */
	public static boolean checkPassword(Object dialectUID, Object spaceDialectUID, String password) throws Exception {
		User user = new User();
		user.setAppId(SSOHelper.getSSOService().getConfig().getAppName());
		user.setDialectUID(dialectUID.toString());
		if (spaceDialectUID != null) {
			user.setSpaceDialectUID(spaceDialectUID.toString());
		}
		user.setPassword(password);
		return checkPassword(user);
	}

	/**
	 * 校验密码
	 *
	 * <pre>
	 * 全匹配模式
	 * </pre>
	 *
	 * @param user
	 * @throws Exception
	 */
	public static boolean fuzzyCheckPassword(User user) throws Exception {
		String saveUrl = AccountConfig.getUserSaveUrl();
		if (!StringUtils.isEmpty(saveUrl)) {
			JSONObject formData = JSON.parseObject(JSON.toJSONString(user));
			formData.put("_operate", "fuzzyCheck");
			ResponseWrap res = HttpUtil.doGet(saveUrl, formData);
			if (!res.isSuccess())
				throw new Exception(res.getContent());
			else {
				ResultWrap result = JSON.parseObject(res.getContent(), ResultWrap.class);
				if (!result.isSuccess())
					throw new Exception(result.getErrMsg());
				else
					return true;
			}
		}
		return false;
	}

	/**
	 * 校验密码
	 *
	 * <pre>
	 * 全匹配模式
	 * </pre>
	 *
	 * @param dialectUID
	 * @param spaceDialectUID
	 * @param password
	 * @throws Exception
	 */
	public static boolean fuzzyCheckPassword(Object dialectUID, Object spaceDialectUID, String password) throws Exception {
		User user = new User();
		user.setAppId(SSOHelper.getSSOService().getConfig().getAppName());
		user.setDialectUID(dialectUID.toString());
		if (spaceDialectUID != null) {
			user.setSpaceDialectUID(spaceDialectUID.toString());
		}
		user.setPassword(password);
		return fuzzyCheckPassword(user);
	}

	/**
	 * 重置密码
	 *
	 * @param user
	 * @throws Exception
	 */
	public static void resetPassword(User user) throws Exception {
		String saveUrl = AccountConfig.getUserSaveUrl();
		saveUrl = saveUrl + "/resetPwd";
		if (!StringUtils.isEmpty(saveUrl)) {
			JSONObject formData = JSON.parseObject(JSON.toJSONString(user));
			//formData.put("_operate", "reset");
			ResponseWrap res = HttpUtil.doGet(saveUrl, formData);
			if (!res.isSuccess())
				throw new Exception(res.getContent());
			else {
				ResultWrap result = JSON.parseObject(res.getContent(), ResultWrap.class);
				if (!result.isSuccess())
					throw new Exception(result.getErrMsg());
			}
		}
	}

	/**
	 * 重置密码
	 *
	 * @param dialectUID
	 *            应用自己的用户唯一标识
	 * @param spaceDialectUID
	 *            企业唯一标识
	 * @param noEncryPwd
	 *            新密码（明文）
	 * @throws Exception
	 */
	public static void resetPassword(Object dialectUID, Object spaceDialectUID, String noEncryPwd) throws Exception {
		User user = new User();
		user.setAppId(SSOHelper.getSSOService().getConfig().getAppName());
		user.setDialectUID(dialectUID.toString());
		if (spaceDialectUID != null) {
			user.setSpaceDialectUID(spaceDialectUID.toString());
		}
		user.setPassword(noEncryPwd);
		resetPassword(user);
	}

	/**
	 * 重置密码
	 *
	 * @param mobile
	 *            手机号
	 * @param noEncryPwd
	 *            新密码（明文）
	 * @throws Exception
	 */
	public static void resetPassword(String mobile, String noEncryPwd) throws Exception {
		User user = new User();
		user.setAppId(SSOHelper.getSSOService().getConfig().getAppName());
		user.setUid(mobile);
		user.setPassword(noEncryPwd);
		resetPassword(user);
	}

	/**
	 * 获取校验码
	 *
	 * @param username
	 *            手机号或邮箱地址
	 * @return
	 */
	public static void sendValidCode(String username) throws Exception {
		String saveUrl = AccountConfig.getUserSaveUrl();
		if (!StringUtils.isEmpty(saveUrl)) {
			ResponseWrap res = HttpUtil.doGet(saveUrl, new ModelMap("_operate", "getVcode").addAttribute("username", username));
			if (!res.isSuccess())
				throw new Exception(res.getContent());
			else {
				ResultWrap result = JSON.parseObject(res.getContent(), ResultWrap.class);
				if (!result.isSuccess())
					throw new Exception(result.getErrMsg());
			}
		}
	}

	/**
	 * 验证校验码
	 *
	 * @param username
	 *            手机号或邮箱地址
	 * @param validCode
	 *            校验码
	 * @return
	 */
	public static boolean checkValidCode(String username, String validCode) throws Exception {
		String saveUrl = AccountConfig.getUserSaveUrl();
		if (!StringUtils.isEmpty(saveUrl)) {
			ResponseWrap res = HttpUtil.doGet(saveUrl, new ModelMap("_operate", "checkVcode").addAttribute("username", username)
					.addAttribute("validCode", validCode));
			if (!res.isSuccess())
				throw new Exception(res.getContent());
			else {
				ResultWrap result = JSON.parseObject(res.getContent(), ResultWrap.class);
				if (!result.isSuccess())
					throw new Exception(result.getErrMsg());
				else
					return true;
			}
		}
		return false;
	}

	/**
	 * 验证密码，返回绑定身份信息的token
	 *
	 * @return
	 */
	public static String getAccessToken(User user) throws Exception {
		String saveUrl = AccountConfig.getUserSaveUrl();
		if (!StringUtils.isEmpty(saveUrl)) {
			JSONObject formData = JSON.parseObject(JSON.toJSONString(user));
			formData.put("_operate", "getToken");
			ResponseWrap res = HttpUtil.doGet(saveUrl, formData);
			if (!res.isSuccess())
				throw new Exception(res.getContent());
			else {
				ResultWrap result = JSON.parseObject(res.getContent(), ResultWrap.class);
				if (!result.isSuccess())
					throw new Exception(result.getErrMsg());
				else
					return String.valueOf(result.getContent());
			}
		}
		return null;
	}

	/**
	 * 验证token，返回当前应用相关的身份信息
	 *
	 * @return
	 */
	public static UserView checkAccessToken(String token) throws Exception {
		String saveUrl = AccountConfig.getUserSaveUrl();
		if (!StringUtils.isEmpty(saveUrl)) {
			ResponseWrap res = HttpUtil.doGet(
					saveUrl,
					new ModelMap("_operate", "checkToken").addAttribute("token", token).addAttribute("appId",
							SSOHelper.getSSOService().getConfig().getAppName()));
			if (!res.isSuccess())
				throw new Exception(res.getContent());
			else {
				ResultWrap result = JSON.parseObject(res.getContent(), ResultWrap.class);
				if (!result.isSuccess())
					throw new Exception(result.getErrMsg());
				else
					return JSON.parseObject(JSON.toJSONString(result.getContent()), UserView.class);
			}
		}
		return null;
	}

	/**
	 * 用token验证登录
	 *
	 * @param request
	 * @param response
	 * @param token
	 * @throws Exception
	 */
	public static UserView loginByAccessToken(HttpServletRequest request, HttpServletResponse response, String token) throws Exception {
		UserView user = checkAccessToken(token);
		if (null != user) {
			SSOToken st = new SSOToken(request, user.getUid());
			st.setData(JSON.toJSONString(user));
			SSOHelper.setSSOCookie(request, response, st, true);
		}
		return user;
	}

	/**
	 * 传入当前登录的企业的营业执照号，查询发出的申请
	 *
	 * @param businessCode
	 * @param statusCode
	 * @param keyword
	 * @param pageNumber
	 * @param pageSize
	 * @return
	 * @throws Exception
	 */
	public static Page<PartnershipRecord> getAllRequest(String businessCode, Integer statusCode, String keyword, int pageNumber,
														int pageSize) throws Exception {
		String getUrl = AccountConfig.getEnPartnersUrl();
		if (!StringUtils.isEmpty(getUrl)) {
			ResponseWrap res = HttpUtil.doGet(getUrl, new ModelMap("_operate", "getAllRequest").addAttribute("businessCode", businessCode)
					.addAttribute("statusCode", statusCode).addAttribute("businessCode", businessCode).addAttribute("keyword", keyword)
					.addAttribute("pageNumber", pageNumber).addAttribute("pageSize", pageSize));
			if (!res.isSuccess())
				throw new Exception(res.getContent());
			return JSONObject.parseObject(res.getContent(), new TypeReference<Page<PartnershipRecord>>() {
			});
		}
		return null;
	}

	/**
	 * 通过已存在uu过滤，取出全部合作伙伴（UAS接口用）
	 * @param businessCode
	 * @param statusCode
	 * @param keyword
	 * @param pageNumber
	 * @param pageSize
	 * @param partnerUUs
	 * @return
	 */
	public static Page<PartnershipRecord> getRequestFilterByPartnerUUs(String businessCode, Integer statusCode, String keyword, List<Long> partnerUUs, int pageNumber, int pageSize) throws Exception {
		String getUrl = AccountConfig.getEnPartnersUrl();
		if (!StringUtils.isEmpty(getUrl)) {
			ResponseWrap res = HttpUtil.doGet(getUrl, new ModelMap("_operate", "getAllRequestFilterByPartnerUUs").addAttribute("businessCode", businessCode)
					.addAttribute("statusCode", statusCode).addAttribute("keyword", keyword).addAttribute("partnerUUs", JSON.toJSON(partnerUUs))
					.addAttribute("pageNumber", pageNumber).addAttribute("pageSize", pageSize));
			if (!res.isSuccess())
				throw new Exception(res.getContent());
			return JSON.parseObject(res.getContent(), new TypeReference<Page<PartnershipRecord>>() {
			});
		}
		return null;
	}

	/**
	 * 进入企业圈
	 *
	 * @return
	 * @throws Exception
	 */
	public static String redirectContactPage() throws Exception {
		String enterUrl = AccountConfig.getContactPageUrl();
		return enterUrl;
	}

	/**
	 * 通过关键词搜索企业信息
	 *
	 * @param keyword
	 * @return
	 * @throws Exception
	 */
	public static Page<UserSpaceDetail> getUserSpacesByKeyword(String keyword, int pageNumber, int pageSize) throws Exception {
		String Url = AccountConfig.getEnPartnersUrl();
		if (!StringUtils.isEmpty(Url)) {
			ResponseWrap res = HttpUtil.doGet(Url,
					new ModelMap("_operate", "getUserSpaces").addAttribute("keyword", keyword).addAttribute("pageNumber", pageNumber)
							.addAttribute("pageSize", pageSize));
			if (!res.isSuccess())
				throw new Exception(res.getContent());
			return JSON.parseObject(res.getContent(), new TypeReference<Page<UserSpaceDetail>>() {
			});
		}
		return null;
	}

	/**
	 * 通过手机号搜索用户账号信息
	 *
	 * @param uid
	 * @return
	 * @throws Exception
	 */
	public static List<User> getUserInfoByUid(String uid) throws Exception {
		String Url = AccountConfig.getSpaceSaveUrl();
		if (!StringUtils.isEmpty(Url)) {
			ResponseWrap res = HttpUtil.doGet(Url + "/userInfo",
					new ModelMap("uid", uid));
			if (!res.isSuccess())
				throw new Exception(res.getContent());
			String resText = res.getContent();
			JSONObject object = JSON.parseObject(resText);
			String contentText = object.getString("content");
			return JSON.parseArray(contentText, User.class);
		}
		return null;
	}

	/**
	 * 通过营业执照号获取企业应用
	 *
	 * @param uid
	 * @return
	 * @throws Exception
	 */
	public static List<UserSpace> getUserSpaceByUid(String uid) throws Exception {
		String Url = AccountConfig.getSpaceSaveUrl();
		if (!StringUtils.isEmpty(Url)) {
			ResponseWrap res = HttpUtil.doGet(Url + "/" + uid);
			if (!res.isSuccess())
				throw new Exception(res.getContent());
			String resText = res.getContent();
			JSONObject object = JSON.parseObject(resText);
			String contentText = object.getString("content");
			return JSON.parseArray(contentText, UserSpace.class);
		}
		return null;
	}

	/**
	 * 新增一条合作关系记录
	 *
	 * @param record
	 * @return
	 * @throws Exception
	 */
	public static String addNewRecord(PartnershipRecord record) throws Exception {
		String url = AccountConfig.getEnPartnersUrl();
		String result = null;
		if (!StringUtils.isEmpty(url)) {
			JSONObject formData = JSON.parseObject(JSON.toJSONString(record));
			formData.put("_operate", "addPartner");
			ResponseWrap res = HttpUtil.doPost(url, formData);
			result = res.getContent();
		}
		return result;
	}

	/**
	 * 同步供应商关系为合作关系记录
	 *
	 * @param record
	 * @return
	 * @throws Exception
	 */
	public static String synchronizeRecord(PartnershipRecord record) throws Exception {
		String url = AccountConfig.getEnPartnersUrl();
		String result = null;
		if (!StringUtils.isEmpty(url)) {
			JSONObject formData = JSON.parseObject(JSON.toJSONString(record));
			formData.put("_operate", "synchronizePartner");
			ResponseWrap res = HttpUtil.doPost(url, formData);
			result = res.getContent();
		}
		return result;
	}

	/**
	 * 通过id和申请人的电话进行确认
	 *
	 * @param id
	 * @param vendUserTel
     * @param appId
	 * @return
	 * @throws Exception
	 */
	public static String acceptRequest(Long id, String vendUserTel, String appId) throws Exception {
		String url = AccountConfig.getEnPartnersUrl();
		String result = null;
		if (!StringUtils.isEmpty(url)) {
			ResponseWrap res = HttpUtil.doGet(
					url,
					new ModelMap("_operate", "acceptRequest").addAttribute("id", id).addAttribute("vendUserTel", vendUserTel)
							.addAttribute("appId", appId));
			if (!res.isSuccess())
				throw new Exception(res.getContent());
			else {
				result = res.getContent();
			}
		}
		return result;
	}

	/**
	 * 申请不通过，通过申请人的电话操作，并标出原因
	 *
	 * @param id
	 * @param reason
	 * @param vendUserTel
     * @param appId
	 * @return
	 * @throws Exception
	 */
	public static String rejectRequest(Long id, String reason, String vendUserTel, String appId) throws Exception {
		String url = AccountConfig.getEnPartnersUrl();
		String result = null;
		if (!StringUtils.isEmpty(url)) {
			ResponseWrap res = HttpUtil.doGet(
					url,
					new ModelMap("_operate", "rejectRequest").addAttribute("id", id).addAttribute("reason", reason)
							.addAttribute("vendUserTel", vendUserTel).addAttribute("appId", appId));
			if (!res.isSuccess())
				throw new Exception(res.getContent());
			else {
				result = res.getContent();
			}
		}
		return result;
	}

	/**
	 * 通过当前企业号和企业列表中的企业号查询申请状态
	 *
	 * @return
	 * @throws Exception
	 */
	public static RequsetStatus getStatusByCustUidAndVendUid(String custUid, String vendUid) throws Exception {
		String url = AccountConfig.getEnPartnersUrl();
		RequsetStatus request = new RequsetStatus();
		if (!StringUtils.isEmpty(url)) {
			ResponseWrap res = HttpUtil.doGet(url, new ModelMap("_operate", "getRequestStatus").addAttribute("custUid", custUid)
					.addAttribute("vendUid", vendUid));
			if (!res.isSuccess())
				throw new Exception(res.getContent());
			else {
				request = JSON.parseObject(res.getContent(), RequsetStatus.class);
			}
		}
		return request;
	}

	/**
	 * 搜索词通过id返回数据
	 * 
	 * @param ids
	 * @return
	 * @throws Exception
	 */
	public static List<UserSpaceDetail> findAll(String ids) throws Exception {
		String url = AccountConfig.getEnPartnersUrl();
		List<UserSpaceDetail> details = new ArrayList<UserSpaceDetail>();
		if (!StringUtils.isEmpty(url)) {
			ResponseWrap res = HttpUtil.doGet(url, new ModelMap("_operate", "findAll").addAttribute("ids", ids));
			if(!res.isSuccess())
				throw new Exception(res.getContent());
			else 
				details = JSONObject.parseArray(res.getContent(), UserSpaceDetail.class);
		}
		return details;
	}

	/**
	 * 通过企业营业执照查询收到的待处理的请求
	 * 
	 * @param businessCode
	 * @return
	 * @throws Exception
	 */
	public static String getRequestTodo(String businessCode) throws Exception {
		String url = AccountConfig.getEnPartnersUrl();
		String result = null;
		if (!StringUtils.isEmpty(url)) {
			ResponseWrap res = HttpUtil.doGet(url,
					new ModelMap("_operate", "getRequestTodo").addAttribute("businessCode", businessCode));
			if (!res.isSuccess())
				throw new Exception(res.getContent());
			else
				result = res.getContent();
		}
		return result;
	}

	/**
	 * 其他应用发起邀请注册，同步数据
	 * 
	 * @param jsonStr
	 * @throws Exception
	 */
	public static void synchroInvitation(String jsonStr) throws Exception {
		String url = AccountConfig.getEnPartnersUrl();
		if (!StringUtils.isEmpty(url)) {
			HttpUtil.doPost(url, new ModelMap("_operate", "invitation").addAttribute("jsonStr", jsonStr));
		}
	}

	/**
	 * ERP、SAAS新开账套名称校验
	 * 
	 * @param name
	 * @return
	 * @throws Exception
	 */
	public static String validName(String name) throws Exception {
		String result = null;
		String url = AccountConfig.getSpaceSaveUrl();
		if (!StringUtils.isEmpty(url)) {
			ResponseWrap res = HttpUtil.doGet(url, new ModelMap("_operate", "validName").addAttribute("name", name),
					50);
			if (!res.isSuccess())
				throw new Exception(res.getContent());
			else
				result = res.getContent();
		}
		return result;
	}

	/**
	 * ERP、SAAS新开账套名称校验
	 * 
	 * @param businessCode
	 * @return
	 * @throws Exception
	 */
	public static String validBusinessCode(String businessCode) throws Exception {
		String result = null;
		String url = AccountConfig.getSpaceSaveUrl();
		if (!StringUtils.isEmpty(url)) {
			ResponseWrap res = HttpUtil.doGet(url,
					new ModelMap("_operate", "validBusinessCode").addAttribute("businessCode", businessCode), 50);
			if (!res.isSuccess())
				throw new Exception(res.getContent());
			else
				result = res.getContent();
		}
		return result;
	}

	/**
	 * 通过营业执照号查找 企业详细信息
	 *
	 * @param
	 * @return
	 * @throws Exception
	 */
	public static UserSpaceDetail findByBusinessCode(String businessCode) throws Exception {
		String result = null;
		String url = AccountConfig.getSpaceSaveUrl();
		if (!StringUtils.isEmpty(url)) {
			ResponseWrap res = HttpUtil.doGet(url,
					new ModelMap("_operate", "findByBusinessCode").addAttribute("businessCode", businessCode), 50);
			if (!res.isSuccess())
				throw new Exception(res.getContent());
			else
				result = res.getContent();
		}
		return JSON.parseObject(result,UserSpaceDetail.class);
	}

	/**
	 * ERP、SAAS新开账套
	 * 
	 * @param userSpaceDetail
	 * @param users
	 * @throws Exception
	 */
	public static String applyApp(UserSpaceDetail userSpaceDetail, List<UserDetail> users) throws Exception {
		String url = AccountConfig.getSpaceSaveUrl();
		String result = null;
		if (!StringUtils.isEmpty(url)) {
			ResponseWrap res = HttpUtil.doPost(url, new ModelMap("_operate", "registerBranchAccount")
							.addAttribute("detail", JSON.toJSON(userSpaceDetail))
							.addAttribute("userInfos", JSON.toJSON(users)));
			if (!res.isSuccess())
				throw new Exception(res.getContent());
			else 
				result = res.getContent();
		}
		return result;
	}

	/**
	 * 商城个人账号增加企业注册
	 * 
	 * @param userSpaceDetail
	 * @throws Exception
	 */
	public static String applyAppForMall(UserSpaceDetail userSpaceDetail) throws Exception {
		String url = AccountConfig.getSpaceSaveUrl();
		String result = null;
		if (!StringUtils.isEmpty(url)) {
			ResponseWrap res = HttpUtil.doPost(url,
					new ModelMap("_operate", "registForMall")
					.addAttribute("detail", JSON.toJSON(userSpaceDetail)));
			if (!res.isSuccess())
				throw new Exception(res.getContent());
			else
				result = res.getContent();
		}
		return result;
	}

	/**
	 * 设置hr账号
	 * 
	 * @param user
	 * @param detail
	 * @return
	 * @throws Exception
	 */
	public static String setHrAccount(User user, UuzcUserSpaceDetail detail) throws Exception {
		String saveUrl = AccountConfig.getUserSaveUrl();
		saveUrl = saveUrl + "/setHrAccount";
		if (!StringUtils.isEmpty(saveUrl)) {
			JSONObject formData = new JSONObject();
			if (detail != null) {
				formData = JSON.parseObject(JSON.toJSONString(detail));
			}
			if (null != user) {
				formData.putAll(JSON.parseObject(JSON.toJSONString(user)));
			}
			ResponseWrap response = HttpUtil.doPost(saveUrl, formData);
			if (!response.isSuccess())
				throw new Exception(response.getContent());
			else {
				return response.getContent();
			}
		}
		return null;
	}

    /**
     * 根据营业执照获取众创需要的企业资料
     *
     * @param businessCode
     * @return
     * @throws Exception
     */
    public static UuzcUserSpaceDetail getUuzcUserSpaceDetail(String businessCode) throws Exception {
        String saveUrl = AccountConfig.getUserSaveUrl();
        if (!StringUtils.isEmpty(saveUrl)) {
            ResponseWrap response = HttpUtil.doGet(saveUrl  + "/uuzcSpace" , new ModelMap("businessCode", businessCode));
            if (!response.isSuccess())
                throw new Exception(response.getContent());
            else {
                return JSONObject.parseObject(response.getContent(), UuzcUserSpaceDetail.class);
            }
        }
        return null;
    }

	/**
	 * 判断当前企业是否设置了hr
	 * 
	 * @param businessCode
	 * @return
	 * @throws Exception
	 */
	public static String getHrAccount(String businessCode) throws Exception {
		String saveUrl = AccountConfig.getUserSaveUrl();
		if (!StringUtils.isEmpty(saveUrl)) {
			ResponseWrap response = HttpUtil.doGet(saveUrl  + "/hrcount" , new ModelMap("businessCode", businessCode));
			if (!response.isSuccess())
				throw new Exception(response.getContent());
			else {
				return response.getContent();
			}
		}
		return null;
	}

    /**
     * 获取当前企业的HR信息
     *
     * @param businessCode
     * @return
     * @throws Exception
     */
    public static User getHrInfo(String businessCode) throws Exception {
        String saveUrl = AccountConfig.getUserSaveUrl();
        if (!StringUtils.isEmpty(saveUrl)) {
            ResponseWrap response = HttpUtil.doGet(saveUrl + "/hrInfo" , new ModelMap("businessCode", businessCode));
            if (!response.isSuccess())
                throw new Exception(response.getContent());
            else {
                return JSONObject.parseObject(response.getContent(), User.class);
            }
        }
        return null;
    }

	/**
	 * 获取当前企业人员账号信息
	 * 
	 * @param businessCode
	 * @return
	 * @throws Exception
	 */
	public static List<User> getEmployees(String businessCode) throws Exception {
		String saveUrl = AccountConfig.getUserSaveUrl();
		saveUrl = saveUrl + "/employees";
		if (!StringUtils.isEmpty(saveUrl)) {
			ResponseWrap response = HttpUtil.doPost(saveUrl, new ModelMap("businessCode", businessCode));
			if (!response.isSuccess())
				throw new Exception(response.getContent());
			else {
				return JSON.parseArray(response.getContent(), User.class);
			}
		}
		return null;
	}

	/**
	 * 保存用户密保问题
	 * @param questions
	 * @throws Exception
	 */
	public static void saveUserQuestions(List<UserQuestion> questions) throws Exception {
		String saveUrl = AccountConfig.getUserSaveUrl();
		saveUrl = saveUrl + "/save/question";
		if (!StringUtils.isEmpty(saveUrl)) {
			ResponseWrap res = HttpUtil.doPost(saveUrl, new ModelMap("question", questions));
			if (!res.isSuccess()) {
				throw new Exception(res.getContent());
			}
		}
	}

	/**
	 * 保存用户密保问题
	 * @param userQuestion
	 * @throws Exception
	 */
	public static void saveUserQuestion(UserQuestion userQuestion) throws Exception {
		String saveUrl = AccountConfig.getUserSaveUrl();
		saveUrl = saveUrl + "/save/question";
		if (!StringUtils.isEmpty(saveUrl)) {
			JSONObject formData = JSON.parseObject(JSON.toJSONString(userQuestion));
			formData.put("_count", "one");
			ResponseWrap res = HttpUtil.doPost(saveUrl, formData);
			if (!res.isSuccess()) {
				throw new Exception(res.getContent());
			}
		}
	}

	/**
	 * 根据imId获取用户userUU（没有则返回null）
	 */
	public static Long getUserUUByImId (Long imId) throws Exception {
		String url = AccountConfig.getUserSaveUrl();
		Long result = null;
		if (!StringUtils.isEmpty(url)) {
			ResponseWrap res = HttpUtil.doPost(url,
					new ModelMap("_operate", "getUserUUByImId")
							.addAttribute("imId", imId));
			if (!res.isSuccess())
				throw new Exception(res.getContent());
			else
				result = Long.valueOf(res.getContent());
		}
		return result;
	}
}
