package vc.kotori.controller.demo;

import org.apache.commons.io.FileUtils;
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.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import vc.kotori.framework.common.ResponseCode;
import vc.kotori.framework.common.ServerResponse;
import vc.kotori.framework.common.page.PagingResult;
import vc.kotori.support.demo.entity.User;
import vc.kotori.support.demo.service.UserService;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

@Controller
@RequestMapping("/demo")
public class ControllerDemo {

    @Autowired
    private UserService userService;

    @RequestMapping(value = "/user/test/json", method = RequestMethod.GET)
    @ResponseBody
    public ServerResponse<User> saveTestJson() throws Exception {
        //测试json返回
        //TODO 尝试用shiro做权限管理
        return ServerResponse.createBySuccessMessage(ResponseCode.SUCCESS.getDesc());
    }

    @RequestMapping(value = "/user/test/json/{page}/{rows}", method = RequestMethod.GET)
    @ResponseBody
    public ServerResponse<PagingResult<User>> savePageJson(@PathVariable("page") int page,@PathVariable("rows") int rows) throws Exception {
        return ServerResponse.createBySuccess(ResponseCode.SUCCESS.getDesc(),this.userService.testPage(page, rows));//测试分页
    }

    @RequestMapping(value = "/user/test", method = RequestMethod.POST)
    public ModelAndView saveTest(User user) throws Exception {
        ModelAndView modelAndView = new ModelAndView("/demo/success");
        System.out.println(user.getUsername());
        userService.test(user);
        return modelAndView;
    }

    /**
     *
     * redirect:重定向时，浏览器每发送一次请求，WEB容器都会重新创建新的request和response对象，所以请求之间不能共享信息，
     *      即不能在请求中访问到他之前请求中的参数和属性的值。url会改变
     *      重定向可以跳转到任意服务器，可以用在系统间的跳转。
     * forward:请求转发时，从发送第一次到最后一次请求的过程中，WEB容器只创建一次request和response对象,
     *      请求之间始终共享这两个对象，所以每个请求可以访问他之前请求中的参数和属性的值;
     *      请求转发只需要请求一次服务器，可以提高访问速度。
     *
     * 请求重定向以redirect:开头，请求转发以forward:开头;
     * return new ModelAndView("redirect:/toList");
     * return "redirect:/toList ";
     */
//    @RequestMapping(value = "/userVo/save", method = RequestMethod.POST)
//    public ModelAndView saveUser(UserVo userVo) throws Exception {
//        ModelAndView modelAndView = new ModelAndView("forward:/demo/success");//这里的请求应该是到方法
//        modelAndView.addObject("name", userVo.getUsername());
//        System.out.println(userVo.getUsername());
//        return modelAndView;
//    }
    @RequestMapping(value = "/user/save3", method = RequestMethod.POST)
    public ModelAndView saveUser3(User user) throws Exception {//<hello2需要改成post>
        ModelAndView modelAndView = new ModelAndView("forward:/demo/hello2");//这里是可以的,直接把页面请求给hello2处理了
//        modelAndView.addObject("name", userVo.getUsername());//这里没有用
        System.out.println(user.getUsername());
        return modelAndView;
    }
    //可以设置下RequestMappingHandlerAdapter 的ignoreDefaultModelOnRedirect属性,这样可以提高效率，避免不必要的检索
    @RequestMapping(value="/user/save2",method=RequestMethod.POST)
    public String testRedirect(RedirectAttributes attr) throws UnsupportedEncodingException {
        attr.addAttribute("name", "kotori");
//        attr.addAttribute("ds", URLEncoder.encode("喵喵喵", "utf-8"));
//        attr.addFlashAttribute("name1", "b");//这个参数不会被加载url后看见
        return "redirect:/demo/hello2";
    }
    /**
     *
     * 1. 使用RequestMapping注解来映射请求的URL
     * 2. 返回值会通过视图解析器解析为实际的物理视图, 对于InternalResourceViewResolver视图解析器，会做如下解析
     *    通过prefix+returnVal+suffix 这样的方式得到实际的物理视图，然后会转发操作
     *    "/WEB-INF/views/success.jsp"
     */
    @RequestMapping("/hello")
    public String hello(){
        System.out.println("hello world");
        return "demo/controllerDemoTest1";
    }

    //  /demo/hello2?name=kotori
    @RequestMapping(value = "/hello2",method = RequestMethod.GET)
    public String hello2(@RequestParam("name") String name, Model model) {
        model.addAttribute("name", name);
        return "demo/controllerDemoTest1";
    }

    //  /demo/hello3/kotori
    @RequestMapping(value = "/hello3/{name}",method = RequestMethod.GET)
    public String hello3(@PathVariable("name") String name, Model model) {//Map<String,Object> model
//        model.put("name", name);
        model.addAttribute(name);
        return "demo/controllerDemoTest1";
    }

    //  /demo/hello4?name=kotori
    @RequestMapping(value = "/hello4", method = RequestMethod.GET)
    public String hello4(HttpServletRequest httpServletRequest) {
        String name = httpServletRequest.getParameter("name");
        httpServletRequest.setAttribute("name", name);
        return "demo/controllerDemoTest1";
    }

    @RequestMapping(value = "/testUpload",method = RequestMethod.POST)
    public String testUpload(MultipartFile file) {
        if (!file.isEmpty()) {
            try {
                FileUtils.copyInputStreamToFile(file.getInputStream(), new File("/Users/kotori/html/",System.currentTimeMillis()+""));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return "demo/success";
    }


}
