package com.lovecoding.mvc.contorller;

import com.lovecoding.mvc.dao.BookDao;
import com.lovecoding.mvc.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;
import java.util.Map;

/**
 * 必须使用 RustFul 风格的操作
 * 并且得又 JSP 页面
 */

@Controller
@RequestMapping("/book")
public class BookContorller {

    @Autowired
    BookService bookService;

    @PostMapping("/")
    public String add(BookDao book){
        int add = bookService.add(book);
        return "/success.jsp";
    }

    @DeleteMapping("/{bookId}")
    @ResponseBody
    public String del(@PathVariable Long bookId){
        bookService.del(bookId);
        return "操作成功";
    }

    @PutMapping("/")
    @ResponseBody
    public String update(BookDao book){
        bookService.update(book);
        return "操作成功！";
    }

    @GetMapping({"/{bookId}", "/"})
    public String get(@PathVariable(required = false) Long bookId, Model model){

        if ( bookId == null ) {
            List<Map<String, Object>> bookDaos = bookService.get();
            model.addAttribute( "books", bookDaos );
            return "/list.jsp";
        }
        BookDao bookDao = bookService.get(bookId);
        model.addAttribute("book", bookDao);
        return "/update.jsp";

    }


}
