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.User;
import cn.hnthyy.thmz.service.thmz.UserService;
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;
    /**
     * 用户信息修改
     * @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;
    }
}
