package com.qiaoba.module.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.qiaoba.api.file.service.FileApiService;
import com.qiaoba.api.system.entity.SysUser;
import com.qiaoba.api.system.entity.dto.ResetUserBasicInfoDto;
import com.qiaoba.api.auth.utils.SecurityUtil;
import com.qiaoba.common.base.exception.ServiceException;
import com.qiaoba.module.system.service.SysProfileService;
import com.qiaoba.module.system.service.SysUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

/**
 * 个人信息 服务层实现
 *
 * @author ailanyin
 * @version 1.0
 * @since 2023/5/19 11:29
 */
@Service
@RequiredArgsConstructor
public class SysProfileServiceImpl implements SysProfileService {

    private final FileApiService fileService;
    private final SysUserService sysUserService;

    @Override
    public String updateAvatar(MultipartFile file) {
        String url = fileService.upload(file);
        SysUser sysUser = new SysUser();
        sysUser.setUserId(SecurityUtil.getLoginUserId());
        sysUser.setAvatar(url);
        if (sysUserService.updateById(sysUser) == 0) {
            fileService.delete(url);
            throw new ServiceException("修改头像失败");
        }
        return url;
    }

    @Override
    public void updatePassword(String oldPassword, String newPassword) {
        String userId = SecurityUtil.getLoginUserId();
        String password = sysUserService.selectById(userId, true).getPassword();
        if (!SecurityUtil.matchesPassword(oldPassword, password)) {
            throw new ServiceException("旧密码错误, 请重新输入");
        }
        SysUser sysUser = new SysUser();
        sysUser.setUserId(SecurityUtil.getLoginUserId());
        sysUser.setPassword(SecurityUtil.encryptPassword(newPassword));
        sysUserService.updateById(sysUser);
    }

    @Override
    public void updateBasicInfo(ResetUserBasicInfoDto dto) {
        SysUser sysUser = BeanUtil.copyProperties(dto, SysUser.class);
        sysUser.setUserId(SecurityUtil.getLoginUserId());
        sysUserService.checkAddOrUpdate(sysUser);
        sysUserService.updateById(sysUser);
    }
}
