package com.uas.sso.controller;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.validation.Valid;

import com.uas.account.exception.VisibleError;
import org.apache.commons.io.FilenameUtils;
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.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
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.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.uas.account.AccountConfig;
import com.uas.account.core.Status;
import com.uas.account.core.util.ArrayUtils;
import com.uas.account.core.util.ChineseUtils;
import com.uas.account.core.util.ExecuteUtils;
import com.uas.account.core.util.FastjsonUtils;
import com.uas.account.core.util.HttpUtils;
import com.uas.account.core.util.StringUtil;
import com.uas.account.entity.App;
import com.uas.account.entity.FileUrl;
import com.uas.account.entity.Setting;
import com.uas.account.entity.Token;
import com.uas.account.entity.User;
import com.uas.account.entity.UserDetail;
import com.uas.account.entity.UserSpaceAndUserInfo;
import com.uas.account.entity.UserSpaceDetail;
import com.uas.account.service.AppService;
import com.uas.account.service.SettingService;
import com.uas.account.service.TokenService;
import com.uas.account.service.UserService;
import com.uas.account.service.UserSpaceService;
import com.uas.account.viewmodel.ApplyAppView;
import com.uas.account.web.BaseController;
import com.uas.dfs.service.FileClient;
import com.uas.message.mail.service.MailService;
import com.uas.message.sms.service.SmsService;
import com.uas.sso.SSOHelper;
import com.uas.sso.common.encrypt.base64.Base64;
import com.uas.sso.web.waf.request.WafRequestWrapper;

@Controller
@RequestMapping("/sso")
public class RegisterController extends BaseController {

	@Autowired
	private UserSpaceService userSpaceService;
	@Autowired
	private FileClient fileClient;
	@Autowired
	private MailService mailService;
	@Autowired
	private SmsService smsService;
	@Autowired
	private SettingService settingService;
	@Autowired
	private TokenService tokenService;
	@Autowired
	private AppService appService;
	@Autowired
	private UserService userService;

	/**
	 * 注册界面，注册三步都由此方法加载，使用pageStep控制注册步数
	 *
	 * 
	 * @throws Exception
	 */
	@RequestMapping(value = "/register", method = RequestMethod.GET)
	public ModelAndView registerPage(ModelMap model) throws Exception {
		// 先清除可能存在的登录状态
		SSOHelper.clearLogin(request, response);

		WafRequestWrapper wr = new WafRequestWrapper(request);

		// 指定returnUrl
		String returnUrl = wr.getParameter(AccountConfig.ReturnURLParam);
		model.addAttribute("returnUrl", returnUrl);

		// 指定注册的app
		String appId = wr.getParameter(AccountConfig.AppIdParam);
		if (StringUtils.isEmpty(appId)) {
			appId = AccountConfig.ACCOUNT_CENTER;
		}
		model.addAttribute("appId", appId);

		Object businessCode = request.getSession().getAttribute("businessCode");
		final UserSpaceDetail detail = (UserSpaceDetail) request.getSession().getAttribute("userspace");
		String inviteuid = wr.getParameter("inviteuid");
		String inviteUserCode = wr.getParameter("inviteUserCode");
		String method = wr.getParameter("method");
		String router = "sso/register";
		/*
		 * businessCode为空或者userspace数据为空时则跳转第一步，并清除userspace数据，注册一个新的企业
		 * 否则
		 * 		1、页面跳转第一步，清除businessCode，为了再次刷新清除历史注册数据
		 * 		2、页面跳转第二步，将填写的企业信息放入session中，企业激活
		 * 		3、页面跳转第三步，清除userspace，为了刷新页面之后跳转第一步并清除本次注册数据
		 * 	第一步不能清除userspace数据，否则在第二步时点上一步按钮没有企业数据
		 * 	第三步不能清除businessCode，否则开通应用的时候找不到企业
		 * 	所以当userspace或者businessCode为空时表示新注册一个新的企业
		 */
		if (!StringUtils.isEmpty(businessCode) && detail != null) {
			int pageStep = (int) request.getSession().getAttribute("pageStep");
			if (pageStep == 1) {
				model.addAttribute("pageToken", request.getSession().getAttribute("pageToken"));
				request.getSession().removeAttribute("businessCode");
			} else if (pageStep == 2) {
				model.addAttribute("pageToken", request.getSession().getAttribute("pageToken"));
				request.getSession().setAttribute("returnUrl", returnUrl);
			} else {
				List<User> users = userService.findByUID(detail.getAdminTel());
				model.addAttribute("adminExist", !CollectionUtils.isEmpty(users));
				detail.setDomain(generateDefaultDomain(detail));
				model.addAttribute("content", detail);
				model.addAttribute("pageStep", 3);
				request.getSession().removeAttribute("userspace");
			}
		} else {
			// new
			model.addAttribute("pageStep", 1);
            request.getSession().removeAttribute("userspace");
			request.getSession().removeAttribute("businessCode");
			// // 防恶意注册
			String pageToken = StringUtil.uuid();
			request.getSession().setAttribute("pageToken", pageToken);
			model.addAttribute("pageToken", pageToken);
			request.getSession().setAttribute("returnUrl", returnUrl);
			if (null != inviteuid && null != inviteUserCode) {
				request.getSession().setAttribute("inviteuid", inviteuid);
				request.getSession().setAttribute("inviteUserCode", inviteUserCode);
				if (null != method) {
					request.getSession().setAttribute("method", method);
				}
			}
		}
		return new ModelAndView(router, model);

	}

