package com.weiqi.mis.contorller;

import com.weiqi.mis.MD5Util;
import com.weiqi.mis.UserService;
import com.weiqi.mis.annotation.LoginType;
import com.weiqi.mis.domain.AdminUserInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * 登录转发
 */
@Controller
@RequestMapping(value = "mis")
public class BaseController {
    private static final Logger logger = LoggerFactory.getLogger(BaseController.class);

    @Autowired
    UserService userService;

    @RequestMapping("/index")
    @LoginType
    public Object toIndex(){
        return "sms/index";
    }

    @RequestMapping("/login")
    public Object login(){
        //System.out.println("sms/login");
        return "sms/login";
    }

    /**
     * 登录接口
     * @param request
     * @param response
     * @param token
     * @return
     */
    @RequestMapping("/toLogin")
    @ResponseBody
    public Object toLogin(HttpServletRequest request,HttpServletResponse response, String username, String token){
        logger.info("username={},token={}",username,token);
        List<AdminUserInfo> userInfoList = userService.getUserInfo(username, token);
        if(userInfoList!=null&&userInfoList.size()>=1){
            AdminUserInfo adminUserInfo = userInfoList.get(0);
            if(adminUserInfo.getUserName().equals(username)&&token.equals(adminUserInfo.getPassword())){
                HttpSession session = request.getSession();
                session.setAttribute("USER", MD5Util.md5(token)); // "USER" 是我们给Session中存储的用户名的键
                session.setMaxInactiveInterval(30*60); // 比如这里设置为30分钟
                return "1";
            }else {
                //验证失败
                return "0";
            }

        }
        return "0";

//        HttpSession session = request.getSession();

//        if (StringUtils.isNotBlank(token) && "dxadmin".equals(token)){
//
//
//            //验证成功
////            session.setAttribute("Token","smsadmin");
//            CookieUtil.addCookie(response, "DXToken", MD5Util.md5("dsadmin"), "/metrics");
////            session.setMaxInactiveInterval(1 * 60 * 60);
//            return "1";
//        }else {
//            //验证失败
//            return "0";
//        }
    }


}
