package com.uas.platform.b2b.manage.controller;

import com.uas.platform.b2b.manage.core.support.SystemSession;
import com.uas.platform.b2b.manage.core.util.StringUtils;
import com.uas.platform.b2b.manage.model.Constant;
import com.uas.platform.b2b.manage.model.UseType;
import com.uas.platform.b2b.manage.model.User;
import com.uas.platform.b2b.manage.page.exception.IllegalOperatorException;
import com.uas.platform.b2b.manage.service.UseLogService;
import com.uas.platform.b2b.manage.service.UserService;
import com.uas.platform.b2b.manage.support.MyException;
import com.uas.platform.b2b.manage.support.SecurityConstant;
import com.uas.platform.b2b.manage.web.BaseController;
import com.uas.platform.core.util.AgentUtils;
import com.uas.platform.core.util.encry.Md5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.support.SessionStatus;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

/**
 * 账户信息
 * 
 * @author hejq
 * @date 2018-07-04 19:14
 */
@RestController
public class AccountController extends BaseController {

    @Autowired
    private UserService userService;

    @Autowired
    private UseLogService useLogService;

	/**
	 * 账户信息
	 * 
	 * @return
	 */
	@RequestMapping(value = "/account", method = RequestMethod.GET)
	public ModelMap getAccountInfo() throws Exception {
	    return success(SystemSession.getUser());
	}

    /**
     * 登录
     *
     * @param userName 用户名 手机或邮箱
     * @param passWord 密码 明文
     * @return ModelMap
     *  <pre>
     *      success : 是否成功
     *      content : 用户信息
     *      url : 访问路径
     *  </pre>
     * @throws IllegalAccessException
     * @throws UnsupportedEncodingException
     */
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public ModelMap login(String userName, String passWord) throws IllegalAccessException, UnsupportedEncodingException {
        userService.login(userName.trim(), passWord.trim(), request, response);
        useLogService.appendLog(UseType.LOGIN.code(), null, AgentUtils.getIp(request));
        ModelMap map = new ModelMap();
        User user = SystemSession.getUser();
        String returnUrl = null != user ? SecurityConstant.INDEX_URL : SecurityConstant.LOGIN_URL;
        boolean logSuccess = null != user ? true : false;
        map.put("success", logSuccess);
        map.put("content", user);
        map.put("url", returnUrl);
        return map;
	}

    /**
     * 退出
     *
     * @return 访问路径
     * @throws IOException IO异常
     */
	@RequestMapping(value = "/logout", method = RequestMethod.POST)
	public ModelMap logout() throws IOException {
        SystemSession.clear();
        User user = SystemSession.getUser();
        if (null != user) {
            logout();
        }
		return new ModelMap("url", SecurityConstant.LOGIN_URL);
	}

    /**
     * 检验手机号
     *
     * @param tel 手机号码
     * @return ModelMap success  true
     */
	@RequestMapping(value = "/valid/tel", method = RequestMethod.POST)
    public ModelMap validTel(String tel) {
	    User user = userService.findByTel(tel);
	    if (null != user) {
            throw new IllegalOperatorException("手机已注册");
        }
        return success();
    }

    /**
     * 检验邮箱
     *
     * @param email 邮箱
     * @return ModelMap success  true
     */
    @RequestMapping(value = "/valid/email", method = RequestMethod.POST)
    public ModelMap validEmail(String email) {
        email = email + Constant.EMAIL_SUFFIX;
        User user = userService.findUserByUserEmail(email);
        if (null != user) {
            throw new IllegalOperatorException("邮箱已注册");
        }
        return success();
    }

    /**
     * 注册
     *
     * @param user 用户信息
     * @return ModelMap
     * <pre>
     *     success: true
     *     content: user
     * </pre>
     */
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public ModelMap register(User user) {
        return success(userService.register(user));
    }

    /**
     * 找回密码
     */
    @RequestMapping(value = "/resetPwd", method = RequestMethod.POST)
    public void resetPwd(@RequestBody String email) {
        if (StringUtils.isEmpty(email)) {
            throw new IllegalOperatorException("请输入邮箱地址");
        }
        // 等于符号
        String equalSymbol = "=";
        if (email.contains(equalSymbol)) {
            email = email.replace("=", "");
        }
        email = email + Constant.EMAIL_SUFFIX;
        userService.sendResetPwdUrl(email);
    }

    /**
     * 通过链接修改密码
     */
    @RequestMapping(value = "/resetPwd/url", method = RequestMethod.GET)
    public void resetPwdByUrl(String secretKey, HttpServletResponse response, HttpServletRequest request) throws IOException, MyException, ServletException {
        userService.resetPwd(secretKey, response, request);
    }

    /**
     * 修改密码
     *
     * @param id 用户id
     * @param password 密码
     */
    @RequestMapping(value = "/resetPassword/{id}", method = RequestMethod.POST)
    public void resetPassword(@PathVariable("id") Long id, String password, HttpServletResponse response) throws IOException {
        useLogService.appendLog(UseType.RESETPASSWORD.code(), SystemSession.getUser().getPassword() + "-->" + Md5Utils.encode(password, SystemSession.getUser().getName()), AgentUtils.getIp(request));
        userService.resetPassword(id, password, response);
    }
}
