package com.uas.account.controller;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.sun.org.apache.xml.internal.security.utils.Constants;
import com.uas.account.entity.*;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.uas.account.AccountConfig;
import com.uas.account.core.Const;
import com.uas.account.core.Page;
import com.uas.account.core.util.StringUtil;
import com.uas.account.exception.AccountException;
import com.uas.account.exception.VisibleError;
import com.uas.account.service.AppService;
import com.uas.account.service.SettingService;
import com.uas.account.service.SysDataToMallService;
import com.uas.account.service.TokenService;
import com.uas.account.service.UserQuestionService;
import com.uas.account.service.UserService;
import com.uas.account.service.UserSpaceService;
import com.uas.account.support.SystemSession;
import com.uas.account.web.BaseController;
import com.uas.message.mail.service.MailService;
import com.uas.message.sms.service.SmsService;
import com.uas.sso.SSOHelper;
import com.uas.sso.SSOToken;
import com.uas.sso.common.encrypt.MD5;

@Controller
@RequestMapping("/api/user")
public class UserManagerController extends BaseController {

	@Autowired
	private UserService userService;
	@Autowired
	private AppService appService;
	@Autowired
	private UserSpaceService userSpaceService;
	@Autowired
	private TokenService tokenService;
	@Autowired
	private MailService mailService;
	@Autowired
	private SmsService smsService;
	@Autowired
	private SettingService settingService;
	@Autowired
	private SysDataToMallService sysService;
	@Autowired
	private UserQuestionService userQuestionService;

	private static final String UTF_8 = "UTF-8";

	private static final String ERROR = "error";

	/**
	 * 按应用和所属企业查找用户
	 *
	 * @param appId
	 * @param spaceId
	 * @return
	 */
	@RequestMapping(value = "/list", method = RequestMethod.GET)
	@ResponseBody
	public Page<User> findAll(String appId, String spaceId, int pageNumber, int pageSize) {
		return userService.findAll(appId, spaceId, pageNumber, pageSize);
	}

	/**
	 * 用户开通应用统计
	 *
	 * @return
	 */
	@RequestMapping(value = "/count", method = RequestMethod.GET)
	@ResponseBody
	public ModelMap count() {
		return success(userService.getUserAppCount());
	}

	/**
	 * 查找用户详细信息
	 *
	 * @param mobile
	 * @param email
	 * @return
	 */
	@RequestMapping(value = "/detail", method = RequestMethod.GET)
	@ResponseBody
	public ModelMap findDetail(String mobile, String email) {
		if (!StringUtils.isEmpty(mobile)) {
			return success(userService.findOne(mobile));
		}
		List<UserDetail> details = userService.findByEmail(email);
		return success(CollectionUtils.isEmpty(details) ? null : details.get(0));
	}

	/**
	 * 查找用户详细信息
	 *
	 * @param pageNumber
	 * @param pageSize
	 * @return
	 */
	@RequestMapping(value = "/detail/list", method = RequestMethod.GET)
	@ResponseBody
	public Page<UserDetail> findAllEnabledDetail(String name, String mobile, int pageNumber, int pageSize) {
		return userService.findAllDetail(name, mobile, pageNumber, pageSize);
	}

	/**
	 * 查找用户
	 *
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "/info", method = RequestMethod.GET)
	@ResponseBody
	public ModelMap findOne(User user) {
		return success(userService.findOne(user.getAppId(), user.getSpaceUID(), user.getUid()));
	}

	/**
	 * 查找用户所使用的全部应用和所属企业信息
	 *
	 * @param detail
	 * @return
	 */
	@RequestMapping(value = "/all", method = RequestMethod.GET)
	@ResponseBody
	public ModelMap findUsers(UserDetail detail) {
		if (!StringUtils.isEmpty(detail.getMobile()))
			return success(userService.findViewByUID(detail.getMobile()));
		else if (!StringUtils.isEmpty(detail.getEmail())) {
			return success(userService.findViewBySecondUID(detail.getEmail()));
		}
		return error("个人信息不完善");
	}

	/**
	 * 查找用户的所有帐号信息（ac$users）
	 *
	 * @param uid
	 * @return
	 */
	@RequestMapping(value = "/userInfo", method = RequestMethod.GET)
	@ResponseBody
	public ModelMap findUserInfo(String uid) {
		if (!StringUtils.isEmpty(uid)) {
			return success(userService.findUserAppByUID(uid));
		}
		return error("个人信息不完善");
	}

