package com.yihu.hos.system.controller;

import com.yihu.hos.system.model.SystemUser;
import com.yihu.hos.system.model.SystemUserRole;
import com.yihu.hos.system.service.UserManager;
import com.yihu.hos.web.framework.model.Result;
import com.yihu.hos.web.framework.util.PKUtil;
import com.yihu.hos.web.framework.util.controller.BaseController;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * 用户管理
 * Created by hzp on 2016/01/11.
 */
@RequestMapping("/user")
@Controller
public class UserController extends BaseController {
    @Resource(name = UserManager.BEAN_ID)
    private UserManager userManager;


    /**
     * 用户管理界面
     *
     * @param model
     * @return
     */
    @RequestMapping("/initial")
    public String roleInitial(Model model) {
        model.addAttribute("contentPage", "system/user/user");
        return "partView";
    }

    /**
     * 用户列表
     *
     * @param request
     * @return
     */
    @RequestMapping("getUserList")
    @ResponseBody
    public Result getUserList(HttpServletRequest request) {
        try {
            Map<String, Object> params = new HashMap<>();
            String name = request.getParameter("name");
            params.put("name", name);
            String page = StringUtils.isEmpty(request.getParameter("page")) ? "1" : request.getParameter("page");
            String rows = StringUtils.isEmpty(request.getParameter("rows")) ? "10" : request.getParameter("rows");

            params.put("page", page);
            params.put("rows", rows);
            return userManager.getUserList(params);
        } catch (Exception ex) {
            return Result.error(ex.getMessage());
        }
    }

    /**
     * 用户编辑界面
     */
    @RequestMapping("editorUser")
    public String editorUser(Model model, String userId) {
        try {
            //是否编辑
            if (userId != null && userId.length() > 0) {
                //获取菜单信息
                SystemUser user = userManager.getUserById(userId);
                model.addAttribute("model", user);
                model.addAttribute("userId", userId);
            }
            model.addAttribute("contentPage", "system/user/editorUser");
            return "pageView";
        } catch (Exception ex) {
            return "error";
        }
    }


    /**
     * 用户编辑界面
     */
    @RequestMapping("roleDistribute")
    public String roleDistribute(Model model, String userId) {
        try {
            //是否编辑
            if (userId != null && userId.length() > 0) {
                //获取菜单信息
                SystemUser user = userManager.getUserById(userId);
                List<SystemUserRole> userRoles = userManager.getUserRoleByUserId(userId);
                String roleId = "";

                if(userRoles != null)
                {
                    for(SystemUserRole userRole:userRoles)
                    {
                        roleId += (StringUtils.isEmpty(roleId)?"":",") + userRole.getRoleId();
                    }
                }

                model.addAttribute("roleId", roleId);
                model.addAttribute("model", user);
                model.addAttribute("userId", userId);
            }
            model.addAttribute("contentPage", "system/user/roleDistribute");
            return "pageView";
        } catch (Exception ex) {
            return "error";
        }
    }

    /**
     * 新增用户
     */
    @RequestMapping("addUser")
    @ResponseBody
    public Result addUser(HttpServletRequest request) {
        try {
            SystemUser obj = new SystemUser();
            BeanUtils.populate(obj, request.getParameterMap());
            String password = request.getParameter("password");
            String passwordTwo = request.getParameter("passwordTwo");
            if (!passwordTwo.equals(password)) {
                throw new Exception("密码不一致");
            }
            String saltValu = PKUtil.getUuid();
            obj.setSaltValue(saltValu);
            obj.setActivated(SystemUser.ACTIVATED_FORBIDDEN);//未激活
            obj.setPassword(DigestUtils.md5Hex(password + saltValu));
            return userManager.addUser(obj);
        } catch (Exception ex) {
            ex.printStackTrace();
            return Result.error("新增用户异常，异常信息：\n"+ex.getMessage());
        }
    }

    /**
     * 修改用户
     */
    @RequestMapping("updateUser")
    @ResponseBody
    public Result updateUser(HttpServletRequest request) {
        try {
            SystemUser obj = new SystemUser();
            BeanUtils.populate(obj, request.getParameterMap());

            return userManager.updateUser(obj);
        } catch (Exception ex) {
            ex.printStackTrace();
            return Result.error("修改用户异常，异常信息：\n"+ex.getMessage());
        }
    }

    /**
     * 修改菜单状态
     */
    @RequestMapping("activityUser")
    @ResponseBody
    public Result activityUser(String userid, String flag) {
        try {
            return userManager.activityUser(userid, flag);
        } catch (Exception ex) {
            ex.printStackTrace();
            return Result.error("修改菜单状态异常，异常信息：\n"+ex.getMessage());

        }
    }

    /**
     * 密码重置
     */
    @RequestMapping("resetPassword")
    @ResponseBody
    public Result resetPassword(HttpServletRequest request) {
        try {
            String userid = request.getParameter("userid");
            return userManager.resetPassword(userid);
        } catch (Exception ex) {
            ex.printStackTrace();
            return Result.error("密码异常，异常信息：\n"+ex.getMessage());
        }
    }
    /**
     * 修改密码界面
     */
    @RequestMapping("renewPassword")
    public String renewPassword(Model model) {
        try {

            model.addAttribute("model",null);

            model.addAttribute("contentPage", "system/user/changePassword");
            return "pageView";
        } catch (Exception ex) {
            return "error";
        }
    }
    /**
     * 修改密码
     */
    @RequestMapping("changePassword")
    @ResponseBody
    public Result changePassword(HttpServletRequest request) {
        try {
            HttpSession session = request.getSession();
            String s="username";
            SystemUser user = (SystemUser) session.getAttribute("userInfo");
            String oldPassword = request.getParameter("oldPassword");

            userManager.getUserByLoginCode(user.getLoginCode()).getSaltValue();
            String test= DigestUtils.md5Hex(oldPassword +  userManager.getUserByLoginCode(user.getLoginCode()).getSaltValue());
            if(!userManager.getUserByLoginCode(user.getLoginCode()).getPassword().equals(test)){
                return Result.error("旧密码输入错误");
            }
            String newPassword = request.getParameter("newPassword");
           return userManager.changePassword(userManager.getUserByLoginCode(user.getLoginCode()).getId(), newPassword);


        } catch (Exception ex) {
            ex.printStackTrace();
            return Result.error("修改密码异常，异常信息：\n"+ex.getMessage());

        }
    }

    /**
     * 删除用户
     */
    @RequestMapping("deleteUser")
    @ResponseBody
    public Result deleteUser(String userid) {
        try {
            return userManager.deleteUser(userid);
        } catch (Exception ex) {
            ex.printStackTrace();
            return Result.error("用户删除异常，异常信息：\n"+ex.getMessage());
        }
    }


    @RequestMapping("/userRoleDistribute")
    @ResponseBody
    public Result userRoleDistribute(HttpServletRequest request,String userId,String roleId)
    {
        try {
            return userManager.userRoleDistribute(userId,roleId);
        } catch (Exception ex) {
            ex.printStackTrace();
            return Result.error("角色分配异常，异常信息：\n"+ex.getMessage());
        }
    }
}
