package com.tuoheng.admin.service.user.update;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tuoheng.admin.entity.User;
import com.tuoheng.admin.enums.MarkEnum;
import com.tuoheng.admin.enums.code.user.EditUserPasswordCodeEnum;
import com.tuoheng.admin.mapper.UserMapper;
import com.tuoheng.admin.request.user.UserEditPwdRequest;
import com.tuoheng.admin.service.third.oidc.OidcService;
import com.tuoheng.admin.utils.CurrentUserUtil;
import com.tuoheng.common.core.utils.CommonUtils;
import com.tuoheng.common.core.utils.JsonResult;
import com.tuoheng.common.core.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 修改用户密码业务层处理
 *
 * @author suqin
 * @team tuoheng
 * @date 2024-01-04
 */
@Slf4j
@Service
public class UpdateUserPasswordService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private OidcService oidcService;

    /**
     * 修改用户密码数据
     *
     * @return
     */
    public JsonResult editPassword(UserEditPwdRequest request) {
        log.info("进入修改用户密码业务接口");
        User user = CurrentUserUtil.getUserInfo();
        JsonResult result = this.check(request, user.getId());
        if (0 != result.getCode()) {
            log.info("修改用户密码业务接口：校验失败：{}", result.getMsg());
            return result;
        }
        user.setPassword(CommonUtils.password(request.getNewPasswordFirst()));
        Integer rowCount = userMapper.updateById(user);
        if (rowCount <= 0) {
            return JsonResult.error(EditUserPasswordCodeEnum.EDIT_IS_FAILED.getCode(), EditUserPasswordCodeEnum.EDIT_IS_FAILED.getMsg());
        }
        // 修改oidc用户密码
        result = oidcService.editUserPassword(user, request.getNewPasswordFirst());
        if (0 != result.getCode()) {
            log.info("修改用户密码业务接口：修改oidc用户密码失败：{}", result.getMsg());
            return result;
        }
        return JsonResult.success();
    }

    /**
     * 检查参数
     *
     * @param request
     * @param userId
     * @return
     */
    private JsonResult check(UserEditPwdRequest request, String userId) {
        log.info("修改用户密码，进入参数校验");
        if (StringUtils.isEmpty(request.getOldPassword())) {
            return JsonResult.error(EditUserPasswordCodeEnum.OLD_PASSWORD_IS_NULL.getCode(), EditUserPasswordCodeEnum.OLD_PASSWORD_IS_NULL.getMsg());
        }

        //密码不为空且长度 >= 8
        if (StringUtils.isEmpty(request.getNewPasswordFirst()) || request.getNewPasswordFirst().length() <8 || request.getNewPasswordFirst().length() >20) {
            return JsonResult.error(EditUserPasswordCodeEnum.NEW_PASSWORD_INVALID_SIZE.getCode(), EditUserPasswordCodeEnum.NEW_PASSWORD_INVALID_SIZE.getMsg());
        }

        if (StringUtils.isEmpty(request.getNewPasswordSecond())) {
            return JsonResult.error(EditUserPasswordCodeEnum.NEW_PASSWORD_IS_NULL.getCode(), EditUserPasswordCodeEnum.NEW_PASSWORD_IS_NULL.getMsg());
        }

        if (!request.getNewPasswordFirst().equals(request.getNewPasswordSecond())) {
            return JsonResult.error(EditUserPasswordCodeEnum.TWO_PASSWORDS_NOT_MATCH.getCode(), EditUserPasswordCodeEnum.TWO_PASSWORDS_NOT_MATCH.getMsg());
        }

        //新密码是否为字母和数字组合
        boolean flag = this.isLetterDigit(request.getNewPasswordFirst());
        if(!flag){
            return JsonResult.error(EditUserPasswordCodeEnum.NEW_PASSWORD_INVALID_VALUE.getCode(), EditUserPasswordCodeEnum.NEW_PASSWORD_INVALID_VALUE.getMsg());
        }

        User user = userMapper.selectOne(new LambdaQueryWrapper<User>()
                .eq(User::getId, userId)
                .eq(User::getMark, MarkEnum.VALID.getCode()));

        if (ObjectUtil.isNull(user)) {
            return JsonResult.error(EditUserPasswordCodeEnum.USER_IS_NOT_EXIST.getCode(), EditUserPasswordCodeEnum.USER_IS_NOT_EXIST.getMsg());
        }

        if (!user.getPassword().equals(CommonUtils.password(request.getOldPassword()))) {
            return JsonResult.error(EditUserPasswordCodeEnum.OLD_PASSWORD_INCORRECT.getCode(), EditUserPasswordCodeEnum.OLD_PASSWORD_INCORRECT.getMsg());
        }
        return JsonResult.success();
    }


    //密码是否为字母和数字组合
    public  boolean isLetterDigit(String str) {
        boolean isDigit = false;//定义一个boolean值，用来表示是否包含数字
        boolean isLetter = false;//定义一个boolean值，用来表示是否包含字母
        boolean isSpecial = false;//定义一个boolean值，用来表示是否包含特殊字符

        for (int i = 0; i < str.length(); i++) {
            //判断是否含有特殊字符
            Pattern p = Pattern.compile("[~`#$%^&*!@.,()\\\\{}|:;?<>]");
            Matcher m = p.matcher(str);
            if (Character.isDigit(str.charAt(i))) {   //用char包装类中的判断数字的方法判断每一个字符
                isDigit = true;
            } else if (Character.isLetter(str.charAt(i))) {  //用char包装类中的判断字母的方法判断每一个字符
                isLetter = true;
            }else if (m.find()) {//判断是否包含特殊字符
                isSpecial = true;   //m.find()  结果为 true 代表包含特殊字符  false 不包含
            }
        }

        isSpecial = !isSpecial;  //返回结果与m.find()结果正相反   用户输入的新密码不能包含特殊字符
        boolean isRight = isDigit && isLetter && isSpecial ;
        return isRight;
    }

}
