package com.usky.system.controller.web;


import com.usky.common.core.bean.ApiResult;
import com.usky.common.core.exception.BusinessException;
import com.usky.common.core.util.StringUtils;
import com.usky.common.security.service.TokenService;
import com.usky.common.security.utils.SecurityUtils;
import com.usky.system.domain.SysUser;
import com.usky.system.domain.SysUserPerson;
import com.usky.system.domain.SysUserVO;
import com.usky.system.domain.constants.UserConstants;
import com.usky.system.model.LoginUser;
import com.usky.system.service.ISysUserService;
import com.usky.system.service.SysUserPersonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


/**
 * 个人信息 业务处理
 *
 * @author yq
 */
@RestController
@RequestMapping("/user/profile")
public class SysProfileController extends BaseController {
    @Autowired
    private ISysUserService userService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private SysUserPersonService sysUserPersonService;

    /**
     * 个人信息
     */
    @GetMapping
    public ApiResult profile() {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUserVO user = loginUser.getSysUser();

        SysUserPerson one = sysUserPersonService.lambdaQuery()
                .eq(SysUserPerson::getUserId, user.getUserId())
                .select(SysUserPerson::getIsLoginNotify)
                .one();
        if(one != null) {
            user.setIsLoginNotify(one.getIsLoginNotify());
        }

        Map<String, Object> map = new HashMap<>();
        map.put("user", user);
        map.put("roleGroup", userService.selectUserRoleGroup(loginUser.getUsername()));
        map.put("postGroup", userService.selectUserPostGroup(loginUser.getUsername()));
        return ApiResult.success(map);
    }

    /**
     * 修改用户
     */
    @PutMapping
    public ApiResult updateProfile(@RequestBody SysUser user) {
        if (StringUtils.isNotEmpty(user.getPhonenumber())
                && UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
            throw new BusinessException("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        }
        if (StringUtils.isNotEmpty(user.getEmail())
                && UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
            throw new BusinessException("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUserVO sysUser = loginUser.getSysUser();
        user.setUserId(sysUser.getUserId());
        user.setPassword(null);
        if (userService.updateUserProfile(user) > 0) {

            // 更新登录通知设置
            Integer isLoginNotify = user.getIsLoginNotify();
            if (isLoginNotify != null) {
                sysUserPersonService.lambdaUpdate()
                        .eq(SysUserPerson::getUserId, sysUser.getUserId())
                        .set(SysUserPerson::getIsLoginNotify, isLoginNotify)
                        .update();
            }

            // 更新缓存用户信息
            sysUser.setNickName(user.getNickName());
            sysUser.setPhonenumber(user.getPhonenumber());
            sysUser.setEmail(user.getEmail());
            sysUser.setSex(user.getSex());
            tokenService.setLoginUser(loginUser);
            return ApiResult.success();
        }
        throw new BusinessException("修改个人信息异常，请联系管理员");
    }

    /**
     * 重置密码
     */
    @PutMapping("/updatePwd")
    public ApiResult updatePwd(String oldPassword, String newPassword) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUserVO sysUser = loginUser.getSysUser();
        String userName = sysUser.getUserName();
        String password = sysUser.getPassword();
        if (!SecurityUtils.matchesPassword(oldPassword, password)) {
            throw new BusinessException("修改密码失败，旧密码错误");
        }
        if (SecurityUtils.matchesPassword(newPassword, password)) {
            throw new BusinessException("新密码不能与旧密码相同");
        }
        if (userService.resetUserPwd(userName, SecurityUtils.encryptPassword(newPassword)) > 0) {
            // 更新缓存用户密码
            sysUser.setPassword(SecurityUtils.encryptPassword(newPassword));
            tokenService.setLoginUser(loginUser);
            return ApiResult.success();
        }
        throw new BusinessException("修改密码异常，请联系管理员");
    }

    /**
     * 头像上传
     */
    @PostMapping("/avatar")
    public ApiResult avatar(@RequestParam String filePath) throws IOException {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUserVO sysUser = loginUser.getSysUser();
        if (userService.updateUserAvatar(loginUser.getUsername(), filePath)) {
            Map<String, Object> map = new HashMap<>();
            map.put("imgUrl", filePath);
            // 更新缓存用户头像
            sysUser.setAvatar(filePath);
            tokenService.setLoginUser(loginUser);
            return ApiResult.success(map);
        }
        return ApiResult.success();
    }
}
