package com.mobvista.apptag.controller;

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

import javax.servlet.http.HttpSession;

import com.github.pagehelper.PageHelper;
import com.mobvista.apptag.config.WebSecurityConfig;
import com.mobvista.apptag.entity.User;
import com.mobvista.apptag.mapper.UserDao;
import com.mobvista.apptag.service.UserService;
import com.mobvista.apptag.utils.PageUtil;
import com.mobvista.apptag.utils.Query;
import com.mobvista.apptag.utils.R;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttribute;

/**
 * @author wangjf
 */
@Controller
public class UserController {

    public static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private UserService userService;

    @Autowired
    private UserDao userDao;

    @GetMapping("/index")
    public String index(@SessionAttribute(WebSecurityConfig.SESSION_KEY) String userName, Model model) {
        User user = userDao.find(userName);
        model.addAttribute("user", user);
        return "index";
    }

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

    @PostMapping(path = "/loginPost")
    @ResponseBody
    R loginPost(@RequestParam(name = "username") String username, @RequestParam(name = "password") String password,
            HttpSession session) {
        if (!userService.validate(username, password)) {
            return R.error("用户名或密码错误，请重新登录！");
        }
        // 设置session
        session.setAttribute(WebSecurityConfig.SESSION_KEY, username);
        return R.ok();
    }

    @GetMapping("/logout")
    public String logout(HttpSession session) {
        // 移除session
        session.removeAttribute(WebSecurityConfig.SESSION_KEY);
        return "redirect:/login";
    }

    @GetMapping("/user/edit")
    String edit(@RequestParam(name = "userId") String userId, Model model) {
        User user = userDao.find(userId);
        model.addAttribute("user", user);
        return "user/edit";
    }

    @PostMapping("/user/update")
    @ResponseBody
    R update(@SessionAttribute(WebSecurityConfig.SESSION_KEY) String userName, @RequestParam Map<String, Object> pMap) {
        User user1 = userDao.find(pMap.get("userId").toString());
        user1.setState(Integer.parseInt(pMap.get("state").toString()));
        user1.setRole(Integer.parseInt(pMap.get("role").toString()));
        if (userDao.save(user1)) {
            return R.ok();
        } else {
            return R.error(1, "保存失败！");
        }
    }

    @GetMapping("/user/add")
    String add() {
        return "user/add";
    }

    @PostMapping("/user/add")
    @ResponseBody
    R add(@SessionAttribute(WebSecurityConfig.SESSION_KEY) String userName, @RequestParam Map<String, Object> uMap) {

        if (userService.createUser(uMap, userName)) {
            return R.ok();
        } else {
            return R.error(1, "保存失败！");
        }

    }

    @GetMapping("/user")
    public String list() {
        return "user/list";
    }

    @PostMapping("/user/list")
    @ResponseBody
    public PageUtil list(@SessionAttribute(WebSecurityConfig.SESSION_KEY) String username, @RequestBody Query query) {
        PageHelper.startPage(query.getOffset() / query.getLimit() + 1, query.getLimit());
        List<User> users = userDao.list();
        int total = userDao.count();
        PageUtil pageUtil = new PageUtil(users, total);
        return pageUtil;
    }

    @GetMapping("/main")
    String main(@SessionAttribute(WebSecurityConfig.SESSION_KEY) String userId, Model model) {
        User user = userDao.find(userId);
        model.addAttribute("user", user);
        return "main";
    }

    @PostMapping("/user/exit")
    @ResponseBody
    boolean exit(@RequestParam(name = "username") String username) {
        // 存在，不通过，false
        return !userService.exit(username);
    }
}