package com.jxy.system.controller;

import com.jxy.common.core.Result.R;
import com.jxy.common.core.constant.UserConstants;
import com.jxy.common.core.utils.StringUtils;
import com.jxy.common.core.web.Result.AjaxResult;
import com.jxy.common.core.web.controller.BaseController;

import com.jxy.common.security.annotation.InnerAuth;
import com.jxy.common.security.annotation.RequiresLogin;
import com.jxy.common.security.service.TokenService;
import com.jxy.common.security.utils.SecurityUtils;
import com.jxy.system.api.entity.SysRole;
import com.jxy.system.api.entity.SysUser;
import com.jxy.system.api.entity.SysUserLeveDate;
import com.jxy.system.api.model.LoginUser;
import com.jxy.system.entity.SysRoleDto;
import com.jxy.system.entity.SysUserDto;
import com.jxy.system.mapper.SysUserLevelMapper;
import com.jxy.system.mapper.SysUserRoleMapper;
import com.jxy.system.service.SysRoleService;
import com.jxy.system.service.SysUserService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


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

    @Autowired
    private SysRoleService roleService;

    @Autowired
    private SysUserRoleMapper userRoleMapper;

    @Autowired
    private SysUserLevelMapper userLevelMapper;


    @Autowired
    private TokenService tokenService;

    /**
     * 个人信息
     */
    @GetMapping
    public AjaxResult profile()
    {
        String username = SecurityUtils.getUsername();
        SysUser user = userService.selectUserByUserName(username);

        //隐藏不需要返回前端的信息
        SysUserDto userDto = new SysUserDto();
        SysRoleDto roleDto = new SysRoleDto();

        BeanUtils.copyProperties(user,userDto);

        if (StringUtils.isNull(user.getRoles()) || user.getRoles().size() < 1)
        {
            //todo 动态获取注册用户信息
            roleDto.setRoleId(2L);
            roleDto.setRoleKey("registered");
            roleDto.setRoleName("L2");
            roleDto.setLevel("L2");
        }else {
            SysRole sysRole = user.getRoles().get(0);
            BeanUtils.copyProperties(sysRole,roleDto);
            if (sysRole.getRoleId() == 1L) {
                roleDto.setLevel("admin");
            } else if (sysRole.getRoleId() == 2L) {
                roleDto.setLevel("L2");
            } else if (sysRole.getRoleId() == 3L) {
                roleDto.setLevel("L3");

                //此时角色是L3 说明应该在会员有效期
                SysUserLeveDate userLevelInfo = userLevelMapper.getUserLevelInfo(SecurityUtils.getUserId());
                if(StringUtils.isNotNull(userLevelInfo)){
                    if(userLevelInfo.getLevelType() == 0){
                        roleDto.setRoleName("月度"+roleDto.getRoleName());
                    }else if(userLevelInfo.getLevelType() == 1){
                        roleDto.setRoleName("年度"+roleDto.getRoleName());
                    }
                }else {
                    //如果查询不到userLevelInfo 说明用户已过期 修改profit返回的用户等级为L2
                    roleDto.setRoleId(2L);
                    roleDto.setRoleKey("registered");
                    roleDto.setRoleName("L2");
                    roleDto.setLevel("L2");
                }
            } else if (sysRole.getRoleId() == 4L) {
                roleDto.setLevel("L4");
            }else {
                roleDto.setLevel(roleDto.getRoleKey());
            }

        }

        userDto.setRole(roleDto);

        //AjaxResult ajax = AjaxResult.success(userDto);

        //ajax.put("roleGroup", userService.selectUserRoleGroup(username));
        return AjaxResult.success(userDto);
    }

    @PostMapping("userLevel")
    public R<SysUserLeveDate> userLevel(@RequestBody() Long userId)
    {
        //先看用户是否有会员记录 有才查询
        System.out.println("调用system接口查询userLevel");
        System.out.println("用户id："+userId);
        SysUserLeveDate info = userLevelMapper.getUserLevelInfo(userId);
        return R.success(info);
    }

    /**
     * 修改用户
     */
    @PutMapping
    @ApiOperation(value = "个人信息")
    @RequiresLogin
    public AjaxResult updateProfile(@RequestBody SysUser user)
    {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser sysUser = loginUser.getSysUser();
        user.setUserName(sysUser.getUserName());
        if (StringUtils.isNotEmpty(user.getPhone())
                && UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user)))
        {
            return AjaxResult.error("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        }
        else if (StringUtils.isNotEmpty(user.getEmail())
                && UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user)))
        {
            return AjaxResult.error("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setUserId(sysUser.getUserId());
        user.setPassword(null);
        if (userService.updateUserProfile(user) > 0)
        {
            // 更新缓存用户信息
            loginUser.getSysUser().setNickName(user.getNickName());
            loginUser.getSysUser().setPhone(user.getPhone());
            loginUser.getSysUser().setEmail(user.getEmail());
            loginUser.getSysUser().setSex(user.getSex());
            tokenService.setLoginUser(loginUser);
            return AjaxResult.success();
        }
        return AjaxResult.error("修改个人信息异常，请联系管理员");
    }

    /**
     * 重置密码(已知原密码修改为新密码)
     */
    @ApiOperation(value = "重置密码")
    @PutMapping("/updatePwd")
    public AjaxResult updatePwd(String oldPassword, String newPassword)
    {
        String username = SecurityUtils.getUsername();
        SysUser user = userService.selectUserByUserName(username);
        String password = user.getPassword();
        if (!SecurityUtils.matchesPassword(oldPassword, password))
        {
            return AjaxResult.error("修改密码失败，旧密码错误");
        }
        if (SecurityUtils.matchesPassword(newPassword, password))
        {
            return AjaxResult.error("新密码不能与旧密码相同");
        }
        if (userService. resetUserPwd(username, SecurityUtils.encryptPassword(newPassword)) > 0)
        {
            // 更新缓存用户密码
            LoginUser loginUser = SecurityUtils.getLoginUser();
            loginUser.getSysUser().setPassword(SecurityUtils.encryptPassword(newPassword));
            tokenService.setLoginUser(loginUser);
            return AjaxResult.success();
        }
        return AjaxResult.error("修改密码异常，请联系管理员");
    }

    /**
     * 重置密码(忘记原密码通过邮箱验证修改为新密码)
     */
    @ApiOperation(value = "重置密码")
    @PostMapping("/resetPwd")
    public AjaxResult resetPwd(@RequestBody SysUser user){
        if(userService.resetPwdByEmail(user.getEmail(),user.getPassword()) > 0){
            //
            return AjaxResult.success();
        }
        return AjaxResult.error("修改密码异常，请联系管理员");
    }

    /**
     * 用户升级
     */
    @PostMapping("/Levelup")
    @ApiOperation(value = "用户升级")
    @InnerAuth
    public AjaxResult LevelUp(@RequestBody SysUserLeveDate user)
    {
        Long roleId = user.getRoleId();
        if(roleId == 1 || roleId > 4){
            return AjaxResult.success("流程最后一步修改用户等级，admin等内部账户不会更改等级");
        }

        if (userService.userLevelUp(user) > 0)
        {
            return AjaxResult.success("用户已升级");
        }
        return AjaxResult.error("修改个人信息异常，请联系管理员");
    }

}
