package cn.iselab.mooctest.user.web.ctrl;

import cn.iselab.mooctest.rpc.user.data.UserDTO;
import cn.iselab.mooctest.user.constants.ResponseStatus;
import cn.iselab.mooctest.user.constants.UrlConstants;
import cn.iselab.mooctest.user.data.ResponseResult;
import cn.iselab.mooctest.user.model.OperationRecord;
import cn.iselab.mooctest.user.model.User;
import cn.iselab.mooctest.user.util.EncryptionUtil;
import cn.iselab.mooctest.user.util.OSSUtil;
import cn.iselab.mooctest.user.web.data.BankAccountInfoVO;
import cn.iselab.mooctest.user.web.data.OperationRecordVO;
import cn.iselab.mooctest.user.web.data.UserVO;
import cn.iselab.mooctest.user.web.exception.ConfigurationNotExistException;
import cn.iselab.mooctest.user.web.logic.UserLogic;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.websocket.Session;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author sean
 * @date 2018-03-05.
 */
@Slf4j
@RestController
public class UserController extends BaseController {

    @Autowired
    private UserLogic userLogic;

    @Autowired
    private OSSUtil ossUtil;

    @RequestMapping(value = UrlConstants.API + "user/{id:\\d+}", method = RequestMethod.GET)
    public UserDTO getUserById(@PathVariable("id") Long id) {
        return userLogic.getUserById(id);
    }

    @RequestMapping(value = UrlConstants.API + "userByEmail/{email:.+}", method = RequestMethod.GET)
    public UserDTO getUserByEmail(@PathVariable("email") String email) {
        log.info("Email: " + email);
        UserDTO userByEmail = userLogic.getUserByEmail(email);
        return userByEmail;
    }

    @RequestMapping(value = UrlConstants.API + "user", method = RequestMethod.POST)
    public UserDTO save(@RequestBody UserDTO userDTO) {
        return userLogic.save(userDTO);
    }


    @RequestMapping(value = UrlConstants.API + "login", method = RequestMethod.POST)
    public ResponseResult<UserDTO> checkLogin(@RequestBody UserDTO user, HttpServletRequest request, HttpServletResponse response) {
        String password = EncryptionUtil.encryptMD5(user.getPassword());
        user.setPassword(password);
        ResponseResult<UserDTO> result = userLogic.checkPWD(user);
        if (result.getStatus() == ResponseStatus.SUCCESS) {
            HttpSession session = request.getSession();
            session.setAttribute("userId", ((UserDTO) result.getData()).getId() + "");
            // return "redirect:http://www.mooctest.net/api/test/login";
        }
        return result;
    }

    @RequestMapping(value = UrlConstants.API + "logout", method = RequestMethod.GET)
    public ResponseResult<Object> logout(HttpServletRequest request) {
        ResponseResult<Object> result = new ResponseResult<Object>();
        Object userId = request.getSession().getAttribute("userId");
        if (userId != null) {
            request.getSession().removeAttribute("userId");
            request.getSession().invalidate();
            result.init(ResponseStatus.SUCCESS, "用户成功退出", userId);
            LOG.info("用户成功退出--userId--" + (String) userId);
        } else {
            result.init(ResponseStatus.FAILED, "用户未登录", null);
            LOG.info(result.getMsg());
        }
        return result;
    }

    @RequestMapping(value = UrlConstants.API + "mobile/login", method = RequestMethod.GET)
    public ResponseResult<Object> mobileLogin(UserVO userVO, HttpServletRequest request) {
        return null;
    }

    @RequestMapping(value = UrlConstants.API + "verify/mail", method = RequestMethod.PUT)
    public ResponseResult<String> sendVerifyEmail(UserDTO userDTO) {
        ResponseResult<String> result = new ResponseResult<>();
        result = userLogic.sendVerifyEmail(userDTO);
        return result;
    }

    @RequestMapping(value = UrlConstants.API + "verify/mobile", method = RequestMethod.PUT)
    public ResponseResult<String> sendVerifyMobileMessage(UserDTO userDTO) {
        return userLogic.sendMobileVerfication(userDTO);
    }