	/**
	 * 注册界面
	 *
	 * @throws Exception
	 */
	@RequestMapping(value = "/register_mall", method = RequestMethod.GET)
	public ModelAndView registerMall(ModelMap model) throws Exception {
		ModelAndView m = registerPage(model);
		return new ModelAndView("sso/reg_mall",m.getModel());
	}

	@RequestMapping(value = "/lastStep", params = "pageStep", method = RequestMethod.GET)
	@ResponseBody
	public ModelMap lastStep(int pageStep){
		if (pageStep > 1) {
			request.getSession().setAttribute("pageStep", pageStep-1);
			return success();
		}
		return error("无法跳转上一步");
	}

	@RequestMapping(value = "/session/data", method = RequestMethod.POST)
	@ResponseBody
	public ModelMap getSessionData(@RequestParam(value="key",required=false) String key){
		if (!StringUtils.isEmpty(key)){
			return success(request.getSession().getAttribute(key));
		}
		return success();
	}

	/**
	 * 生成默认域名
	 * 
	 * @return
	 */
	private String generateDefaultDomain(UserSpaceDetail detail) {
		String domain = null;
		UserSpaceDetail oldOne = null;
		if (!StringUtils.isEmpty(detail.getUrl())) {
			Pattern p = Pattern.compile("http(s)*://(.+\\.)*(.+)\\..+", Pattern.CASE_INSENSITIVE);
			Matcher m = p.matcher(detail.getUrl());
			if (m.find()) {
				domain = m.group(3);
				if ("1688".equals(domain) || "taobao".equals(domain) || "qq".equals(domain) || "baidu".equals(domain)) {
					domain = m.group(2);
				}
			}
		}
		if (domain == null) {
			domain = StringUtil.substr(ChineseUtils.converterToFirstSpell(StringUtils.trimAllWhitespace(detail.getName())), 0, 16);
		} else {
			oldOne = userSpaceService.findByDomain(domain);
			if (oldOne != null) {
				domain = StringUtil.substr(ChineseUtils.converterToFirstSpell(StringUtils.trimAllWhitespace(detail.getName())), 0, 16);
			}
		}
		oldOne = userSpaceService.findByDomain(domain);
		if (oldOne != null) {
			domain = StringUtil.substr(ChineseUtils.converterToSpell(StringUtils.trimAllWhitespace(detail.getName())), 0, 16);
			oldOne = userSpaceService.findByDomain(domain);
			if (oldOne != null) {
                domain = null;
            }
		}
		return domain;
	}

