package cn.hnthyy.thmz.controller;

import cn.hnthyy.thmz.Utils.JsonUtil;
import cn.hnthyy.thmz.Utils.Md5Util;
import cn.hnthyy.thmz.Utils.TokenUtil;
import cn.hnthyy.thmz.comment.UserLoginToken;
import cn.hnthyy.thmz.entity.thmz.Role;
import cn.hnthyy.thmz.entity.thmz.User;
import cn.hnthyy.thmz.entity.thmz.UserRoleRelation;
import cn.hnthyy.thmz.service.thmz.RoleService;
import cn.hnthyy.thmz.service.thmz.UserRoleRelationService;
import cn.hnthyy.thmz.service.thmz.UserService;
import cn.hnthyy.thmz.vo.UserRoleRelationVo;
import cn.hnthyy.thmz.vo.UserVo;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private UserRoleRelationService userRoleRelationService;
    @Autowired
    private RoleService roleService;
    /**
     * 用户信息修改
     * @param userParam
     * @return
     */
    @UserLoginToken
    @RequestMapping(value = "/modify-user", method = RequestMethod.POST)
    public Map<String, Object> modifyUser(HttpServletRequest httpServletRequest, @RequestBody User userParam) {
        Map<String, Object> resultMap = new HashMap<>();
        String message = "用户信息修改成功！";
        if (userParam == null) {
            resultMap.put("code", -1);
            resultMap.put("message", "用户信息修改失败,用户信息参数错误");
            return resultMap;
        }
        String token = TokenUtil.getToken(httpServletRequest);
        if (StringUtils.isBlank(token)) {
            resultMap.put("code", -1);
            resultMap.put("message", "用户信息修改失败,用户Token不存在");
            return resultMap;
        }
        DecodedJWT decodedJWT=TokenUtil.parseJWT(token);
        User tokenUser=(User)JsonUtil.jsontoObject(decodedJWT.getSubject(),User.class);
        if(tokenUser==null || tokenUser.getId()==null){
            resultMap.put("code", -1);
            resultMap.put("message", "用户信息修改失败,用户主键不能为空");
            return resultMap;
        }
        if(StringUtils.isNotBlank(userParam.getOldPassword())){
            try {
                if (!Md5Util.checkPassword(userParam.getOldPassword(), tokenUser.getPassword())) {
                    resultMap.put("code", -1);
                    resultMap.put("message", "密码重置失败,原密码密码错误，请重新输入");
                    return resultMap;
                }
                userParam.setPassword(Md5Util.encoderByMd5(userParam.getPassword()));
                message = "用户密码重置成功,即将注销登录，请重新登录！";
            } catch (Exception e) {
                log.error("密码重置错误，错误信息：{}", e.getMessage());
                resultMap.put("code", -1);
                resultMap.put("message", "重置密码失败,系统发生未知错误，请重稍后重试或联系管理员");
                return resultMap;
            }
        }
        userParam.setId(tokenUser.getId());
        Integer num= userService.updateUser(userParam);
        if (num == null) {
            resultMap.put("code", -1);
            resultMap.put("message", "用户信息修改失败,请稍后重试或联系管理员");
            return resultMap;
        }
        resultMap.put("code", 0);
        resultMap.put("message", message);
        return resultMap;
    }


    /**
     * 用户信息查询
     * @return
     */
    @UserLoginToken
    @RequestMapping(value = "/user-info", method = RequestMethod.POST)
    public Map<String, Object> userInfo(HttpServletRequest httpServletRequest) {
        Map<String, Object> resultMap = new HashMap<>();
        String token = TokenUtil.getToken(httpServletRequest);
        if (StringUtils.isBlank(token)) {
            resultMap.put("code", -1);
            resultMap.put("message", "用户信息查询失败,用户Token不存在");
            return resultMap;
        }
        DecodedJWT decodedJWT=TokenUtil.parseJWT(token);
        User tokenUser=(User)JsonUtil.jsontoObject(decodedJWT.getSubject(),User.class);
        if(tokenUser==null || tokenUser.getId()==null){
            resultMap.put("code", -1);
            resultMap.put("message", "用户信息查询失败,用户主键不能为空");
            return resultMap;
        }
        User userDb= userService.queryUserById(tokenUser.getId());
        if (userDb == null) {
            resultMap.put("code", -1);
            resultMap.put("message", "用户信息查询失败,用户不存在");
            return resultMap;
        }
        resultMap.put("code", 0);
        resultMap.put("message", "用户信息查询成功！");
        resultMap.put("data", userDb);
        return resultMap;
    }


    /**
     * 获取当前登录用户的姓名
     * @return
     */
    @UserLoginToken
    @RequestMapping(value = "/getUserName", method = RequestMethod.GET)
    public Map<String, Object> getUserName(HttpServletRequest httpServletRequest) {
        Map<String, Object> resultMap = new HashMap<>();
        String token = TokenUtil.getToken(httpServletRequest);
        DecodedJWT decodedJWT=TokenUtil.parseJWT(token);
        User tokenUser=(User)JsonUtil.jsontoObject(decodedJWT.getSubject(),User.class);
        if(tokenUser==null || tokenUser.getId()==null){
            resultMap.put("code", -1);
            resultMap.put("message", "用户信息查询失败,用户主键不能为空");
            return resultMap;
        }
        User userDb= userService.queryUserById(tokenUser.getId());
        if (userDb == null) {
            resultMap.put("code", -1);
            resultMap.put("message", "用户信息查询失败,用户不存在");
            return resultMap;
        }
        resultMap.put("code", 0);
        resultMap.put("data", userDb);
        resultMap.put("message", "用户信息查询成功！");
        return resultMap;
    }



    /**
     * 获取用户树
     * @return
     */
    @UserLoginToken
    @RequestMapping(value = "/getUserTree", method = RequestMethod.GET)
    public Map<String, Object> getUserTree() {
        Map<String, Object> resultMap = new HashMap<>();

        List<User> userList= userService.queryAllUser();
        List<Map<String,Object>> treeList = new ArrayList<>();
        for (User user : userList){
            Map<String,Object> temp = new HashMap<>();
            temp.put("text",user.getUserName());
            temp.put("dataId",user.getId());
            treeList.add(temp);
        }
        resultMap.put("code", 0);
        resultMap.put("data", treeList);
        resultMap.put("message", "用户树查询成功！");
        return resultMap;
    }

    /**
     * 获取所有的用户
     *
     * @return
     */
    @UserLoginToken
    @RequestMapping(value = "/getUserPage", method = {RequestMethod.GET, RequestMethod.POST})
    public Map<String, Object> getUserPage(@RequestBody UserVo userVo) {
        Map<String, Object> resultMap = new HashMap<>();
        try {
            ArrayList<UserRoleRelationVo> userRoleRelationVos = new ArrayList<>();
            int total = userService.countUser(userVo);
            List<User> users = userService.queryUserPage(userVo);
            for (User user : users) {//通过user基础信息查询关联角色
                UserRoleRelationVo userRoleRelationVo = new UserRoleRelationVo();
                List<UserRoleRelation> userRoleRelations = userRoleRelationService.queryByUserId(user.getId());
                StringBuffer roleIds = new StringBuffer();
                StringBuffer roleNames = new StringBuffer();
                String str = ",";
                for (int i = 0; i < userRoleRelations.size(); i++) {//多个角色
                    Role role = roleService.queryById(userRoleRelations.get(i).getRoleId());
                    if(i != 0){
                        roleIds.append(str+userRoleRelations.get(i).getRoleId());
                        roleNames.append(str+role.getRoleName());
                    }else{
                        roleIds.append(userRoleRelations.get(i).getRoleId());
                        roleNames.append(role.getRoleName());
                    }
                }
                if (userRoleRelations.size() > 0) {
                    userRoleRelationVo.setRoleIds(roleIds.toString());
                    userRoleRelationVo.setCreateId(userRoleRelations.get(0).getCreateId());
                    userRoleRelationVo.setCreateTime(userRoleRelations.get(0).getCreateTime());
                    userRoleRelationVo.setRoleName(roleNames.toString());
                    userRoleRelationVo.setCreateName(userService.queryUserById(userRoleRelations.get(0).getCreateId()).getUserName());
                }
                userRoleRelationVo.setUser(user);
                userRoleRelationVos.add(userRoleRelationVo);
            }
            resultMap.put("code", 0);
            resultMap.put("message", "查询所有用户成功");
            resultMap.put("total", total);
            resultMap.put("data", userRoleRelationVos);
            return resultMap;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("查询所有用户失败，错误信息{}", e.getMessage());
            resultMap.put("code", -1);
            resultMap.put("message", "查询所有用户失败");
            return resultMap;
        }
    }

    /**
     * 根据主键查询用户
     *
     * @param id
     * @return
     */
    @UserLoginToken
    @RequestMapping(value = "/getUser", method = {RequestMethod.GET})
    public Map<String, Object> getUser(@RequestParam Long id) {
        Map<String, Object> resultMap = new HashMap<>();
        try {
            UserRoleRelationVo userRoleRelationVo = new UserRoleRelationVo();
            User user = userService.queryUserById(id);
            userRoleRelationVo.setUser(user);
            List<UserRoleRelation> userRoleRelations = userRoleRelationService.queryByUserId(id);
            StringBuffer roleIds = new StringBuffer();
            for (UserRoleRelation userRoleRelation : userRoleRelations) {
                roleIds.append(userRoleRelation.getRoleId());
            }
            if (userRoleRelations.size() > 0) {
                userRoleRelationVo.setRoleIds(roleIds.toString());
                userRoleRelationVo.setCreateId(userRoleRelations.get(0).getCreateId());
                userRoleRelationVo.setCreateTime(userRoleRelations.get(0).getCreateTime());
            }
            if (user == null) {
                resultMap.put("code", -1);
                resultMap.put("message", "根据主键查询用户失败，不存在该用户");
                return resultMap;
            }
            resultMap.put("code", 0);
            resultMap.put("message", "根据主键查询用户成功");
            resultMap.put("data", userRoleRelationVo);
            return resultMap;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("根据主键查询用户失败，错误信息{}", e.getMessage());
            resultMap.put("code", -1);
            resultMap.put("message", "根据主键查询用户失败");
            return resultMap;
        }
    }


    /**
     * 保存用户与角色的关系
     *
     * @param userRoleRelationVo
     * @return
     */
    @UserLoginToken
    @RequestMapping(value = "/saveUserRoleRelation", method = {RequestMethod.POST})
    public Map<String, Object> saveUserRoleRelation(@RequestBody UserRoleRelationVo userRoleRelationVo, HttpServletRequest httpServletRequest) {
        Map<String, Object> resultMap = new HashMap<>();
        try {
            if (userRoleRelationVo == null) {
                resultMap.put("code", -1);
                resultMap.put("message", "保存用户与角色关系失败,参数为空");
                return resultMap;
            }
            User tokenUser = TokenUtil.getUser(httpServletRequest);
            //保存用户角色关联
            userRoleRelationService.saveUserRoleRelation(userRoleRelationVo,tokenUser.getId());
            resultMap.put("code", 0);
            resultMap.put("message", "保存用户与菜单关系成功");
            return resultMap;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("保存用户与菜单关系失败，错误信息{}", e.getMessage());
            resultMap.put("code", -1);
            resultMap.put("message", "保存用户与菜单关系失败");
            return resultMap;
        }
    }
}