	/**
	 * 开通应用
	 *
	 * @return
	 */
	@RequestMapping("/applyApp")
	@ResponseBody
	public ModelMap applyApp(User user) {
		userService.applyApp(user);
		return success();
	}

	/**
	 * 用户信息新增、修改
	 *
	 * @param user
	 * @param userDetail
	 * @return
	 */
	@RequestMapping(method = RequestMethod.POST)
	@ResponseBody
	public ModelMap apiSave(User user, UserDetail userDetail) {
		if (user == null || user.getAppId() == null)
			throw new AccountException("参数错误");
		return success(userService.saveAllInfo(user, userDetail));
	}

	/**
	 * 控制台帮助用户重置密码
	 *
	 * @return
	 */
	@RequestMapping("resetPwd")
	@ResponseBody
	public ModelMap consoleResetPassword(User user) {
		if (user == null || user.getPassword() == null) {
			return error("参数错误");
		}
		user.setAppId(AccountConfig.ACCOUNT_CENTER);
		userService.syncUserPassword(user, user.getPassword());
		sysService.changepwd(user, user.getPassword());
		return success();
	}

	/**
	 * 用户绑定信息查询
	 *
	 * @param user
	 * @return
	 */
	@RequestMapping(method = RequestMethod.GET)
	@ResponseBody
	public ModelMap apiGet(User user) {
		if (user == null)
			throw new AccountException("参数错误");
		return success(userService.findOne(user));
	}

	/**
	 * 用户全部绑定信息查询
	 *
	 * @param user
	 * @return
	 */
	@RequestMapping(params = "_operate=all", method = RequestMethod.GET)
	@ResponseBody
	public ModelMap apiGetAll(User user) {
		if (user == null)
			throw new AccountException("参数错误");
		if (!StringUtils.isEmpty(user.getUid()))
			return success(userService.findByUID(user.getUid()));
		else if (!StringUtils.isEmpty(user.getSecondUID()))
			return success(userService.findBySecondUID(user.getSecondUID()));
		return error("未找到用户");
	}

	/**
	 * 解除用户与企业绑定关系
	 *
	 * @param user
	 * @return
	 */
	@RequestMapping(params = "_operate=unbind", method = RequestMethod.POST)
	@ResponseBody
	public ModelMap apiUnbind(User user) {
		if (user == null || user.getAppId() == null)
			throw new AccountException("参数错误");
		userService.delete(user);
		return success();
	}

	/**
	 * 接口调用验证密码登录
	 *
	 * @return
	 */
	@RequestMapping(params = "_operate=check")
	@ResponseBody
	public ModelMap apiLogin(User user) {
		if (null == user || null == user.getAppId() || null == user.getPassword()) {
			return error("参数错误");
		}
		User oldOne = userService.findOne(user);
		App app = appService.findOne(user.getAppId());
		if (app != null) {
			app = StringUtils.isEmpty(app.getUserControl()) ? app : appService.findOne(app.getUserControl());
		}
		if (null != oldOne.getId()) {
			// 允许应用在调用该接口前，已经将用户输入的明文加密为密文
			String encryPwd = user.getPassword().length() >= 32 ? user.getPassword() : userService.getEncryPassword(app.getEncryFormat(),
					user.getPassword(), user.getSalt());
			if (encryPwd.equals(oldOne.getPassword())) {
				return success();
			}
			return error("密码错误");
		}
		return error("未找到用户");
	}

	/**
	 * 接口调用验证密码登录
	 *
	 * <pre>
	 * 这个比较特殊，指定应用可能密码为空，需要借用其他应用的密码来校验
	 * </pre>
	 *
	 * @return
	 */
	@RequestMapping(params = "_operate=fuzzyCheck")
	@ResponseBody
	public ModelMap apiFuzzyLogin(User user) {
		if (null == user || null == user.getPassword()) {
			return error("参数错误");
		}
		if (!StringUtils.isEmpty(user.getUid())) {
			List<User> users = userService.findByUID(user.getUid());
			if (users != null && users.size() == 0) {
				return error("未找到用户");
			}
			for (User one : users) {
				App app = appService.findOne(one.getAppId());
				if (app != null) {
					app = StringUtils.isEmpty(app.getUserControl()) ? app : appService.findOne(app.getUserControl());
				}
				if (null != one.getId()) {
					// 允许应用在调用该接口前，已经将用户输入的明文加密为密文
					String encryPwd = user.getPassword().length() >= 32 ? user.getPassword() : userService.getEncryPassword(
							app.getEncryFormat(), user.getPassword(), one.getSalt());
					if (encryPwd.equals(one.getPassword())) {
						if (!StringUtils.isEmpty(user.getAppId()) && !one.getAppId().equals(user.getAppId())) {
							// 通过其他应用校验通过的，修改当前应用下绑定的密码
							App userApp = appService.findOne(user.getAppId());
							userService.changePassword(userApp, user, user.getPassword());
						}
						return success();
					}
				}
			}
			return error("密码错误");
		}
		return error("请填写手机号");
	}

