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

import cn.iselab.mooctest.rpc.user.data.UserDTO;
import cn.iselab.mooctest.rpc.user.data.UserWechatDTO;
import cn.iselab.mooctest.rpc.user.data.WechatUserInfoDTO;
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.data.UserInfo;
import cn.iselab.mooctest.user.model.UserThirdParty;
import cn.iselab.mooctest.user.service.ThirdPartyAuthService;
import cn.iselab.mooctest.user.service.UserService;
import cn.iselab.mooctest.user.util.EncryptionUtil;
import cn.iselab.mooctest.user.web.data.UserVO;
import cn.iselab.mooctest.user.web.logic.ThirdPartyLogic;
import cn.iselab.mooctest.user.web.logic.UserLogic;
import cn.iselab.mooctest.user.web.logic.WechatLogic;
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.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.net.URLDecoder;

/**
 * @Author: xuexb
 * @Date: 2018.12.21 11:51
 */
@Controller
public class PageController extends BaseController{

    @Autowired
    UserLogic userLogic;

    @Autowired
    ThirdPartyLogic thirdPartyLogic;

    @Autowired
    ThirdPartyAuthService thirdPartyAuthService;

    @Autowired
    WechatLogic wechatLogic;

    @Value("${redirect.url}")
    private String redirectUrl;


    @RequestMapping(value = UrlConstants.PAGE + "login", method = RequestMethod.GET)
    public String login(@RequestParam(value = "redirect", required = false)String redirect, HttpServletRequest request){
        LOG.info("redirect:" + redirect);
        String redirectUrl = "";
        try {
            redirectUrl = URLDecoder.decode(redirect, "UTF-8");
        } catch (Exception e) {
            LOG.error("redirectUrl 解码出错", e);
            redirectUrl = null;
        }
        if (redirectUrl==null || redirectUrl.isEmpty() || !redirectUrl.startsWith("http")){
            if (request.getSession().getAttribute("redirectURL")==null)
                redirectUrl = UrlConstants.DEFAULT_GOTO;
            else
                redirectUrl = (String) request.getSession().getAttribute(("redirectURL"));
        }
        HttpSession session = request.getSession();
        session.setAttribute("redirectURL", redirectUrl);
        LOG.info("RedirectUrl: " + redirectUrl);
        if (session.getAttribute("userId") != null){
            LOG.info("用户已登录!用户ID"+session.getAttribute("userId"));
            return "redirect: "+redirectUrl;
        }
        return "login";
    }

    @RequestMapping(value = UrlConstants.PAGE + "dologin", method = RequestMethod.POST)
    public String checkLogin(Model model, UserDTO user, HttpServletRequest request, HttpServletResponse response){
        ResponseResult<UserDTO> result = new ResponseResult<UserDTO>();
        String password = EncryptionUtil.encryptMD5(user.getPassword());
        user.setPassword(password);
        result = userLogic.checkPWD(user);
        if (result.getStatus().equals(ResponseStatus.SUCCESS)) {
            HttpSession session = request.getSession();
            session.setAttribute("userId", ((UserDTO)result.getData()).getId()+"");
            session.setAttribute("userName", ((UserDTO)result.getData()).getEmail());
            // return "redirect:http://www.mooctest.net/api/test/login";
            LOG.info("(String)session.getAttribute(redirectURL) " + (String)session.getAttribute("redirectURL"));
//            String afterLogin = session.getAttribute("redirectURL")==null?
//                    UrlConstants.DEFAULT_GOTO:(String)session.getAttribute("redirectURL");
            userLogic.recordLoginAction(request, ((UserDTO)result.getData()).getId() , "password");
            LOG.info("redirectURL: "+redirectUrl);
            LOG.info("userId: "+ session.getAttribute("userId"));
            return "redirect:" + redirectUrl;
        }
        else{
            model.addAttribute("result", result);
            return "login";
        }
    }

    @RequestMapping(value = UrlConstants.PAGE + "mobile/login", method = RequestMethod.GET)
    public String mobileLogin(){
        return "mobile_login";
    }

    @RequestMapping(value = UrlConstants.PAGE + "mobile/dologin", method = RequestMethod.POST)
    public String checkMobileLogin(Model model, UserVO userVO, HttpServletRequest request){
        ResponseResult<UserDTO> result = userLogic.loginByMobile(userVO);
        model.addAttribute("result", result);
        if (result.getStatus() != ResponseStatus.SUCCESS){
            return "mobile_login";
        }
        HttpSession session = request.getSession();
        session.setAttribute("userId", ((UserDTO)result.getData()).getId()+"");
        session.setAttribute("userName", ((UserDTO)result.getData()).getEmail());
        userLogic.recordLoginAction(request, ((UserDTO)result.getData()).getId(), "mobile");
        String redirectURL = (String) request.getSession().getAttribute("redirectURL");
        redirectURL = redirectURL==null?UrlConstants.DEFAULT_GOTO:redirectURL;
        return "redirect:"+redirectURL;
    }

