package com.forum.controller.admin;


import com.forum.entity.User;
import com.forum.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/admin")
public class AdminLoginController {

    @Autowired
    private UserService userService;
    @Autowired
    private ForumService forumService;
    @Autowired
    private TagService tagService;
    @Autowired
    private NoticeService noticeService;

    @Autowired
    private LinkService linkService;

    @GetMapping()
    public String loginPage() {
        return "admin/admin-login";
    }

    @PostMapping("/login")
    public String login(@RequestParam String username,
                        @RequestParam String password,
                        HttpSession session,
                        RedirectAttributes attributes, Model model) {
        User admin = userService.checkUser(username, password);

        if (admin != null && admin.getType() == 1) {
            session.setAttribute("admin", admin);
            return "admin/admin-index";
        } else {
            attributes.addFlashAttribute("msgs", "用户名或密码错误");
            return "redirect:/admin";
        }
    }

    @RequestMapping("/welcome")
    public String welcome(Model model) {
        int count = userService.count();
        int a = forumService.countForum();
        int b = forumService.countView();
        int c = tagService.countTag();
        int d = noticeService.countNotice();
        int e = linkService.countLink();

        model.addAttribute("userCount", count);
        model.addAttribute("forumCount", a);
        model.addAttribute("forumView", b);
        model.addAttribute("tagCount", c);
        model.addAttribute("noticeCount", d);
        model.addAttribute("linkCount", e);
        return "admin/welcome";
    }

    @GetMapping("/logout")
    public String logout(HttpSession session) {
        session.removeAttribute("admin");
        return "redirect:/admin";
    }
}