	/**
	 * 开通应用
	 * 
	 * @param file
	 * @param view
	 * @return
	 */
	@RequestMapping(value = "/register/applyApp", method = RequestMethod.POST)
	@ResponseBody
	public ModelMap applyApps(@RequestBody MultipartFile file, final ApplyAppView view) {
		Object businessCode = request.getSession().getAttribute("businessCode");
		final UserSpaceDetail detail = userSpaceService.findByBusinessCode(businessCode.toString());
		final UserSpaceAndUserInfo info = new UserSpaceAndUserInfo();
		if (detail == null) {
			return error("您的企业注册资料已经失效，请重新注册");
		} else {

			detail.setDomain(view.getDomain());

			// 这里修改下，先只开通默认应用
			Object inviteuid = request.getSession().getAttribute("inviteuid");
			Object inviteUserCode = request.getSession().getAttribute("inviteUserCode");
			Object method = request.getSession().getAttribute("method");
			if (null != inviteuid && null != inviteUserCode) {
				detail.setInviteuid(inviteuid.toString());
				detail.setInviteUserCode(inviteUserCode.toString());
				if (null != method) {
					detail.setMethod(method.toString());
				}
			}
			String password = request.getSession().getAttribute("password") == null ? view.getPassword() : request.getSession().getAttribute("password").toString();
			UserSpaceAndUserInfo viewinfo = userSpaceService.initUserSpaceDetail(detail, password,
					view.getUserDetails());
			info.setSpaceDialectUID(viewinfo.getSpaceDialectUID());
			info.setUserDialectUID(viewinfo.getUserDialectUID());
            ExecuteUtils.asyncExecute(new Runnable() {
                @Override
                public void run() {
                    if (null != view.getApplyApps()) {
                        for (String app : view.getApplyApps()) {
                            // 然后开通可选应用：因为一些可选应用，需要用到默认应用开通后才有的参数
                            userSpaceService.applyApp(detail.getBusinessCode(), app, view.getPassword(), view.getUserDetails());
                        }
                    }
                }
            });
		}
		// 方便下面发送邮件的程序一起执行
		view.getUserDetails().add(new UserDetail(detail));
		if (null == view.getApplyApps() || view.getApplyApps().length == 0) {
			App app = appService.findOne(AccountConfig.ACCOUNT_CENTER);
			view.setApplyApps(new String[] { StringUtils.isEmpty(app.getUserControl()) ? app.getUid() : app.getUserControl() });
		}
		// 知会下企业用户
		ExecuteUtils.asyncExecute(new Runnable() {

			@Override
			public void run() {
				for (UserDetail user : view.getUserDetails()) {
					if (!StringUtils.isEmpty(user.getEmail())) {
						for (String app : view.getApplyApps()) {
							// 邮件
							Setting mailTpl = settingService.findOne("templateForSendMailWhenRegisterFinished." + app + "."
									+ (!StringUtils.isEmpty(user.getDepartment()) ? user.getDepartment() : "管理员"));
							if (mailTpl != null) {
								ModelMap data = new ModelMap();
								data.put("domain", detail.getDomain());
								data.put("spaceName", detail.getName());
								data.put("name", user.getName());
								data.put("uid", user.getMobile());
								data.put("job", user.getJob());
								data.put("enuu", info.getSpaceDialectUID());
								data.put("useruu", info.getUserDialectUID());
								mailService.send(mailTpl.getValue(), user.getEmail(), data);
							}
						}
					}
				}
			}
		});
		return success();
	}

	/**
	 * 校验企业名称
	 * 
	 * @param name
	 * @return
	 */
	@RequestMapping(value = "/userspace/valid", params = "name", method = RequestMethod.GET)
	@ResponseBody
	public ModelMap validName(String name) {
		// 去掉可能存在的空格再进行检验
		name = StringUtils.trimAllWhitespace(name);
		if (!StringUtils.isEmpty(name)) {
			UserSpaceDetail detail = userSpaceService.findByName(name);
			if (null != detail) {
				if (detail.getStatus().equals(Status.ENABLED.value())) {
					return error("企业已被注册，请确认无误后联系管理员（" + detail.getAdminName() + "）处理").addAttribute("registerDate",
							detail.getRegisterDate());
				} else {
					userSpaceService.delete(detail);
				}
			}
		} else {
			return error("参数错误");
		}
		return success();
	}

	/**
	 * 校验企业营业执照
	 * 
	 * @param businessCode
	 * @return
	 */
	@RequestMapping(value = "/userspace/valid", params = "businessCode", method = RequestMethod.GET)
	@ResponseBody
	public ModelMap validBusinessCode(String businessCode) {
		// 去掉可能存在的空格再进行检验
		businessCode = StringUtils.trimAllWhitespace(businessCode);
		if (!StringUtils.isEmpty(businessCode)) {
			UserSpaceDetail detail = userSpaceService.findByBusinessCode(businessCode);
			if (null != detail) {
				if (detail.getStatus().equals(Status.ENABLED.value())) {
					return error("企业已被注册，请确认无误后联系管理员（" + detail.getAdminName() + "）处理").addAttribute("registerDate",
							detail.getRegisterDate());
				} else {
					userSpaceService.delete(detail);
				}
			}
		} else {
			return error("参数错误");
		}
		return success();
	}