    /**
     * 非本项目的登录注册界面中的邮箱验证码获取，此时需要传值为json格式
     *
     * @param userDTO
     * @return
     */
    @RequestMapping(value = UrlConstants.API + "verify/mail/new", method = RequestMethod.PUT)
    public ResponseResult<String> sendVerifyEmailNew(@RequestBody UserDTO userDTO) {
        return userLogic.sendVerifyEmail(userDTO);
    }

    /**
     * 非本项目的登录注册界面中的手机验证码获取，此时需要传值为json格式
     *
     * @param userDTO
     * @return
     */
    @RequestMapping(value = UrlConstants.API + "verify/mobile/new", method = RequestMethod.PUT)
    public ResponseResult<String> sendVerifyMobileMessageNew(@RequestBody UserDTO userDTO) {
        return userLogic.sendMobileVerfication(userDTO);
    }

    @RequestMapping(value = UrlConstants.API + "password/reset", method = RequestMethod.PUT)
    public ResponseResult<UserVO> resetPassword(@RequestBody UserVO userVO) {
        return userLogic.resetPassword(userVO);
    }

    @RequestMapping(value = UrlConstants.API + "user/password", method = RequestMethod.PUT)
    public ResponseResult<UserVO> updatePassword(@RequestBody UserVO userVO, HttpServletRequest request) {
        return userLogic.updateUserPassword(userVO, request);
    }

    @RequestMapping(value = UrlConstants.API + "user/password/new", method = RequestMethod.PUT)
    public ResponseResult<UserVO> updatePasswordNew(@RequestBody UserVO userVO, HttpServletRequest request) {
        return userLogic.updateUserPasswordNew(userVO, request);
    }

    @RequestMapping(value = UrlConstants.API + "user/email", method = RequestMethod.PUT)
    public ResponseResult<UserVO> updateEmail(@RequestBody UserVO userVO, HttpServletRequest request) {
        ResponseResult<UserVO> responseResult = userLogic.updateUserEmail(userVO, request);
        return responseResult;
    }

    @RequestMapping(value = UrlConstants.API + "user/mobile", method = RequestMethod.PUT)
    public ResponseResult<UserVO> updateMobile(@RequestBody UserVO userVO, HttpServletRequest request) {
        return userLogic.updateUserMobile(userVO, request);
    }

    /**
     * 验证旧手机号和验证码
     *
     * @param userVO
     * @param request
     * @return
     */
    @RequestMapping(value = UrlConstants.API + "user/old/mobile", method = RequestMethod.PUT)
    public ResponseResult<UserVO> verifyOldMobile(@RequestBody UserVO userVO, HttpServletRequest request) {
        return userLogic.verifyOldMobile(userVO, request);
    }

    @RequestMapping(value = UrlConstants.API + "bankInfo", method = RequestMethod.POST)
    public ModelAndView setBankInfo(BankAccountInfoVO infoVO, HttpServletRequest request) {
        ResponseResult<Object> result = userLogic.setBankInfo(infoVO, request);
        if (result.getStatus() == ResponseStatus.SUCCESS) {
            // return new ModelAndView("redirect:"+(String) request.getSession().getAttribute("redirectURL"));
            userLogic.recordUserOperation(request, Long.parseLong((String) request.getSession().getAttribute("userId")), "Upload Bank Info", "user center");
            return new ModelAndView("success_page").addObject("message", "银行账户信息上传成功！");
        }
        ModelAndView modelAndView = new ModelAndView("error_page");
        modelAndView.addObject("message", result.getMsg());
        return modelAndView;
    }

    @RequestMapping(value = UrlConstants.API + "operation_record", method = RequestMethod.POST)
    public void recordUserOperation(@RequestBody OperationRecordVO recordVO) {
        userLogic.recordUserOperation(recordVO.toOperationRecord());
    }


//    /**
//     * 获取平台名称
//     * @return
//     */
//    @RequestMapping(value = UrlConstants.API + "getPlatformName", method = RequestMethod.GET)
//    public String getPlatformName() throws ConfigurationNotExistException {
//        return userLogic.getPlatformName();
//    }

    /**
     * 获取平台名称
     * @return
     */
    @RequestMapping(value = "/page" + UrlConstants.API + "configuration", method = RequestMethod.GET)
    public Map<String, String> getConfiguration() {
        return userLogic.getConfiguration();
    }
}
