package com.wisedu.mooc.app.home.web;


import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.wisedu.coeus.core.ConstantStatic;
import com.wisedu.coeus.util.*;
import com.wisedu.coeus.util.json.JSONObject;
import com.wisedu.mooc.app.home.exception.HomeException;
import com.wisedu.mooc.app.home.service.HomeService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.wisedu.coeus.core.bo.LoginUser;
import com.wisedu.coeus.core.security.LoginCheck;
import com.wisedu.coeus.debug.Logger;
import com.wisedu.coeus.debug.LoggerFactory;
import com.wisedu.coeus.web.LoginContext;
import com.wisedu.mooc.app.user.bo.UserInfo;

@Controller
@RequestMapping(value = "/home")
@LoginCheck("false")
public class HomeController {

    private static final Logger LOGGER = LoggerFactory.getLogger(HomeController.class);

    @Autowired
    private HomeService homeService;

    /**
     * 系统首页
     *
     * @param request
     * @param response
     * @param model
     * @return
     */
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index(HttpServletRequest request, HttpServletResponse response, Model model, ModelMap modelMap) {
        LoginUser loginUser = LoginContext.getLoginUser();
        UserInfo userInfo = (UserInfo) loginUser.getUserInfo();

        //如果已经登录则跳转到课程首页
        if (!loginUser.getGuest()) {
            return "redirect:/portal/mycourse/index.mooc";
        }
        String historyUrl = request.getParameter("historyUrl");

        model.addAttribute("historyUrl", historyUrl);
        model.addAttribute("lUser", loginUser);
        model.addAttribute("uInfo", userInfo);
        return "home.index";
    }