	/**
	 * 不允许申请的域名 TODO: 配置到数据库
	 */
	private static final String[] UNUSABLE_DOMAIN = { "www", "uas", "make", "trade", "usoft", "usoftchina", "youruan", "usofterp",
			"report", "ubtob", "ubtoc", "test", "static", "saas", "saas-static", "admin", "administrator", "manage", "manager", "finance",
			"public", "help", "dfs", "message" };

	/**
	 * 校验企业域名
	 * 
	 * @param domain
	 * @return
	 */
	@RequestMapping(value = "/userspace/valid", params = "domain", method = RequestMethod.GET)
	@ResponseBody
	public ModelMap validDomain(String domain) {
		if (!StringUtils.isEmpty(domain)) {
			if (!domain.matches("^[\\w-]+$")) {
				return error("域名不合法，只能包含字母、数字和-");
			}
			if (ArrayUtils.contains(UNUSABLE_DOMAIN, domain) || userSpaceService.findByDomain(domain) != null) {
				return error("域名已被申请");
			}
			return success();
		} else {
			return error("参数错误");
		}
	}

	@RequestMapping(value = "/userspace/register", method = RequestMethod.POST)
	@ResponseBody
	public ModelMap register(final @Valid UserSpaceDetail detail, BindingResult result, @RequestParam(required = true) String pageToken,
							 @RequestBody MultipartFile businessImage, @RequestBody MultipartFile logoFile) {
		request.getSession().setAttribute("pageToken", pageToken);
		if (!pageToken.equals(request.getSession().getAttribute("pageToken"))) {
			return error("为防止恶意注册，请刷新后重试");
		} else {
			// 刷新token
			pageToken = StringUtil.uuid();
			request.getSession().setAttribute("pageToken", pageToken);
		}
		if (result.hasErrors()) {
			return error(result.getFieldErrors()).addAttribute("pageToken", pageToken);
		}
		if (StringUtils.isEmpty(detail.getBusinessCodeImage()) && (businessImage == null || businessImage.isEmpty())) {
			return error("请上传营业执照附件").addAttribute("pageToken", pageToken);
		}
		try {
			if (!(businessImage == null || businessImage.isEmpty())) {
				if (businessImage.getSize() > 5242880) {
					return error("营业执照附件大小不要超过5M").addAttribute("pageToken", pageToken);
				}
				HttpUtils.Response response = HttpUtils.upload(FileUrl.FILE_UPLOAD, businessImage, null);
				JSONObject obj = FastjsonUtils.parseObject(response.getResponseText());
				String path = (String) obj.get("path");
				if (path != null) {
					detail.setBusinessCodeImage(path);
				} else {
					return error("请检查您的营业执照附件").addAttribute("pageToken", pageToken);
				}
			}
		} catch (IOException e) {
			return error("请检查您的营业执照附件").addAttribute("pageToken", pageToken);
		} catch (Exception e) {
			return error("营业执照上传失败").addAttribute("pageToken", pageToken);
		}
		if (null != logoFile && !logoFile.isEmpty()) {
			if (logoFile.getSize() > 102400) {
				return error("Logo图片大小不要超过100Kb");
			}
			try {
				HttpUtils.Response response = HttpUtils.upload(FileUrl.FILE_UPLOAD, businessImage, null);
				JSONObject obj = FastjsonUtils.parseObject(response.getResponseText());
				String path = (String) obj.get("path");
				if (path != null) {
					detail.setLogoImage(path);
				} else {
					return error("请检查您的企业LOGO图片");
				}
			} catch (IOException e) {
				return error("请检查您的企业LOGO图片");
			} catch (Exception e) {
				return error("LOGO图片上传失败");
			}
		}
		request.getSession().setAttribute("pageStep", 2);
		request.getSession().setAttribute("userspace", detail);
		request.getSession().setAttribute("businessCode", detail.getBusinessCode());
		ModelMap data = new ModelMap();
		return success(data);
	}