    @RequestMapping(value = UrlConstants.PAGE + "register", method = RequestMethod.GET)
    public String register(){
        return "register";
    }

    @RequestMapping(value = UrlConstants.PAGE + "doregister", method = RequestMethod.POST)
    public String doRegister(Model model, UserVO userVO, HttpServletRequest request){
        ResponseResult<UserDTO> result = new ResponseResult<>();
        result = userLogic.registerAccount(userVO);
        if (result.getStatus() != ResponseStatus.SUCCESS){
            model.addAttribute("result", result);
            return "register";
        }
        model.addAttribute("href", UrlConstants.GO_LOGIN);
        return "success_page";
    }

    @RequestMapping(value = UrlConstants.PAGE + "login/github", method = RequestMethod.GET)
    public String loginByGithub(@RequestParam("code")String code, Model model, HttpServletRequest request){
        ResponseResult<Object> result = new ResponseResult<>();
        LOG.info("code: " + code);
        result = thirdPartyLogic.loginByGithub(code, request);
        if (result.getStatus()==ResponseStatus.NOTFOUND){
            UserInfo userInfo = (UserInfo) result.getData();
            model.addAttribute("thirdPartyName", userInfo.getNickname());
            model.addAttribute("thirdPartyId", userInfo.getThirdPartyId());
            model.addAttribute("headImg", userInfo.getHeadimgurl());
            model.addAttribute("from", "github");
            return "third_party_bind";
        }
        HttpSession session = request.getSession();
        UserDTO user = userLogic.getUserById(((UserThirdParty)result.getData()).getUserId());
        session.setAttribute("userId", user.getId()+"");
        session.setAttribute("userName", user.getEmail());
        userLogic.recordLoginAction(request, user.getId(), "github");
        String redirectUrl = (String)request.getSession().getAttribute("redirectURL");
        if (redirectUrl==null || redirectUrl.isEmpty())
            redirectUrl = UrlConstants.DEFAULT_GOTO;
        return "redirect:"+redirectUrl;
    }

    @RequestMapping(value = UrlConstants.PAGE + "login/wechat", method = RequestMethod.GET)
    public String loginByWechat(@RequestParam("code")String code, Model model, HttpServletRequest request){
        LOG.info("wechat_code: " + code);
        UserWechatDTO userWechatDTO = wechatLogic.getUserByCode(code);
        if(userWechatDTO.getType()==UserWechatDTO.NEW){
            model.addAttribute("headImg",userWechatDTO.getUserInfo().getHeadimgurl());
            model.addAttribute("thirdPartyName",userWechatDTO.getUserInfo().getNickname());
            model.addAttribute("unionid",userWechatDTO.getUserInfo().getUnionid());
            model.addAttribute("openid",userWechatDTO.getUserInfo().getOpenid());
            model.addAttribute("from","wechat");
            return "third_party_bind";
        }
        HttpSession session = request.getSession();
        session.setAttribute("userId", userWechatDTO.getUser().getId()+"");
        session.setAttribute("userName", userWechatDTO.getUser().getEmail());
        userLogic.recordLoginAction(request,userWechatDTO.getUser().getId(), "wechat");
        String redirectUrl = (String) session.getAttribute("redirectURL");
        if (redirectUrl==null || redirectUrl.isEmpty())
            redirectUrl = UrlConstants.DEFAULT_GOTO;
        return "redirect:"+redirectUrl;
    }



    @RequestMapping(value = UrlConstants.PAGE + "thirdParty/bind", method = RequestMethod.POST)
    public String thirdPartyBind(UserVO userVO, Model model, HttpServletRequest request){
        UserVO user = userVO;
        LOG.info(userVO.toString());
        user.setPassword(EncryptionUtil.encryptMD5(user.getPassword()));
        ResponseResult<UserDTO> result = userLogic.checkPWD(user);
        if (result.getStatus()!=ResponseStatus.SUCCESS){
            model.addAttribute("result", result);
            model.addAttribute("thirdPartyName", userVO.getThirdPartyName());
            model.addAttribute("thirdPartyId", userVO.getThirdPartyId());
            model.addAttribute("headImg", userVO.getHeadImgUrl());
            model.addAttribute("from", userVO.getFrom());
            model.addAttribute("openid", userVO.getOpenid());
            model.addAttribute("unionid", userVO.getUnionid());
            return "third_party_bind";
        }
        UserDTO userToBind = (UserDTO) result.getData();
        if(userVO.getFrom()=="wechat"){
            UserWechatDTO userWechatDTO = new UserWechatDTO();
            userWechatDTO.setUser(userToBind);
            WechatUserInfoDTO wechatUserInfoDTO = new WechatUserInfoDTO();
            wechatUserInfoDTO.setUnionid(userVO.getUnionid());
            wechatUserInfoDTO.setOpenid(userVO.getOpenid());
            userWechatDTO.setUserInfo(wechatUserInfoDTO);
            wechatLogic.setUserWechat(userWechatDTO);
            userLogic.recordUserOperation(request, userToBind.getId(), "bind to third party", "wechat");
            userLogic.recordLoginAction(request, userToBind.getId(), "wechat");
        }else {
            UserThirdParty userThirdParty = new UserThirdParty();
            userThirdParty.setThirdPartyIdentity(userVO.getThirdPartyId());
            userThirdParty.setUserId(userToBind.getId());
            userThirdParty.setType(userVO.getFrom());
            userThirdParty.setIsDelete(0);
            LOG.info(userThirdParty.getUserId()+"--"+userThirdParty.getThirdPartyIdentity()+"---"+userThirdParty.getType());
            thirdPartyAuthService.save(userThirdParty);
            userLogic.recordUserOperation(request, userToBind.getId(), "bind to third party", userThirdParty.getType());
            userLogic.recordLoginAction(request, userToBind.getId(), userThirdParty.getType());
        }
        HttpSession session = request.getSession();
        session.setAttribute("userId", ((UserDTO)result.getData()).getId()+"");
        session.setAttribute("userName", ((UserDTO)result.getData()).getEmail());
        String redirectUrl = (String)request.getSession().getAttribute("redirectURL");
        if (redirectUrl==null || redirectUrl.isEmpty())
            redirectUrl = UrlConstants.DEFAULT_GOTO;
        return "redirect:"+redirectUrl;
    }

