package com.uas.sso.controller;

import com.uas.account.AccountConfig;
import com.uas.account.core.Logger;
import com.uas.account.core.util.StringUtil;
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.service.AppService;
import com.uas.account.service.SettingService;
import com.uas.account.service.TokenService;
import com.uas.account.service.UserService;
import com.uas.account.web.BaseController;
import com.uas.message.sms.service.SmsService;
import com.uas.sso.web.waf.request.WafRequestWrapper;

import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
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;

/**
 * 个人用户注册请求
 */
@Controller
@RequestMapping("/sso")
public class RegisterPersonalController extends BaseController {

	@Autowired
	private UserService userService;

	@Autowired
	private SettingService settingService;

	@Autowired
	private SmsService smsService;

	@Autowired
	private TokenService tokenService;

	@Autowired
	private AppService appService;

	private Logger logger = Logger.getLogger();

	/**
	 * 注册界面
	 * 
	 * @throws Exception
	 */
	@RequestMapping(value = "/register_p", method = RequestMethod.GET)
	public ModelAndView registerPage(ModelMap model) throws Exception {
		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);

		if(false) {
			model.addAttribute("pageStepPerson", 2);
		} else {

			// 防恶意注册
			String pageToken = StringUtil.uuid();
			request.getSession().setAttribute("pageToken", pageToken);
			model.addAttribute("pageToken", pageToken);

			Object pageStepPerson = request.getSession().getAttribute("pageStepPerson");
			model.addAttribute("pageStepPerson", pageStepPerson == null ? 1 : pageStepPerson);
		}
		return new ModelAndView("sso/reg_personal", model);
	}

	@RequestMapping(value = "/user/register", method = RequestMethod.POST)
	@ResponseBody
	public ModelMap register(final UserDetail user, @RequestParam(required = true) String pageToken, String returnUrl) {
		if (!pageToken.equals(request.getSession().getAttribute("pageToken"))) {
			return error("为防止恶意注册，请刷新后重试");
		}

		UserDetail newUser = userService.register(user);

		request.getSession().setAttribute("pageStepPerson", 2);
		request.getSession().removeAttribute("pageToken");

		request.getSession().setAttribute("registerMobile", user.getMobile());

		ModelMap data = new ModelMap();
		data.put("returnUrl", returnUrl);
		return success(data);
	}

	@RequestMapping(value = "/user/applyApp", method = RequestMethod.POST)
	@ResponseBody
	public ModelMap applyApp(@RequestParam(required = true) String pageToken, @RequestParam String password, @RequestParam String passwordConfirm, String returnUrl) {
		if (!pageToken.equals(request.getSession().getAttribute("pageToken"))) {
			return error("为防止恶意注册，请刷新后重试");
		}

		if(StringUtils.isEmpty(password) || StringUtils.isEmpty(passwordConfirm) || !password.equals(passwordConfirm)) {
			return error("请输入密码，并确认密码");
		}

		String registerMobile = (String) request.getSession().getAttribute("registerMobile");
		if(StringUtils.isEmpty(registerMobile)) {
			request.getSession().setAttribute("pageStepPerson", 1);
			request.getSession().removeAttribute("pageToken");
			return error("注册信息已过期，请重新注册");
		}

		UserDetail userDetail = userService.findOne(registerMobile);
		if(userDetail == null) {
			request.getSession().setAttribute("pageStepPerson", 1);
			request.getSession().removeAttribute("pageToken");
			return error("注册信息已过期，请重新注册");
		}
		User user = userService.syncUserToB2B(userDetail, password);
		try {
			userService.syncUserToApp(appService.findOne("mall"), user, userDetail);
			logger.info("个人注册同步到商城", user);
		} catch (Exception e) {
			logger.error("个人注册同步数据到商城", e.getMessage(), user);
		}

		request.getSession().setAttribute("pageStepPerson", 1);
		request.getSession().removeAttribute("registerMobile");

		ModelMap data = new ModelMap();
		data.put("returnUrl", returnUrl);
		return success(data);
	}

	@RequestMapping(value = "/user/checkTelEnable", method = RequestMethod.GET)
	@ResponseBody
	public ModelMap checkTelEnable(final String uid) {
		ModelMap data = new ModelMap();
		List<User> users = userService.findByUID(uid);
		if(users!=null && users.size()>0){
			return error("该账号已被注册");
		}else{
			return success(data);
		}
	}

	/**
	 * 获取验证码
	 *
	 * @param tel
	 * @return
	 */
	@RequestMapping(value = "/user/checkcode", method = RequestMethod.GET)
	@ResponseBody
	public ModelMap sendCheckCode(String tel, @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);
		System.out.println(code);
		Token token = new Token(code, 600);
		token.setTel(tel);
		tokenService.save(token);
		ModelMap data = new ModelMap();
		data.put("checkcode", code);
		request.getSession().setAttribute("token", token.getId());
		// 手机短信
		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 = "/user/checkcode", method = RequestMethod.POST)
	@ResponseBody
	public ModelMap validCheckCode(String tel, 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)){
				return error("请重新获取验证码");
			}
			String existCode = existToken.getBind().toString();
			if (code.equals(existCode)) {
				return success();
			} else {
				return error("验证码错误");
			}
		}
		return error("参数错误");
	}

}