	@RequestMapping(value = "/mobile/userspace/register", method = RequestMethod.GET)
	@ResponseBody
	public ModelMap registerPageByMobile() {
		// 防恶意注册
		ModelMap model = new ModelMap();
		String pageToken = StringUtil.uuid();
		request.getSession().setAttribute("pageToken", pageToken);
		request.getSession().setAttribute("hehe", "hahaha");
		model.addAttribute("pageToken", pageToken);
		model.addAttribute("sessionId", request.getSession().getId());
 		return success(model);
	}

	private String saveFile(String data)  {
		byte[] imgByte = Base64.decode(data);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyymmddhhmmsss");
		String name = sdf.format(new Date()) + ".jpg";
		String path = fileClient.uploadImage(imgByte, imgByte.length, FilenameUtils.getExtension(name), null);
		return  path;
	}

	@RequestMapping(value = "/mobile/userspace/register", method = RequestMethod.POST)
	@ResponseBody
	public ModelMap registerByMobile(final @Valid UserSpaceDetail detail, BindingResult result,
			@RequestParam(required = true) String pageToken, String businessImage) {
		ModelMap data = new ModelMap();
		if (pageToken == null || !pageToken.equals(request.getSession().getAttribute("pageToken"))) {
			return error("为防止恶意注册，请刷新后重试");
		} else {
			// 刷新token
			pageToken = StringUtil.uuid();
			request.getSession().setAttribute("pageToken", pageToken);
			data.put("pageToken", pageToken);
		}
		if (result.hasErrors()) {
			return error(result.getFieldErrors()).addAttribute("pageToken", pageToken);
		}
		String path = saveFile(businessImage);
		detail.setBusinessCodeImage(path);
		UserSpaceDetail oldOne = userSpaceService.findByName(detail.getName());
		if (oldOne != null && oldOne.getStatus().equals(Status.ENABLED.value())) {
			throw new VisibleError("企业名称已被注册！");
		}

		oldOne = userSpaceService.findByBusinessCode(detail.getBusinessCode());
		if (oldOne != null && oldOne.getStatus().equals(Status.ENABLED.value())) {
			throw new VisibleError("营业执照号已被注册！");
		}
		request.getSession().setAttribute("pageStep", 3);
		request.getSession().setAttribute("userspace", detail);
		return success(data);
	}

//	@RequestMapping(value = "/mobile/userspace/register", method = RequestMethod.POST)
//	@ResponseBody
//	public ModelMap registerByMobile(final @Valid UserSpaceDetail detail, BindingResult result,
//			@RequestParam(required = true) String pageToken) {
//		if (!pageToken.equals(request.getSession().getAttribute("pageToken"))) {
//			return error("为防止恶意注册，请刷新后重试");
//		} else {
//			// 刷新token
//			pageToken = StringUtil.uuid();
//			request.getSession().setAttribute("pageToken", pageToken);
//		}
//		if (result.hasErrors()) {
//			return error(result.getFieldErrors()).addAttribute("pageToken", pageToken);
//		}
//
//		userSpaceService.register(detail);
//
//		request.getSession().setAttribute("pageStep", 3);
//		request.getSession().removeAttribute("pageToken");
//		// 知会下审核人
//		ExecuteUtils.asyncExecute(new Runnable() {
//
//			@Override
//			public void run() {
//				// 邮件
//				Setting mailReceiver = settingService.findOne("mailReceiverAfterRegister");
//				Setting mailTpl = settingService.findOne("templateForSendMailWhenRegister");
//				if (mailReceiver != null && mailTpl != null) {
//					ModelMap data = new ModelMap();
//					data.put("name", detail.getShortName());
//					mailService.send(mailTpl.getValue(), mailReceiver.getValue(), data);
//				}
//			}
//		});
//		request.getSession().setAttribute("businessCode", detail.getBusinessCode());
//		return success();
//	}

