package com.yunfeiyun.agmp.common.web.system.controller;

import com.yunfeiyun.agmp.common.constant.ErrorCode;
import com.yunfeiyun.agmp.common.core.domain.AjaxResult;
import com.yunfeiyun.agmp.common.exception.BizException;
import com.yunfeiyun.agmp.common.framework.web.service.ISysUserService;
import com.yunfeiyun.agmp.common.framework.web.service.TokenService;
import com.yunfeiyun.agmp.common.web.system.domain.SysRes;
import com.yunfeiyun.agmp.common.annotation.Log;
import com.yunfeiyun.agmp.common.core.controller.BaseController;
import com.yunfeiyun.agmp.common.core.domain.entity.SysUser;
import com.yunfeiyun.agmp.common.core.domain.model.IBaseUser;
import com.yunfeiyun.agmp.common.core.domain.model.LoginUser;
import com.yunfeiyun.agmp.common.enums.BusinessType;
import com.yunfeiyun.agmp.common.framework.manager.ResManager;
import com.yunfeiyun.agmp.common.utils.SecurityUtils;
import com.yunfeiyun.agmp.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

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

    @Autowired
    private TokenService tokenService;

    @Autowired
    private ResManager resManager;

    /**
     * 个人信息
     */
    @GetMapping("/info")
    public AjaxResult profile()
    {
        LoginUser loginUser = getLoginUser();
        IBaseUser user = loginUser.getUser();
        AjaxResult ajax = AjaxResult.success(user);
        ajax.put("roleGroup", userService.selectUserRoleGroup(loginUser.getUsername()));
        return ajax;
    }

    /**
     * 修改用户
     */
    @Log(title = "个人信息", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    public AjaxResult updateProfile(@RequestBody SysUser user)
    {
        LoginUser loginUser = getLoginUser();
        IBaseUser sysUser = loginUser.getUser();
        user.setUserLoginname(sysUser.getUserLoginname());
        if (StringUtils.isNotEmpty(user.getUserMobile()) && !userService.checkPhoneUnique(user))
        {
            throw new BizException(ErrorCode.ADD_PROFILE_MOBILE_ERROR.getCode(),ErrorCode.ADD_PROFILE_MOBILE_ERROR.getMessage());
        }
        if (StringUtils.isNotEmpty(user.getUserEmail()) && !userService.checkEmailUnique(user))
        {
            throw new BizException(ErrorCode.ADD_PROFILE_EMAIL_ERROR.getCode(),ErrorCode.ADD_PROFILE_EMAIL_ERROR.getMessage());
        }
        user.setUserId(sysUser.getUserId());
        user.setUserLoginpwd(null);
        //user.setAvatar(null);
        user.setDeptId(null);
        if (userService.updateUserProfile(user) > 0)
        {
            // 更新缓存用户信息
            sysUser.setUserLoginname(user.getUserLoginname());
            sysUser.setUserMobile(user.getUserMobile());
            sysUser.setUserEmail(user.getUserEmail());
            sysUser.setUserSex(user.getUserSex());
            tokenService.setLoginUser(loginUser);
            return success();
        }
        throw new BizException(ErrorCode.ADD_PROFILE_BASE_ERROR.getCode(),ErrorCode.ADD_PROFILE_BASE_ERROR.getMessage());
    }

    /**
     * 重置密码
     */
    @Log(title = "个人信息", businessType = BusinessType.UPDATE)
    @PostMapping("/updatePwd")
    public AjaxResult updatePwd(String oldPassword, String newPassword)
    {
        LoginUser loginUser = getLoginUser();
        String loginName = loginUser.getUsername();
        String password = loginUser.getPassword();
        if (!SecurityUtils.matchesPassword(oldPassword, password))
        {
            throw new BizException(ErrorCode.ADD_PWDOLD_ERROR.getCode(),ErrorCode.ADD_PWDOLD_ERROR.getMessage());

        }
        if (SecurityUtils.matchesPassword(newPassword, password))
        {
            throw new BizException(ErrorCode.ADD_PWDDIFF_ERROR.getCode(),ErrorCode.ADD_PWDDIFF_ERROR.getMessage());
        }
        if (userService.resetUserPwd(loginName, SecurityUtils.encryptPassword(newPassword)) > 0)
        {
            // 更新缓存用户密码
            loginUser.getUser().setUserLoginpwd(SecurityUtils.encryptPassword(newPassword));
            tokenService.setLoginUser(loginUser);
            return success();
        }
        throw new BizException(ErrorCode.ADD_PWDUNKNOWN_ERROR.getCode(),ErrorCode.ADD_PWDUNKNOWN_ERROR.getMessage());
    }

    /**
     * 头像上传
     */
    @Log(title = "用户头像", businessType = BusinessType.UPDATE)
    @PostMapping("/avatar")
    public AjaxResult avatar(@RequestParam("avatarfile") MultipartFile file) throws Exception
    {
        if (!file.isEmpty())
        {
            LoginUser loginUser = getLoginUser();
            //SysRes sysRes  = resManager.uploadRes( ResConstants.BizType.AVATAR, ResConstants.mediaType.IMG,file,getLoginUser());
            SysRes sysRes = userService.updateUserAvatar(loginUser.getUserId(), file);
            if (sysRes !=null)
            {
                AjaxResult ajax = AjaxResult.success();
                ajax.put("imgUrl", sysRes.getResUrl());
                // 更新缓存用户头像
                loginUser.getUser().setUserAvatar(sysRes.getResUrl());
                tokenService.setLoginUser(loginUser);
                return ajax;
            }
        }
        throw new BizException(ErrorCode.UPLOAD_FAIL.getCode(),ErrorCode.UPLOAD_FAIL.getMessage());
    }
}
