package com.vctgo.system.controller;

import com.vctgo.common.core.constant.CacheConstants;
import com.vctgo.common.core.domain.R;
import com.vctgo.common.core.utils.StrUtils;
import com.vctgo.common.core.utils.file.FileTypeUtils;
import com.vctgo.common.core.utils.file.MimeTypeUtils;
import com.vctgo.common.core.web.controller.BaseController;
import com.vctgo.common.core.web.domain.AjaxResult;
import com.vctgo.common.log.annotation.Log;
import com.vctgo.common.log.enums.BusinessType;
import com.vctgo.common.redis.service.RedisService;
import com.vctgo.common.security.service.TokenService;
import com.vctgo.common.security.utils.SecurityUtils;
import com.vctgo.system.api.RemoteFileService;
import com.vctgo.system.api.domain.FileInfo;
import com.vctgo.system.api.domain.SysPlatformUser;
import com.vctgo.system.api.domain.SysUserTempalte;
import com.vctgo.system.api.model.LoginUser;
import com.vctgo.system.service.ISysPlatformUserService;
import com.vctgo.system.service.SystemCommonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;

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

    @Autowired
    private TokenService tokenService;

    @Autowired
    private RemoteFileService remoteFileService;

    @Autowired
    private RedisService redisService;

    @Autowired
    private SystemCommonService systemCommonService;

    /**
     * 个人信息
     */
    @GetMapping
    public AjaxResult profile()
    {
        String username = SecurityUtils.getUsername();
        SysPlatformUser user = userService.selectUserByUserName(username);
        AjaxResult ajax = AjaxResult.success(user);
        ajax.put("roleGroup", userService.selectUserRoleGroup(username));
        ajax.put("postGroup", userService.selectUserPostGroup(username));
        return ajax;
    }

    /**
     * 修改用户
     */
    @PutMapping
    public AjaxResult updateProfile(@RequestBody SysPlatformUser user)
    {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUserTempalte sysUser = loginUser.getSysUserTempalte();
        user.setUserName(sysUser.getUserName());
        if (StrUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user))
        {
            return error("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        }
        else if (StrUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user))
        {
            return error("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setUserId(sysUser.getUserId());
        user.setPassword(null);
        user.setAvatar(null);
        user.setDeptId(null);
        if (userService.updateUserProfile(user) > 0)
        {
            // 更新缓存用户信息
            loginUser.getSysUserTempalte().setNickName(user.getNickName());
            loginUser.getSysUserTempalte().setPhonenumber(user.getPhonenumber());
            loginUser.getSysUserTempalte().setEmail(user.getEmail());
            loginUser.getSysUserTempalte().setSex(user.getSex());
            tokenService.setLoginUser(loginUser);
            return success();
        }
        systemCommonService.synchronizedUserInfo(sysUser);
        return error("修改个人信息异常，请联系管理员");
    }

    /**
     * 重置密码
     */
    @PutMapping("/updatePwd")
    public AjaxResult updatePwd(String oldPassword, String newPassword) {
        String username = SecurityUtils.getUsername();
        SysPlatformUser user = userService.selectUserByUserName(username);
        String password = user.getPassword();
        if (!SecurityUtils.matchesPassword(oldPassword, password)) {
            return error("修改密码失败，旧密码错误");
        }
        if (SecurityUtils.matchesPassword(newPassword, password)) {
            return error("新密码不能与旧密码相同");
        }
        if (userService.resetUserPwd(username, SecurityUtils.encryptPassword(newPassword)) > 0) {

            // 修改密码该账号退出登录
            Collection<String> keys = redisService.keys(CacheConstants.LOGIN_TOKEN_KEY + "*");
            for (String key : keys) {
                LoginUser onlineUser = redisService.getCacheObject(key);
                if (onlineUser.getUserid().longValue() == user.getUserId().longValue()) {
                    redisService.deleteObject(key);
                }
            }
            return success();
        }
        return error("修改密码异常，请联系管理员");
    }

    /**
     * 重置密码
     */
    @PutMapping("/resetPwd")
    public AjaxResult updatePwd()
    {
        //默认密码采用随机生成
        String randomPassword = SecurityUtils.randomPassword(6);//随机密码6位
//        String newPassword = SecurityUtils.encryptPassword(randomPassword);
        String username = SecurityUtils.getUsername();
        SysPlatformUser user = userService.selectUserByUserName(username);
        String password = user.getPassword();
        if (SecurityUtils.matchesPassword(randomPassword, password))
        {
            return error("新密码不能与旧密码相同");
        }
        if (userService.resetUserPwd(username, SecurityUtils.encryptPassword(randomPassword)) > 0)
        {
            // 更新缓存用户密码
            LoginUser loginUser = SecurityUtils.getLoginUser();
            loginUser.getSysUserTempalte().setPassword(SecurityUtils.encryptPassword(randomPassword));
            tokenService.setLoginUser(loginUser);
            return success(randomPassword);
        }
        return error("修改密码异常，请联系管理员");
    }

    /**
     * 头像上传
     */
    @PostMapping("/avatar")
    public AjaxResult avatar(@RequestParam("avatarfile") MultipartFile file)
    {
        if (!file.isEmpty())
        {
            LoginUser loginUser = SecurityUtils.getLoginUser();
            String extension = FileTypeUtils.getExtension(file);
            if (!StrUtils.equalsAnyIgnoreCase(extension, MimeTypeUtils.IMAGE_EXTENSION))
            {
                return error("文件格式不正确，请上传" + Arrays.toString(MimeTypeUtils.IMAGE_EXTENSION) + "格式");
            }
            R<FileInfo> fileResult = remoteFileService.upload(file);
            if (StrUtils.isNull(fileResult) || StrUtils.isNull(fileResult.getData()))
            {
                return error("文件服务异常，请联系管理员");
            }
            String url = fileResult.getData().getFileUrl();
            if (userService.updateUserAvatar(loginUser.getUsername(), url))
            {
                AjaxResult ajax = AjaxResult.success();
                ajax.put("imgUrl", url);
                // 更新缓存用户头像
                loginUser.getSysUserTempalte().setAvatar(url);
                tokenService.setLoginUser(loginUser);
                return ajax;
            }
        }
        return error("上传图片异常，请联系管理员");
    }
}