	/**
	 * 手机注册设置管理员
	 * 
	 * @param adminDetail
	 * @param password
	 * @return
	 */
	@RequestMapping(value = "/mobile/userspace/setAdmin", method = RequestMethod.POST)
	@ResponseBody
	public ModelMap setAdminByMobile(final UserSpaceDetail adminDetail, String password) {

		UserSpaceDetail userSpaceDetail = (UserSpaceDetail) request.getSession().getAttribute("userspace");

		// 校验验证码绑定的手机号和邮箱是否一致
		Token existToken = tokenService.findOne(adminDetail.getCheckcodeToken());

		if (!checkPassword(adminDetail.getAdminTel(), password)) {
            return error("用户名或密码错误！");
        }

		// 设置联系人信息
		userSpaceDetail.setContactMan(adminDetail.getAdminName());
		userSpaceDetail.setContactTel(adminDetail.getContactTel());
		userSpaceDetail.setContactEmail(adminDetail.getContactEmail());
		// 设置管理员信息
		userSpaceDetail.setAdminTel(adminDetail.getAdminTel());
		userSpaceDetail.setAdminName(adminDetail.getAdminName());
		userSpaceDetail.setAdminEmail(adminDetail.getAdminEmail());
		// 设置验证码
		userSpaceDetail.setCheckcode(adminDetail.getCheckcode());
		userSpaceDetail.setCheckcodeToken(adminDetail.getCheckcodeToken());

		userSpaceDetail = userSpaceService.register(userSpaceDetail);

		// 知会下审核人
		final UserSpaceDetail finalUserSpaceDetail = userSpaceDetail;
		ExecuteUtils.asyncExecute(new Runnable() {

			@Override
			public void run() {
				// 邮件
				Setting mailReceiver = settingService.findOne("mailReceiverAfterRegister");
				Setting mailTpl = settingService.findOne("templateForSendMailWhenRegister");
				if (mailReceiver != null && mailTpl != null) {
					ModelMap data = new ModelMap();
					data.put("name", finalUserSpaceDetail.getName());
					mailService.send(mailTpl.getValue(), mailReceiver.getValue(), data);
				}
			}
		});

		ApplyAppView applyAppView = new ApplyAppView();
		applyAppView.setPassword(password);
		List<UserDetail> userDetails = new ArrayList<>();
		userDetails.add(new UserDetail(userSpaceDetail));
		applyAppView.setUsers(JSONObject.toJSONString(userDetails));
		request.getSession().setAttribute("businessCode", userSpaceDetail.getBusinessCode() );
		applyApps(null, applyAppView);
		String spaceUid = null;
		User imUser = userService.findOne("im", spaceUid, userSpaceDetail.getAdminTel());
		User b2bUser = userService.findOne("b2b", userSpaceDetail.getBusinessCode(), userSpaceDetail.getAdminTel());
		ModelMap map = new ModelMap();
		map.put("enUU", b2bUser == null ? null : b2bUser.getSpaceDialectUID());
		map.put("imid", imUser == null ? null : imUser.getDialectUID());
		return success(map);
	}

