package com.yingpaipay.web.service.impl;

import cn.hutool.crypto.digest.BCrypt;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yingpaipay.web.domain.bo.AppletUserUpdateAvatarBo;
import com.yingpaipay.web.domain.bo.AppletUserUpdatePasswordBo;
import com.yingpaipay.web.domain.vo.AppletUserBasicInfoVo;
import com.yingpaipay.web.domain.vo.AppletUserInfoVo;
import com.yingpaipay.web.service.IAppletUserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.exception.BusinessException;
import org.dromara.common.core.utils.MessageUtils;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.system.domain.SysUser;
import org.dromara.system.mapper.SysUserMapper;
import org.dromara.system.service.ISysOssService;
import org.springframework.stereotype.Service;

/**
 * @Author: Huanyi
 * @CreateTime: 2025-12-04
 * @Description:
 * @Version: 1.0
 */

@Service
@RequiredArgsConstructor
@Slf4j
public class AppletUserServiceImpl implements IAppletUserService {

    private final SysUserMapper userMapper;

    private final ISysOssService ossService;

    @Override
    public AppletUserInfoVo getInfo() {
        SysUser sysUser = userMapper.selectById(LoginHelper.getUserId());
        AppletUserInfoVo vo = new AppletUserInfoVo();
        vo.setNickname(sysUser.getNickName());
        vo.setPhoneNumber(sysUser.getPhonenumber());
        if (sysUser.getAvatar() != null) {
            vo.setAvatar(ossService.getById(sysUser.getAvatar()).getUrl());
        }
        return vo;
    }

    @Override
    public AppletUserBasicInfoVo getBasicInfo() {
        SysUser user = userMapper.selectById(LoginHelper.getUserId());
        AppletUserBasicInfoVo vo = new AppletUserBasicInfoVo();
        vo.setNickname(user.getNickName());
        vo.setPhoneNumber(user.getPhonenumber());
        if (user.getAvatar() != null) {
            vo.setAvatar(ossService.getById(user.getAvatar()).getUrl());
        }
        vo.setGender(user.getSex());

        return vo;
    }

    @Override
    public int updatePassword(AppletUserUpdatePasswordBo bo) {
        SysUser user = userMapper.selectById(LoginHelper.getUserId());
        if (!BCrypt.checkpw(bo.getOldPassword(), user.getPassword())) {
            throw new BusinessException(MessageUtils.message("applet.auth.login.passworderror"));
        }
        user.setPassword(BCrypt.hashpw(bo.getNewPassword()));
        return userMapper.updateById(user);
    }

    @Override
    public int updateAvatar(AppletUserUpdateAvatarBo bo) {
        return userMapper.update(
            Wrappers.lambdaUpdate(SysUser.class)
                .eq(SysUser::getUserId, LoginHelper.getUserId())
                .set(bo.getId() != null, SysUser::getAvatar, bo.getId())
        );
    }
}