	/**
	 * 验证密码，返回绑定身份信息的token
	 *
	 * @return
	 */
	@RequestMapping(params = "_operate=getToken")
	@ResponseBody
	public ModelMap apiGetToken(User user) {
		ModelMap map = apiLogin(user);
		if (isSuccess(map)) {
			Token token = new Token(user);
			tokenService.save(token);
			return success(token.getId());
		}
		return map;
	}

	/**
	 * 验证密码，返回绑定身份信息的token
	 *
	 * @return
	 */
	@RequestMapping(params = "_operate=getAccessToken")
	@ResponseBody
	public ModelMap apiGetAccessToken(User user, Integer expires_in) {
		ModelMap map = apiLogin(user);
		if (isSuccess(map)) {
			Token token = new Token(user, expires_in);
			tokenService.save(token);
			return success(token.getId());
		}
		return map;
	}

	/**
	 * 验证token，返回其他身份信息
	 *
	 * @return
	 */
	@RequestMapping(params = "_operate=checkToken")
	@ResponseBody
	public ModelMap apiCheckAccessToken(String token, String appId) {
		Token tk = tokenService.findOne(token);
		if (null != tk) {
			try {
				User user = JSON.parseObject(JSON.toJSONString(tk.getBind()), User.class);
				User currUser = null;
				App app = appService.findOne(null == appId ? user.getAppId() : appId);
				if (app != null) {
					app = StringUtils.isEmpty(app.getUserControl()) ? app : appService.findOne(app.getUserControl());
				}

				if (null != user.getSpaceUID()) {
					UserSpace space = userSpaceService.findOne(app.getUid(), user.getSpaceUID());
					if (null != space) {
						currUser = userService.findOneView(app.getUid(), space.getId(), user.getUid());
					}
				}

				if (null == currUser) {
					currUser = new UserView();
					currUser.setAppId(app.getUid());
					currUser.setSecondUID(user.getSecondUID());
					currUser.setSpaceUID(user.getSpaceUID());
					currUser.setUid(user.getUid());
					currUser = userService.findOne(currUser);
				}

				if (null != currUser.getId()) {
					return success(currUser);
				}
				return error("未找到用户");
			} finally {
				tokenService.delete(token);
			}
		}
		return error("验证信息已过期");
	}

	/**
	 * ERP到账户中心的验证
	 *
	 * @param appId
	 * @param access_token
	 * @param redirect_page
	 * @return
	 */
	@RequestMapping("/webpage")
	public ModelAndView redirectPage(String appId, String access_token, String redirect_page) {
		ModelMap data = apiCheckAccessToken(access_token, appId);
		if (isSuccess(data)) {
			User user = (User) getContent(data);
			if (user != null) {
				SystemSession.setUser(user);
			}
			SSOToken st = new SSOToken(request, user.getUid());
			st.setData(JSON.toJSONString(user));
			SSOHelper.setSSOCookie(request, response, st, true);
			return new ModelAndView("redirect:/" + redirect_page);
		} else {
			return new ModelAndView("common/error", data);
		}
	}

	/**
	 * 接口调用修改密码
	 *
	 * @return
	 */
	@RequestMapping(params = "_operate=modify")
	@ResponseBody
	public ModelMap apiChangePassword(User user, String newPassword) {
		if (null == user || null == user.getAppId() || null == user.getPassword() || null == newPassword) {
			return error("参数错误");
		}

		User oldOne = userService.findOne(user);
		App app = appService.findOne(user.getAppId());
		if (app != null) {
			app = StringUtils.isEmpty(app.getUserControl()) ? app : appService.findOne(app.getUserControl());
		}
		if (null != oldOne.getId()) {
			String encryPwd = user.getPassword().length() >= 32 ? user.getPassword() : userService.getEncryPassword(app.getEncryFormat(),
					user.getPassword(), user.getSalt());
			if (encryPwd.equals(oldOne.getPassword())) {
				userService.changePassword(app, oldOne, newPassword);
				sysService.changepwd(user, newPassword);
				return success();
			}
			return error("密码错误");
		}
		return error("未找到用户");
	}