    /**
     * 校验密码，如果账号存在但是密码错误，则返回false，否则为true
     */
	private boolean checkPassword(String adminTel, String password) {

		List<User> users = userService.findByUID(adminTel);
		// 如果用户存在则校验密码
		boolean checkPsw = false;
		if (!CollectionUtils.isEmpty(users)) {
			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 = password.length() >= 32 ? password : userService.getEncryPassword(
							app.getEncryFormat(), password, one.getSalt());
					if (encryPwd.equals(one.getPassword())) {
						checkPsw = true;
					}
				}
			}
			if (!checkPsw){
				return false;
			}
		}
		return true;
	}

	/**
	 * 获取验证码
	 * 
	 * @param tel
	 * @param email
	 * @return
	 */
	@RequestMapping(value = "/userspace/checkcode", method = RequestMethod.GET)
	@ResponseBody
	public ModelMap sendCheckCode(String tel, String email, @RequestParam String pageToken) {
		if(!pageToken.equals(request.getSession().getAttribute("pageToken"))) {
			return error("非法操作");
		}
		Token _pageToken = tokenService.findOne(pageToken);
		if (null == _pageToken) {
			Token token = new Token(pageToken, 0, 1000*60*60*24);
			tokenService.save(token);
		} else if (System.currentTimeMillis() - _pageToken.getTime().getTime() <= 60000) {
			return error("操作频繁，请稍后再试");
		} else {
			_pageToken.setTime(new Date());
			tokenService.save(_pageToken);
		}
		ModelMap map = new ModelMap();
		// 验证码10分钟有效
		String code = StringUtil.getRandomNumber(6);
		Token token = new Token(code, 600);
		token.setEmail(email);
		token.setTel(tel);
		tokenService.save(token);
		ModelMap data = new ModelMap();
		data.put("checkcode", code);
		request.getSession().setAttribute("token", token.getId());
		// 邮件
		try {
			if (!StringUtils.isEmpty(email)) {
				Setting mailTplId = settingService.findOne("templateForSendEmailWhenRegister");
				if (!StringUtils.isEmpty(mailTplId)) {
                    mailService.send(mailTplId.getValue(), email, data);
                }
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		// 手机短信
		try {
			if (!StringUtils.isEmpty(tel)) {
				Setting smsTplId = settingService.findOne("templateForSendSmsWhenRegister");
				if (!StringUtils.isEmpty(smsTplId)) {
                    smsService.send(smsTplId.getValue(), tel, new Object[]{code});
                }
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		map.put("token", token.getId());

		return success(map);
	}

	/**
	 * 验证验证码是否正确
	 * 
	 * @param token
	 * @param code
	 * @return
	 */
	@RequestMapping(value = "/userspace/checkcode", method = RequestMethod.POST)
	@ResponseBody
	public ModelMap validCheckCode(String tel, String email, String token, String code) {
		if (!StringUtils.isEmpty(token) && !StringUtils.isEmpty(code)) {
			Token existToken = tokenService.findOne(token);
			if (existToken == null || existToken.isExpired()) {
				return error("验证码已经失效，请重新获取");
			}
			if (!existToken.getTel().equals(tel) || !existToken.getEmail().equals(email)){
				return error("请重新获取验证码");
			}
			String existCode = existToken.getBind().toString();
			if (code.equals(existCode)) {
				return success();
			} else {
				return error("验证码错误");
			}
		}
		return error("参数错误");
	}

	@RequestMapping(value = "/userspace/setAdmin", method = RequestMethod.POST)
	@ResponseBody
	public ModelMap setAdmin(String adminName, String password, String adminTel, String adminEmail, String checkcode, String checkcodeToken, String token){
		ModelMap modelMap = new ModelMap();
		request.getSession().setAttribute("password", password);
		if (StringUtils.isEmpty(adminName)) {
			return error("请输入姓名！");
		}
		if (StringUtils.isEmpty(password)) {
			return error("请输入密码！");
		}
		if (StringUtils.isEmpty(adminTel)) {
			return error("请输入手机号！");
		}
		if (StringUtils.isEmpty(adminEmail)) {
			return error("请输入邮箱！");
		}
		Token existToken = tokenService.findOne(token);
		if (!checkPassword(adminTel, password)) {
            return error("用户名或密码错误！");
        }

		// 将第一步和第二步的信息合并
		UserSpaceDetail detail = (UserSpaceDetail) request.getSession().getAttribute("userspace");
		detail.setAdminEmail(adminEmail);
        detail.setAdminName(adminName);
        detail.setAdminTel(adminTel);
		detail.setCheckcodeToken(checkcodeToken);
		detail.setCheckcode(checkcode);
        if (StringUtils.isEmpty(detail.getContactMan())) {
            detail.setContactMan(detail.getAdminName());
            detail.setContactEmail(detail.getAdminEmail());
            detail.setContactTel(detail.getAdminTel());
        }
        detail.setStatus(Status.ENABLED.value());
        try { // 前台显示操作数据库信息，方便找错
			detail = userSpaceService.register(detail);
		} catch (RuntimeException e) {
			return error(e.getMessage());
		}
		request.getSession().setAttribute("pageStep", 3);
		modelMap.put("enuu",detail.getId());
		modelMap.put("returnUrl", request.getSession().getAttribute("returnUrl"));

        // 知会下审核人
        final UserSpaceDetail finalDetail = detail;
        ExecuteUtils.asyncExecute(new Runnable() {

            @Override
            public void run() {
                // 邮件
                Setting mailReceiver = settingService.findOne("mailReceiverAfterRegister");
                Setting mailTpl = settingService.findOne("templateForSendMailWhenRegister");
                if (mailReceiver != null && mailTpl != null) {
                    ModelMap data = new ModelMap();
                    data.put("name", finalDetail.getName());
                    data.put("id", finalDetail.getId());
                    mailService.send(mailTpl.getValue(), mailReceiver.getValue(), data);
                }
                // 短信
                Setting smsReceiver = settingService.findOne("smsReceiverAfterRegister");
                Setting smsTpl = settingService.findOne("templateForSendSmsWhenRegister");
                if (smsReceiver != null && smsTpl != null) {
                    try {
                        smsService.send(smsTpl.getValue(), smsReceiver.getValue(), new Object[] { finalDetail.getName() });
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        });
		return success(modelMap);
	}
}