    /**
     * 退出
     *
     * @param request
     * @param response
     * @param model
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public String logout(HttpServletRequest request, HttpServletResponse response, ModelMap model) throws IOException {
        String path = request.getParameter("path");
        if (Strings.isEmpty(path)) {
            path = "/";
        }
        UserInfo userInfo = new UserInfo();
        userInfo.setUserId(LoginUser.COEUS_ANONYMOUS_USER_ID);
        LoginUser loginUser = new LoginUser(userInfo);
        loginUser.setGuest(true);
        LoginContext.setLoginUser(loginUser);
        UrlUtils.redirect(request, response, path);
        return null;
    }

    /**
     * 登录
     *
     * @param request
     * @param response
     * @param model
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/doLogin", method = RequestMethod.POST)
    public String doLogin(HttpServletRequest request, HttpServletResponse response, ModelMap model) throws IOException {
        int role = 40;
        String retMsg = "";
        String retCode = "";
        JSONObject resultMap = new JSONObject();
        //判断用户当前的身份
        String historyUrl = request.getParameter("historyUrl");
        String loginName = request.getParameter("loginName");
        String strPassword = request.getParameter("password");
        String checkCode = (String) request.getSession().getAttribute("checkImageText"); //校验验证码
        String isCheckCode = request.getParameter("isCheckCode");
        String inputCheckCode = request.getParameter("checkCode"); //输入的验证码
        if ("1".equals(isCheckCode) && !inputCheckCode.trim().equals(checkCode)) {
            // 首先验证验证码是否正确
            retCode = HomeException.CHECKCODE_ERROR;
            retMsg = "验证码不正确！";
        }
        if (loginName.isEmpty()) {
            throw new HomeException(HomeException.LOGIN_ERROR, "登录账号不能为空！");
        }
        if (strPassword.isEmpty()) {
            throw new HomeException(HomeException.PASSWORD_NULL, "密码不能为空！");
        }
        try {
            if (Strings.isEmpty(retCode)) {
                List<UserInfo> userInfos = homeService.queryUserByLoginName(loginName);
                UserInfo userInfo = null;
                if (!CollectionUtils.isEmpty(userInfos)) {
                    userInfos = homeService.getUserInfoForLogin(loginName, strPassword);
                    if (!CollectionUtils.isEmpty(userInfos)) {
                        userInfo = userInfos.get(0);
                        retCode = "success";
                    }
                    if ("success".equals(retCode)) {
                        //登陆成功后将图片验证码session清空
                        request.getSession().setAttribute("checkImageText", null);

                        role = userInfo.getRole();

                        if (Strings.isNotEmpty(historyUrl)) {
                            resultMap.put("historyUrl", SecurityUtils.decodeToText(historyUrl));
                        }
                        this.homeService.executeLogin(request, userInfo);
                    } else {
                        retCode = HomeException.PASSWORD_ERROR;
                        retMsg = "密码错误！";
                    }
                } else {
                    retCode = HomeException.USER_NOT_EXIST;
                    retMsg = "用户不存在！";
                }
            }
        } catch (HomeException ex) {
            LOGGER.error(ex.getMessage(), ex);
        }

        resultMap.put("retCode", retCode);
        resultMap.put("retMsg", retMsg);
        resultMap.put("role", role);
        response.setContentType(ConstantStatic.HTTP_JSON_CONTENTTYPE);
        response.getWriter().print(JSONObject.toJSONString(resultMap));
        return null;
    }

    /**
     * 更换验证码.
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/changeImage", method = RequestMethod.POST)
    public String changeImage(ModelMap model) {
        return "home.changeImage";
    }

    /**
     * 获得验证码.
     *
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/getImage")
    public String getImage(HttpServletRequest request, HttpServletResponse response) throws IOException {
        JSONObject resultMap = new JSONObject();
        String str = ImageTools.createImage(response.getOutputStream());
        resultMap.put("str", str);
        response.setContentType("image/jpeg");
        HttpSession httpSession = request.getSession();
        httpSession.setAttribute("checkImageText", str);
        return null;
    }

    /**
     * 用户注册页面
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/register", method = RequestMethod.GET)
    public String register(ModelMap model) {
        return "home.register";
    }

    /**
     * 注册
     *
     * @param request
     * @param response
     * @param model
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/doRegister", method = RequestMethod.POST)
    public String doRegister(HttpServletRequest request, HttpServletResponse response, ModelMap model) throws IOException {
        JSONObject resultMap = new JSONObject();

        String retMsg = "";
        String returnFlag = "false";
        String loginName = request.getParameter("loginName");
        String password = request.getParameter("password");

        if (password.isEmpty()) {
            throw new HomeException(HomeException.PASSWORD_NULL, "密码不能为空！");
        }

        String inputCheckCode = request.getParameter("checkCode"); //输入的验证码
        String checkCode = (String) request.getSession().getAttribute("checkImageText"); //校验验证码
        if (!inputCheckCode.trim().equals(checkCode)) {
            // 首先验证验证码是否正确
            returnFlag = HomeException.CHECKCODE_ERROR;
            retMsg = "验证码不正确！";
        } else {
            try {
                List<UserInfo> userInfos = this.homeService.queryUserByLoginName(loginName);
                if (CollectionUtils.isEmpty(userInfos)) { //不存在
                    UserInfo userInfo = this.homeService.insertRegisterInfo(loginName, password);
                    returnFlag = "success";

                    //注册后自动登录
                    homeService.executeLogin(request, userInfo);

                    //注册成功后，将图片验证码session清空
                    request.getSession().setAttribute("checkImageText", null);
                } else {
                    returnFlag = HomeException.ACCOUNT_ALREADY_EXISTS;
                    retMsg = "账号已存在！";
                }
            } catch (HomeException ex) {
                LOGGER.error(ex.getMessage(), ex);
            }
        }

        resultMap.put("returnCode", returnFlag);
        resultMap.put("retMsg", retMsg);
        response.setContentType(ConstantStatic.HTTP_JSON_CONTENTTYPE);
        response.getWriter().print(JSONObject.toJSONString(resultMap));
        return null;
    }
}