	/**
	 * 接口调用重置密码
	 *
	 * @return
	 */
	@RequestMapping(params = "_operate=reset")
	@ResponseBody
	public ModelMap apiResetPassword(User user) {
		if (user == null || user.getAppId() == null || user.getPassword() == null) {
			return error("参数错误");
		}
		App app = appService.findOne(user.getAppId());
		if (app != null) {
			app = StringUtils.isEmpty(app.getUserControl()) ? app : appService.findOne(app.getUserControl());
		}
		user.setAppId(app.getUid());
		User oldOne = userService.findOne(user);
		if (oldOne.getId() != null) {
			userService.changePassword(app, oldOne, user.getPassword());
			sysService.changepwd(user, user.getPassword());
		} else if (!StringUtils.isEmpty(user.getUid())) {
			UserDetail userDetail = new UserDetail();
			userDetail.setMobile(user.getUid());
			userDetail.setEmail(user.getSecondUID());
			userDetail.setName(user.getName());
			userService.save(user, userDetail);
			sysService.changepwd(user, user.getPassword());
		}
		return success();
	}

	/**
	 * 接口调用获取验证码
	 *
	 * @param username
	 * @return
	 */
	@RequestMapping(params = "_operate=getVcode")
	@ResponseBody
	public ModelMap apiGetValidCode(@RequestParam(required = true) String username) {
		return getValidCode(username);
	}

	/**
	 * 接口调用校验验证码
	 *
	 * @param username
	 * @param validCode
	 * @return
	 */
	@RequestMapping(params = "_operate=checkVcode")
	@ResponseBody
	public ModelMap apiCheckValidCode(@RequestParam(required = true) String username, @RequestParam(required = true) String validCode) {
		String tokenId = "resetPwd:" + username;
		Token token = tokenService.findOne(tokenId);
		if (null == token) {
			return error("验证码已过期，请重新获取");
		}
		if (!token.getBind().equals(MD5.toMD5(validCode))) {
			return error("验证码错误");
		}
		tokenService.delete(tokenId);
		return success();
	}

	/**
	 * 用户操作获取验证码
	 * 
	 * @param username
	 * @return
	 */
	@RequestMapping(value = "/vcode", params = "source=resetPwd", method = RequestMethod.GET)
	@ResponseBody
	public ModelMap getValidCode(@RequestParam String username) {
		// 用户修改密码检测是否完成第一步
		request.getSession().setAttribute("firstStep", false);

		username = StringUtils.trimAllWhitespace(username);
		String tokenId = "resetPwd:" + username;
		Token oldOne = tokenService.findOne(tokenId);
		if (null != oldOne) {
			if (System.currentTimeMillis() - oldOne.getTime().getTime() < 60000) {
				return error("403", "请不要频繁获取验证码");
			} else {
				// 这种情况可能短信发送后没及时收到
				tokenService.delete(tokenId);
			}
		}
		final String validCode = StringUtil.getRandomNumber(6);
		Token token = new Token(tokenId, MD5.toMD5(validCode), 600);
		tokenService.save(token);
		UserDetail detail = null;
		boolean isMobile = true;
		if (username.matches(Const.REGEXP_EMAIL)) {
			List<UserDetail> details = userService.findByEmail(username);
			if (CollectionUtils.isEmpty(details)) {
				return error("邮箱未注册");
			}
			if (details.size() > 1) {
				// 一个邮箱绑定了多次的账号信息
				return error("您的邮箱未激活，请使用手机号认证");
			}
			detail = details.get(0);
			request.getSession().setAttribute("detail", detail);
			isMobile = false;
		} else if (username.matches(Const.REGEXP_MOBILE)) {
			detail = userService.findOne(username);
			if (null == detail) {
				return error("手机号未注册");
			}
			request.getSession().setAttribute("detail", detail);
		} else {
			return error("手机号或邮箱地址不正确");
		}
		request.getSession().setAttribute("firstStep", true);

		// 发送验证码
		if (isMobile) {
			// 短信
			Setting smsTpl = settingService.findOne("templateForSendSmsAboutValidCode");
			if (smsTpl != null) {
				smsService.send(smsTpl.getValue(), username, new Object[] { validCode });
			} else {
				return error("系统错误");
			}
		} else {
			// 邮件
			Setting mailTpl = settingService.findOne("templateForSendMailAboutValidCode");
			if (mailTpl != null) {
				mailService.send(mailTpl.getValue(), username, new ModelMap("validCode", validCode).addAttribute("name", detail.getName()));
			} else {
				return error("系统错误");
			}
		}
		return success();
	}

