package com.bonus.system.controller;

import com.bonus.common.core.utils.StringUtils;
import com.bonus.common.core.utils.file.FileTypeUtils;
import com.bonus.common.core.utils.file.MimeTypeUtils;
import com.bonus.common.core.web.controller.BaseController;
import com.bonus.common.core.web.domain.AjaxResult;
import com.bonus.common.log.annotation.SysLog;
import com.bonus.common.log.enums.OperaType;
import com.bonus.common.security.service.TokenService;
import com.bonus.common.security.utils.SecurityUtils;
import com.bonus.system.api.RemoteFileService;
import com.bonus.system.api.domain.SysFile;
import com.bonus.system.api.domain.SysUser;
import com.bonus.system.api.model.LoginUser;
import com.bonus.system.domain.UserPasswordHistory;
import com.bonus.system.service.ISysUserService;
import com.bonus.system.service.PasswordValidatorService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.Arrays;

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

    @Autowired
    private TokenService tokenService;

    @Resource
    private RemoteFileService remoteFileService;

    @Resource
    private PasswordValidatorService passwordValidatorService;

    /**
     * 个人信息
     */
    @GetMapping
    public AjaxResult profile() {
        try {
            String username = SecurityUtils.getUsername();
            SysUser user = userService.selectUserByUserName(username);
            AjaxResult ajax = AjaxResult.success(user);
            ajax.put("roleGroup", userService.selectUserRoleGroup(username));
            ajax.put("postGroup", userService.selectUserPostGroup(username));
            return ajax;
        } catch (Exception e) {
            log.error(e.toString(), e);
        }
        return error("数据查询异常");
    }

    /**
     * 修改当前登录用户的个人信息
     */
   @PostMapping("/edit")
   @SysLog(title = "个人中心", businessType = OperaType.UPDATE, logType = 0, module = "首页->个人中心")
   public AjaxResult updateProfile(@RequestBody SysUser user) {
        try {
            LoginUser loginUser = SecurityUtils.getLoginUser();
            SysUser currentUser = loginUser.getSysUser();
            currentUser.setNickName(user.getNickName());
            currentUser.setEmail(user.getEmail());
            currentUser.setPhonenumber(user.getPhonenumber());
            currentUser.setSex(user.getSex());
            if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(currentUser)) {
                return error("修改用户'" + loginUser.getUsername() + "'失败，手机号码已存在");
            }
            if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(currentUser)) {
                return error("修改用户'" + loginUser.getUsername() + "'失败，邮箱账号已存在");
            }
            if (userService.updateUserProfile(currentUser) > 0) {
                // 更新缓存用户信息
                tokenService.setLoginUser(loginUser);
                return success();
            }
            return error("修改个人信息异常，请联系管理员");
        } catch (Exception e) {
            log.error(e.toString(), e);
        }
        return error("修改个人信息异常，请联系管理员");
    }

    /**
     * 重置密码
     */
   @PostMapping("/updatePwd")
    @SysLog(title = "个人中心", businessType = OperaType.UPDATE, logType = 0, module = "首页->个人中心", details = "修改密码")
    public AjaxResult updatePwd(String oldPassword, String newPassword) {
        try {
            String username = SecurityUtils.getUsername();
            SysUser user = userService.selectUserByUserName(username);

            String password = user.getPassword();
            if (!SecurityUtils.matchesPassword(oldPassword, password)) {
                return error("修改密码失败，旧密码错误");
            }
            AjaxResult ajaxResult = passwordValidatorService.validatePassword(user.getUserId(), user.getUserName(), password, newPassword);
            if (ajaxResult.isError()) {
                return ajaxResult;
            }
            newPassword = SecurityUtils.encryptPassword(newPassword);
            if (userService.resetUserPwd(username, newPassword) > 0) {
                // 更新缓存用户密码
                LoginUser loginUser = SecurityUtils.getLoginUser();
                loginUser.getSysUser().setPassword(newPassword);
                tokenService.setLoginUser(loginUser);
                UserPasswordHistory userPasswordHistory = new UserPasswordHistory();
                userPasswordHistory.setUserId(user.getUserId());
                userPasswordHistory.setChangeUser(SecurityUtils.getUserId());
                userPasswordHistory.setNewPassword(newPassword);
                userPasswordHistory.setOldPassword(password);
                passwordValidatorService.addPasswordExpiry(userPasswordHistory);
                return success();
            }
            return error("修改密码异常，请联系管理员");
        } catch (Exception e) {
            return error("修改密码异常，请联系管理员");
        }
    }

    /**
     * 头像上传
     */
    @PostMapping("/avatar")
    @SysLog(title = "个人中心", businessType = OperaType.UPDATE, logType = 0, module = "首页->个人中心", details = "头像上传")
    public AjaxResult avatar(@RequestParam("avatarfile") MultipartFile file) {
        try {
            if (!file.isEmpty()) {
                LoginUser loginUser = SecurityUtils.getLoginUser();
                String extension = FileTypeUtils.getExtension(file);
                if (!StringUtils.equalsAnyIgnoreCase(extension, MimeTypeUtils.IMAGE_EXTENSION)) {
                    return error("文件格式不正确，请上传" + Arrays.toString(MimeTypeUtils.IMAGE_EXTENSION) + "格式");
                }
                AjaxResult fileResult = remoteFileService.upload(file);
                if (fileResult.isError()) {
                    return error("文件服务异常，请联系管理员");
                }
                String url = fileResult.getDataAs(SysFile.class).getUrl();
                if (userService.updateUserAvatar(loginUser.getUsername(), url)) {
                    AjaxResult ajax = AjaxResult.success();
                    ajax.put("imgUrl", url);
                    // 更新缓存用户头像
                    loginUser.getSysUser().setAvatar(url);
                    tokenService.setLoginUser(loginUser);
                    return ajax;
                }
            }
            return error("上传图片异常，请联系管理员");
        } catch (Exception e) {
            log.error(e.toString(), e);
        }
        return error("上传图片异常，请联系管理员");
    }
}
