package com.supServer.project.service.impl;


import com.supServer.common.constant.Constants;
import com.supServer.common.constant.UserConstants;
import com.supServer.common.exception.ServiceException;
import com.supServer.common.utils.SecurityUtils;
import com.supServer.common.utils.ServletUtils;
import com.supServer.common.utils.uuid.IdUtils;
import com.supServer.framework.security.mode.LoginUser;
import com.supServer.framework.security.service.TokenService;
import com.supServer.framework.web.domain.AjaxResult;
import com.supServer.project.entity.dto.UserDto;
import com.supServer.project.entity.UserInfo;
import com.supServer.project.entity.vo.ForgotPasswordVo;
import com.supServer.project.entity.vo.UserResetPwdVo;
import com.supServer.project.entity.vo.UserUpdateVo;
import com.supServer.project.mapper.UserInfoMapper;
import com.supServer.project.service.UserInfoService;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@Service
public class UserInfoServiceImpl implements UserInfoService {

    /**
     * 0、个人用户    1、企业用户
     */
    private static final String USER_TYPE = "1";
    /**
     * 认证状态（0、待审核  1、认证通过  2、不通过 3注销）
     */
    private static final String USER_STATUS_CANCEL = "3";

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private TokenService tokenService;


    // 令牌自定义标识
    @Value("${token.header}")
    private String header;



    @Override
    public UserInfo selectUserByUserName(String username) {
        return userInfoMapper.selectUserByUserName(username);
    }

    @Override
    public String checkUserNameUnique(String userName)
    {
        int count = userInfoMapper.checkUserNameUnique(userName);
        if (count > 0)
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    @Override
    public String checkUserPhoneUnique(String phone) {
        int count = userInfoMapper.checkUserPhoneUnique(phone);
        if (count > 0)
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    @Override
    public int registerUser(UserInfo userInfo) {
        return userInfoMapper.registerUser(userInfo);
    }

    @Override
    public int resetPwd(UserInfo userInfo) {
        UserInfo user = userInfoMapper.selectUserByPhone(userInfo.getPhone());
        if (ObjectUtils.isEmpty(user)){
            throw new ServiceException("手机号未注册");
        }
        if (!"0".equals(user.getType())){
            throw new ServiceException("该账号为企业用户");
        }
        if (userInfo.getPassword().length() < UserConstants.PASSWORD_MIN_LENGTH
            || userInfo.getPassword().length() > UserConstants.PASSWORD_MAX_LENGTH){
            throw new ServiceException("密码长度应为:8-12");
        }
        userInfo.setUserId(user.getUserId());
        userInfo.setPassword(SecurityUtils.encryptPassword(userInfo.getPassword()));
        int i = userInfoMapper.updateUserInfo(userInfo);
        tokenService.resetPwd(user.getUserId());
        return i;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult resetPwd(UserResetPwdVo userInfoVo) {
        // 获取当前登录人信息
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        UserInfo userInfoToken = loginUser.getUser();
        // 查询最新的数据
        UserInfo userInfo = userInfoMapper.selectUserByUserName(userInfoToken.getUserName());
        // 原密码
        String oldPassword = BCrypt.hashpw(userInfoVo.getOldPassword(), userInfo.getPassword());
        if (!oldPassword.equals(userInfo.getPassword())) {
            return AjaxResult.error("原密码错误");
        }
        // 设置新密码
        String newPassword = SecurityUtils.encryptPassword(userInfoVo.getNewPassword());
        userInfo.setPassword(newPassword);

        int status = userInfoMapper.updateUserInfo(userInfo);

        // 消息来源
        String identifier = IdUtils.fastSimpleUUID();

        if (1 == status) {
            tokenService.resetPwd(userInfo.getUserId());

            return AjaxResult.success();
        }

        return AjaxResult.error("密码修改失败");
    }

    @Override
    public int updateUserInfo(UserUpdateVo userUpdateVo) {
        // 获取当前登录人信息
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        UserInfo userInfo = new UserInfo();
        userInfo.setUserId(loginUser.getUserId());
        userInfo.setPhone(userUpdateVo.getPhone());
        userInfo.setAccount(userUpdateVo.getUserName());
        userInfo.setEmail(userUpdateVo.getEmail());
        return userInfoMapper.updateUserInfo(userInfo);
    }

/*    @Override
    @Transactional(rollbackFor = Exception.class)
    public int cancelUserInfo() {
        // 获取当前登录人信息
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        UserInfo user = loginUser.getUser();
        if (USER_TYPE.equals(user.getType())) {
            AuthenticationRecord authenticationRecord = recordService.getByUserId(user.getUserId());
            // 注销
            authenticationRecord.setStatus(USER_STATUS_CANCEL);
            recordService.updateAuthenticationRecordById(authenticationRecord);
        }
        UserInfo userInfo = new UserInfo();
        userInfo.setUserId(loginUser.getUserId());
        userInfo.setAccountStatus(USER_STATUS_CANCEL);
        return userInfoMapper.updateUserInfo(userInfo);
    }*/

    @Override
    public UserDto getByUserId(String userId) {
        return userInfoMapper.getByUserId(userId);
    }

    @Override
    public int updateLoginTime(String userId) {
        return userInfoMapper.updateLoginTime(userId);
    }

    @Override
    public UserInfo selectUserByPhone(String phone) {
        return userInfoMapper.selectUserByPhone(phone);
    }

    @Override
    public UserInfo selectUserByNumber(String userName) {
        return userInfoMapper.selectUserByNumber(userName);
    }


    /***
     *@Description: 获取请求token
     *@Param:
     *@return: java.lang.String
     *@Author: Dgm
     *@date: 2022/4/2 17:20
     */
    private String getToken(HttpServletRequest request)
    {
        String token = request.getHeader(header);
        if (StringUtils.isNotEmpty(token) && token.startsWith(Constants.TOKEN_PREFIX))
        {
            token = token.replace(Constants.TOKEN_PREFIX, "");
        }
        return token;
    }

    /**
     * 忘记密码
     * @param forgotPasswordVo
     * @return
     */
    @Override
    public AjaxResult forgotPassword(ForgotPasswordVo forgotPasswordVo) {
        Integer num = userInfoMapper.forgotPassword(forgotPasswordVo.getPhone(), SecurityUtils.encryptPassword(forgotPasswordVo.getPassWord()));
        if(num<=0){
            return AjaxResult.error("修改失败");
        }
        return AjaxResult.success("修改成功");
    }
}