	/**
	 * 用户操作校验验证码
	 *
	 * @param username
	 * @param validCode
	 * @return
	 */
	@RequestMapping(value = "/vcode", params = "source=resetPwd", method = RequestMethod.POST)
	@ResponseBody
	public ModelMap checkValidCode(@RequestParam(required = true) String username, @RequestParam(required = true) String validCode) {
		String tokenId = "resetPwd:" + username;
		Token token = tokenService.findOne(tokenId);
		if (null == token) {
			return error("验证码已过期，请重新获取");
		}
		if (!token.getBind().equals(MD5.toMD5(validCode))) {
			return error("验证码错误");
		}
		return success();
	}

	/**
	 * 用户操作校验验证码
	 *
	 * @param username
	 * @param validCode
	 * @return
	 */
	@RequestMapping(value = "/vcode", params = "source=submitValidCheck", method = RequestMethod.POST)
	@ResponseBody
	public ModelMap toAssistCheck(@RequestParam(required = true) String username, @RequestParam(required = true) String validCode) {
		String tokenId = "resetPwd:" + username;
		Token token = tokenService.findOne(tokenId);
		if (null == token) {
			return error("验证码已过期，请重新获取");
		}
		if (!token.getBind().equals(MD5.toMD5(validCode))) {
			return error("验证码错误");
		}
		tokenService.delete(tokenId);
		Token pageToken = new Token(username, 86400);
		tokenService.save(pageToken);
		return success(pageToken.getId());
	}

	/**
	 * 用户操作重置密码
	 *
	 * @param pageToken
	 * @param password
	 * @return
	 */
	@RequestMapping(value = "/resetPwd", method = RequestMethod.POST)
	@ResponseBody
	public ModelMap userResetPwd(@RequestParam(required = true) String pageToken, @RequestParam(required = true) String password) {
		Token token = tokenService.findOne(pageToken);
		if (null == token) {
			return error("请刷新后重试");
		}
		String username = StringUtils.trimAllWhitespace(token.getBind().toString());
		User user = null;
		try {
			Short level = checkPasswordLevel(password);
			if (level == 1) {
				return error("密码强度过低，请重新设置密码");
			}
		} catch (Exception e) {
			return error(e.getMessage());
		}
		if (username.matches(Const.REGEXP_EMAIL)) {
			List<User> users = userService.findBySecondUID(username);
			if (!CollectionUtils.isEmpty(users)) {
				user = users.get(0);
			} else {
				return error("邮箱地址错误");
			}
		} else if (username.matches(Const.REGEXP_MOBILE)) {
			List<User> users = userService.findByUID(username);
			if (!CollectionUtils.isEmpty(users)) {
				user = users.get(0);
			} else {
				return error("手机号错误");
			}
		} else {
			return error("请使用手机号或邮箱地址验证");
		}
		try {
			boolean isPassCheck = (boolean) request.getSession().getAttribute("firstStep") &&
					(boolean) request.getSession().getAttribute("answer1") && (boolean) request.getSession().getAttribute("answer2");
			if (!isPassCheck) {
				return error("请刷新后重试");
			}
		} catch (NullPointerException e) {
			return error("请刷新后重试");
		}

		App app = appService.findOne(user.getAppId());
		userService.changePassword(app, user, password);
		user.setAppId(AccountConfig.ACCOUNT_CENTER);
		syncUserPassword(user, password);
		sysService.changepwd(user, password);
		tokenService.delete(pageToken);
		return success();
	}

	/**
	 * 新开一个线程处理
	 *
	 * @param user
	 * @param password
	 */
	private void syncUserPassword(final User user, final String password) {
		new Thread(new Runnable() {
			@Override
			public void run() {
				userService.syncUserPassword(user, password);
			}
		}).start();
	}

	/**
	 * 控制台重置用户邮箱地址
	 *
	 * @param uid
	 * @param secondUID
	 * @return
	 */
	public ModelMap consoleResetEmail(@RequestParam(required = true) String uid, @RequestParam(required = true) String secondUID) {
		if (!secondUID.matches(Const.REGEXP_EMAIL)) {
			return error("邮箱地址格式错误");
		}
		userService.changeSecondUID(uid, secondUID);
		return success();
	}

	/**
	 * 企业信息库总数
	 */
	@RequestMapping(value = "/enterprise/count", method = RequestMethod.GET)
	@ResponseBody
	public Integer getEnterpriseCount() {
		return userService.getEnterpriseCount();
	}

