package com.sys.controller;

import com.cku.core.PageBeanResult;
import com.cku.core.RESTResponse;
import com.cku.util.MD5Generator;
import com.cku.util.PageBean;
import com.cku.util.ServletUtils;
import com.sys.model.SysUser;
import com.sys.service.SysUserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.io.IOException;
import java.util.*;

/**
 * Created by user on 2016/5/13.
 */
@Controller
@RequestMapping("sys")
public class SystemController {

    @Autowired
    private SysUserServiceImpl sysUserService;
    @RequestMapping("/addUser")
    public ModelAndView addUser(HttpServletRequest request, HttpServletResponse response, SysUser sysUser, ModelMap modelMap){
        //过滤名称重复
        List<SysUser> list = sysUserService.selectByUserName(sysUser.getUserName());
        if(list!=null && list.size()>0){
            modelMap.addAttribute("message","添加用户失败!");
            return new ModelAndView("error",modelMap);
        }
        Random rad=new Random();
        String salt = rad.nextInt(1000)+"";
        sysUser.setUserSalt(salt);
        sysUser.setCreateDate(new Date());
        sysUser.setLoginCount(0);
        sysUser.setIsdel(0);
        String m5pwd = MD5Generator.generate(sysUser.getPassword()+salt);
        sysUser.setPassword(m5pwd);
        sysUserService.insertSelective(sysUser);
        modelMap.addAttribute("toPage","sys/listUser.do");
        modelMap.addAttribute("message","添加用户成功!");
        return new ModelAndView("success",modelMap);
    }
    @RequestMapping(value = "/preAddUser")
    public ModelAndView preAddUser() {
        ModelAndView _modelAndView = new ModelAndView("sys/user/addUser");
        SysUser sysUser = new SysUser();
        return _modelAndView.addObject("sysUser", sysUser);
    }

    @RequestMapping("/listUser")
    public ModelAndView listUser(HttpServletRequest request, HttpServletResponse response,ModelMap modelMap){
    	HttpSession session = request.getSession();
    	SysUser sys = (SysUser)session.getAttribute("user");
    	ModelAndView mv = new ModelAndView();
    	if(sys!=null && sys.getRole()==1){
    		String userName = ServletUtils.getParameter(request, "userName",null);
            PageBean pb = ServletUtils.getParameterBean(request);
            PageBeanResult<SysUser> s = sysUserService.selectAll(userName,pb);
            modelMap.addAttribute("pageList",s);
            mv = new ModelAndView("sys/user/listUser",modelMap);
    	} else {
    		modelMap.addAttribute("message","无访问权限!");
    		mv = new ModelAndView("error",modelMap);
    	}
        return mv;
    }
    @RequestMapping("/delUser")
    @ResponseBody
    public void delUser(HttpServletRequest request, HttpServletResponse response,ModelMap modelMap) throws IOException {
        RESTResponse result = null;
        try {
            Long id = ServletUtils.getParameterLong(request,"id",(long)0);
            SysUser sysUser = sysUserService.selectByPrimaryKey(id);

            if(sysUser!=null &&sysUser.getIsdel()==0 ){
                sysUser.setIsdel(1);
                sysUserService.updateByPrimaryKeySelective(sysUser);
                result=new RESTResponse("items","success");
            }

        }catch (Exception e){
            result = new RESTResponse(e);
        }
        ServletUtils.writeResponse(response, result);
    }
    @RequestMapping("/login")
    public ModelAndView login(HttpServletRequest request, HttpServletResponse response,@RequestParam Map<String, Object> params,ModelMap modelMap){
        ModelAndView result = null;
        String userName = (String)params.get("userName");
        List<SysUser> list = sysUserService.selectByUserName(userName);
        if(list==null || list.size()==0){
            modelMap.addAttribute("message","用户不存在！!");
            result = new ModelAndView("error",modelMap);
        }else{
            String password = (String)params.get("password");
            String m5pwd = MD5Generator.generate(password+list.get(0).getUserSalt());
            if(m5pwd.equals(list.get(0).getPassword())){
                SysUser  sysUser= list.get(0);
                modelMap.addAttribute("toPage","index.jsp");
                modelMap.addAttribute("message","登陆成功!");
                result = new ModelAndView("success",modelMap);
                sysUser.setLastLoginDate(new Date());
                sysUser.setLoginCount(sysUser.getLoginCount()+1);
                sysUserService.updateByPrimaryKeySelective(sysUser);
                request.getSession().setAttribute("user",list.get(0));
                request.getSession().setAttribute("userId", sysUser.getUserId());
            }else{
                modelMap.addAttribute("message","用户名或密码不正确!");
                result = new ModelAndView("error",modelMap);
            }
        }
        return result;
    }
    @RequestMapping("/logout")
    public ModelAndView logout(HttpServletRequest request, HttpServletResponse response,ModelMap modelMap){
        ModelAndView result = null;
        modelMap.addAttribute("toPage","index.jsp");
        modelMap.addAttribute("message","退出登录成功!");
        result = new ModelAndView("success",modelMap);
        request.getSession().removeAttribute("user");
        return result;
    }
}