    @RequestMapping(value = UrlConstants.PAGE + "uploadBankInfo", method = RequestMethod.GET)
    public String uploadBankInfo(@RequestParam(value = "redirect", required = false)String redirect, Model model, HttpServletRequest request){
        if (request.getSession().getAttribute("userId")==null){
            model.addAttribute("message", "请登录后再进行操作！");
            return "error_page";
        }
        if (redirect==null){
            redirect = request.getSession().getAttribute("redirectURL")==null ?
                    UrlConstants.DEFAULT_GOTO : (String) request.getSession().getAttribute("redirectURL");
        } else{
            try {
                redirect = URLDecoder.decode(redirect, "UTF-8");
            } catch (Exception e) {
                LOG.error("redirectUrl 解码出错", e);
                redirect = UrlConstants.DEFAULT_GOTO;
            }
        }
        request.getSession().setAttribute("redirectURL", redirect);
        return "upload_card_info";
    }

    @RequestMapping(value = UrlConstants.PAGE + "forgetPassword/mobile", method = RequestMethod.GET)
    public String forgetPassword(){
        return "forget_password_mobile";
    }

    @RequestMapping(value = UrlConstants.PAGE + "forgetPassword/email", method = RequestMethod.GET)
    public String forgetPasswordByEmail(){
        return "forget_password_email";
    }

    @RequestMapping(value = UrlConstants.PAGE + "forgetPassword/check/{type}", method = RequestMethod.POST)
    public String foregetPasswordCheck(@PathVariable("type") String type, UserVO userVO, Model model){
        ResponseResult<UserVO> result = userLogic.checkVerifyCode(userVO, type);
        if (result.getStatus()!=ResponseStatus.SUCCESS){
            model.addAttribute("result", result);
            return "forget_password_"+type;
        }
        model.addAttribute("user", (UserVO)result.getData());
        return "forget_password_reset";
    }

    @RequestMapping(value = UrlConstants.PAGE + "update/password", method = RequestMethod.GET)
    public String updatePassword(@RequestParam(value = "redirect", required = false)String redirect, Model model, HttpServletRequest request){
        if (request.getSession().getAttribute("userId")==null){
            model.addAttribute("message", "请前往登录后再进行操作");
            return "error_page";
        }
        userLogic.saveRedirectUrl(redirect, request);
        return "reset_password";
    }

    @RequestMapping(value = UrlConstants.PAGE + "update/email", method = RequestMethod.GET)
    public String updateEmail(Model model, HttpServletRequest request){
        if (request.getSession().getAttribute("userId")==null){
            model.addAttribute("message", "请前往登录后再进行操作");
            return "error_page";
        }
        return "reset_email";
    }

    @RequestMapping(value = UrlConstants.PAGE + "update/mobile", method = RequestMethod.GET)
    public String updateMobile(Model model, HttpServletRequest request){
        if (request.getSession().getAttribute("userId")==null){
            model.addAttribute("message", "请前往登录后再进行操作");
            return "error_page";
        }
        return "reset_mobile";
    }

    @RequestMapping(value = UrlConstants.PAGE + "operation/success", method = RequestMethod.GET)
    public String operationSuccess(Model model){
        model.addAttribute("message", "操作成功!");
        return "success_page";
    }

    @RequestMapping("error-404")
    public String toPage404(Model model){
        model.addAttribute("message", "老铁，你的页面飞走了！\n404 Not Fount");
        return "error_page";
    }

    @RequestMapping("error-400")
    public String toPage400(Model model){
        model.addAttribute("message", "对不起，你的请求出错了！\n400 Bad Request");
        return "error_page";
    }

    @RequestMapping("error-500")
    public String toPage500(Model model){
        model.addAttribute("message", "大侠，系统出现了错误！\n500 Error");
        return "error_page";
    }
}