	/**
	 * 优软云个人用户注册总数
	 */
	@RequestMapping(value = "/personalUser/count", method = RequestMethod.GET)
	@ResponseBody
	public Integer getPersonalUserCount() {
		return userService.getPersonalUserCount();
	}

	/**
	 * UU互联用户数
	 */
	@RequestMapping(value = "/uuUser/count", method = RequestMethod.GET)
	@ResponseBody
	public Integer getUuUserCount() {
		return userService.getUuUserCount();
	}

	/**
	 * 优软众创人员注册信息同步
	 *
	 * @param userDetail
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(value = "/sysUserdata/uuzc", method = RequestMethod.POST)
	@ResponseBody
	public UuzcUserDeatil sysUserdata(UuzcUserDeatil userDetail) throws UnsupportedEncodingException {
		List<User> users = userService.findByUID(userDetail.getMobile());
		String password = userDetail.getPassword();
		// 转明码
		String pwd = new String(Base64.decodeBase64(password.getBytes(UTF_8)), UTF_8);
		userDetail.setPassword(pwd);
		// 先判断账号是否已存在
		if (!CollectionUtils.isEmpty(users)) {
			User user = users.get(0);
			return user.covert();
		} else {
			UserDetail detail = userDetail.covert();
			detail = userService.save(detail);
			return userService.initUserForUUzc(detail, userDetail.getPassword());
		}
	}

	/**
	 * 优软众创登录通知账户中心
	 *
	 * @param userDetail
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(value = "/login/fromuuzc", method = RequestMethod.POST)
	@ResponseBody
	public ModelMap login(UuzcUserDeatil userDetail) throws UnsupportedEncodingException {
		String password = userDetail.getPassword();
		String pwd = new String(Base64.decodeBase64(password.getBytes(UTF_8)), UTF_8);
		User user = userDetail.covertUser();
		user.setPassword(pwd);
		if (null == user || null == user.getAppId() || null == user.getPassword()) {
			return error("参数错误");
		}
		User oldOne = userService.findByAppId(user);
		App app = appService.findOne("b2b");
		if (app != null) {
			app = StringUtils.isEmpty(app.getUserControl()) ? app : appService.findOne(app.getUserControl());
		}
		if (null != oldOne.getId()) {
			// // 允许应用在调用该接口前，已经将用户输入的明文加密为密文
			// String encryPwd = user.getPassword().length() >= 32 ?
			// user.getPassword()
			// : userService.getEncryPassword(app.getEncryFormat(),
			// user.getPassword(), user.getSalt());
			// if (encryPwd.equals(oldOne.getPassword())) {
			// return success("登录成功");
			// }
			// return error("密码错误");
			List<UserView> userView = getUserByUserName(app, oldOne.getUid());
			if (userView.size() > 0) {
				return loginByUser(app, userView.get(0), pwd, user.getDialectUID());
			}
		}
		return error("未找到用户");
	}

	private List<UserView> getUserByUserName(App app, String username) {
		if (username.contains("@")) {
			return userService.findByAppAndSecondUID(app.getUid(), username);
		} else if (username.matches(Const.REGEXP_MOBILE)) {
			return userService.findByAppAndUID(app.getUid(), username);
		} else {
			if (Const.NO == app.getDialectEnable()) {
				throw new VisibleError("请使用手机号或邮箱地址登录" + app.getDescription());
			}
			return userService.findByAppAndDialectUID(app.getUid(), username);
		}
	}

	private ModelMap loginByUser(App app, UserView user, String pass, String dialectuid) {
		if (user == null) {
			return error("您输入的账号或密码有误");
		} else {
			/*
			 * 设置登录 Cookie 最后一个参数 true 时添加 cookie 同时销毁当前 JSESSIONID 创建信任的
			 * JSESSIONID
			 */
			SSOToken st = new SSOToken(request, user.getUid());
			st.setData(JSON.toJSONString(user));
			SSOHelper.setSSOCookie(request, response, st, true);
			return success();
			// if (StringUtils.isEmpty((user.getPassword()))) {
			// return error("100", "未设置密码");// 使用错误码100来判断
			// } else if (!StringUtils.isEmpty(dialectuid)) {// 平台用户
			// String encryPwd =
			// userService.getEncryPassword(app.getEncryFormat(), pass,
			// user.getSalt());
			// if (encryPwd.equals(user.getPassword())) {
			// UserSpaceDetail detail =
			// userSpaceService.findByBusinessCode(user.getSpaceUID());
			// if (detail != null)
			// user.setSpaceDomain(detail.getDomain());
			// /*
			// * 设置登录 Cookie 最后一个参数 true 时添加 cookie 同时销毁当前 JSESSIONID
			// * 创建信任的 JSESSIONID
			// */
			// SSOToken st = new SSOToken(request, user.getUid());
			// st.setData(JSON.toJSONString(user));
			// SSOHelper.setSSOCookie(request, response, st, true);
			// return success();
			// } else {
			// return error("密码错误");
			// }
			// } else {// 众创用户
				/*
				 * 设置登录 Cookie 最后一个参数 true 时添加 cookie 同时销毁当前 JSESSIONID 创建信任的
				 * JSESSIONID
				 */
			// }
		}
	}

	/**
	 * 优软众创更新用户信息
	 *
	 * @param detail
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(value = "/userInfo/fromuuzc", method = RequestMethod.POST)
	@ResponseBody
	public UuzcUserDeatil updateUserInfo(UuzcUserDeatil detail) throws UnsupportedEncodingException {
		String password = detail.getPassword();
		// 转明码
		String pwd = new String(Base64.decodeBase64(password.getBytes(UTF_8)), UTF_8);
		detail.setPassword(pwd);
		User user = detail.covertUser();
		UserDetail userDetail = detail.covert();
		List<User> users = userService.save(user, userDetail);
		return users.size() > 0 ? users.get(0).covert() : null;
	}

	/**
	 * 设置当前企业的hr账号
	 *
	 * @param user
	 * @param uuzcUserSpaceDetail
	 * @throws Exception
	 */
	@RequestMapping(value = "/setHrAccount", method = RequestMethod.POST)
	@ResponseBody
	public ModelMap setHrAccount(User user, UuzcUserSpaceDetail uuzcUserSpaceDetail) throws Exception {
		// 先判断当前企业是否已经存在hr账号
		User hrInfo = userService.findHrInfo(uuzcUserSpaceDetail.getBusinessCode());
		// 存在的话先将以前的权限去掉
        if(null != hrInfo) {
            if(hrInfo.getUid().equals(user.getUid())) {// 如果当前账号是hr账号，不用进行更改
                return new ModelMap("msg", "success");
            } else {
                userService.updateHrInfo(hrInfo, false);
            }
        }
        UserDetail detail = new UserDetail();
        detail.setEmail(user.getSecondUID());
        detail.setName(user.getName());
        detail.setMobile(user.getUid());
        user = userService.findOne("b2b", uuzcUserSpaceDetail.getBusinessCode(), user.getUid());
        if (null == user) {
            userService.save(detail);
            userService.setHrAccount(detail, uuzcUserSpaceDetail);
            user = userService.findOne("b2b", uuzcUserSpaceDetail.getBusinessCode(), detail.getMobile());
            if (null != user) {
                return new ModelMap("msg", "success");
            } else {
                return new ModelMap("msg", "setFailure");
            }
        } else {
            userService.updateHrInfo(user, true);
            return new ModelMap("msg", "success");
        }
	}

	/**
	 * 查询企业是否已开通hr账号
	 *
	 * @param businessCode
	 * @return
	 */
	@RequestMapping(value = "/hrcount", method = RequestMethod.GET)
	@ResponseBody
	public ModelMap getHrAccount(String businessCode) {
		return new ModelMap("count", userService.findHrAccount(businessCode));
	}

    /**
     * 获取当前企业hr的信息
     *
     * @param businessCode
     * @return
     */
    @RequestMapping(value = "/hrInfo", method = RequestMethod.GET)
    @ResponseBody
    public User getHrInfo(String businessCode) {
        return userService.findHrInfo(businessCode);
    }

    /**
     * 获取当前企业的信息
     *
     * @param businessCode
     * @return
     */
    @RequestMapping(value = "/uuzcSpace", method = RequestMethod.GET)
    @ResponseBody
    public UuzcUserSpaceDetail getUuzcUserSpaceDetail(String businessCode) {
        UserSpaceDetail detail = userSpaceService.findByBusinessCode(businessCode);
        return null != detail ? detail.covert() : null;
    }

	/**
	 * 通过企业营业执照查询该企业的员工的信息
	 *
	 * @param businessCode
	 * @return
	 */
	@RequestMapping(value = "/employees", method = RequestMethod.POST)
	@ResponseBody
	public List<User> getEmployees(String businessCode) {
		return userService.findByBusinessCode(businessCode);
	}

	@RequestMapping(value = "/checkTel", method = RequestMethod.GET)
	@ResponseBody
	public ModelMap checkTel (@RequestParam String tel) {
		UserDetail detail = userService.findOne(tel);
		if (detail == null) {
			return error("手机号未注册");
		}
		return success();
	}

	@RequestMapping(value = "/checkEmail", method = RequestMethod.GET)
	@ResponseBody
	public ModelMap checkEmail (@RequestParam String email) {
		if (email == null) {
			return error("请输入邮箱");
		}
		List<UserDetail> details = userService.findByEmail(email);
		if (CollectionUtils.isEmpty(details)) {
			return error("邮箱未注册");
		}
		if (details.size() > 1) {
			// 一个邮箱绑定了多次的账号信息
			return error("您的邮箱未激活，请使用手机号认证");
		}
		request.getSession().setAttribute("fistStep", true);
		return success();
	}

	/**
	 * 获取用户密保问题
	 * @param tel
	 * @return
	 */
	@RequestMapping(value = "/encrypted/question", method = RequestMethod.GET)
	@ResponseBody
	public ModelMap getEncryptedQuestion (@RequestParam String tel) {
		UserDetail detail = (UserDetail) request.getSession().getAttribute("detail");
		if (detail == null) {
			return error("请求超时，请返回第一步进行验证");
		}
		Long userUU = userService.findUserUUByMobile(detail.getMobile());
		if (userUU == null) {
			return error("您尚未设置密保，请联系客服协助处理");
		}
		List<UserQuestion> userQuestions = userQuestionService.getEncryptedQuestion(userUU);
		if (CollectionUtils.isEmpty(userQuestions)) {
			return error("您尚未设置密保，请联系客服协助处理");
		}
		List<Map<String, Object>> questions = new ArrayList<>();
		Map<String, Object> question = null;
		Map<Long, String> answers = new HashMap<>(userQuestions.size());
		Map<Long, Short> sorts = new HashMap<>(userQuestions.size());
		for (UserQuestion userQuestion : userQuestions) {
			question = new HashMap<>(userQuestions.size());
			question.put("id", userQuestion.getId());
			question.put("question", userQuestion.getQuestion());
			questions.add(question);
			answers.put(userQuestion.getId(), userQuestion.getAnswer());
			sorts.put(userQuestion.getId(), userQuestion.getSort());
		}
		request.getSession().setAttribute("answers", answers);
		request.getSession().setAttribute("sorts", sorts);
		return success(questions);
	}

	/**
	 * 校验密保问题
	 *
	 * @param id
	 * @param answer
	 * @return
	 */
	@RequestMapping(value = "/check/question", method = RequestMethod.POST)
	@ResponseBody
	public ModelMap checkEncryptedQuestion (@RequestParam Long id, @RequestParam String answer) {
		Map<Long, String> answers = (Map<Long, String>) request.getSession().getAttribute("answers");
		Map<Long, Short> sorts = (Map<Long, Short>) request.getSession().getAttribute("sorts");
		if (id == null) {
			return error("404", "请刷新重试");
		}
		if (answers == null) {
			return error("404", "该手机号未设置密保");
		}
		if (!answers.containsKey(id)) {
			return error("404", "非法操作");
		}
		if (!answers.get(id).equals(answer)) {
			request.getSession().setAttribute("answer"+sorts.get(id), false);
			return error("请输入正确的答案");
		}
		request.getSession().setAttribute("answer"+sorts.get(id), true);
		boolean isOK;
		try {
			isOK = (boolean) request.getSession().getAttribute("answer1")
					&& (boolean) request.getSession().getAttribute("answer2");
		} catch (NullPointerException e) {
			isOK = false;
		}
		return success("答案正确").addAttribute("isOk", isOK);
	}

	@RequestMapping(value = "/save/question", params = "_count=all", method = RequestMethod.POST)
	@ResponseBody
	public ModelMap saveEncryptedQuestions (List<UserQuestion> questions) {
		userQuestionService.save(questions);
		return success();
	}

	@RequestMapping(value = "/save/question", params = "_count=one", method = RequestMethod.POST)
	@ResponseBody
	public ModelMap saveEncryptedQuestion (UserQuestion userQuestion) {
		userQuestionService.saveOne(userQuestion);
		return success();
	}

	/**
	 * 根据imId获取对应userUU(没有则返回null)
	 *
	 * @param imId
	 * @return
	 */
	@RequestMapping(params = "_operate=getUserUUByImId", method = RequestMethod.GET)
	@ResponseBody
	public String getUserUUByImId(Long imId) {
		if (imId == null)
			throw new AccountException("参数错误");
		return userService.getUserUUByImId(imId);
	}
}
