package cn.ftebox.controller;

import cn.ftebox.entity.Blog;
import cn.ftebox.entity.Blogger;
import cn.ftebox.service.BloggerService;
import cn.ftebox.util.CryptographyUtil;
import cn.ftebox.util.ResponseUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 博主登录相关
 */
@Controller
@RequestMapping("/blogger")
public class BloggerController {
    @Resource
    private BloggerService bloggerService;

    @RequestMapping("/login.do")
    public String login(Blogger blogger,HttpServletRequest request) {
        /**用户名*/
        String userName = blogger.getUserName();
        /**密码*/
        String password = blogger.getPassword();
        String pw = CryptographyUtil.md5(password, "java1234");

        /**Subject*/
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(userName, pw);
        try {
            // 传递token个shiro的realm
            subject.login(token);
            return "redirect:/admin/main.jsp";
        }catch (Exception e){
            e.printStackTrace();
            request.setAttribute("blogger",blogger);
            request.setAttribute("errorInfo","用户名密码错误！");
        }
        return "login";
    }

    @RequestMapping({"/register.do"})
    public String register(Blogger blogger, HttpServletResponse response) throws IOException {
        blogger.setPassword(CryptographyUtil.md5(blogger.getPassword(),"java1234"));
        int resultTotal = bloggerService.insert(blogger);
        JSONObject result = new JSONObject();
        if (resultTotal > 0) {
            result.put("success", Boolean.valueOf(true));
        } else {
            result.put("error", Boolean.valueOf(false));
        }
        ResponseUtil.write(response, result);
        return null;
    }
}
