package shop.alien.store.service.impl;

import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import shop.alien.entity.result.R;
import shop.alien.entity.store.LifeUser;
import shop.alien.entity.store.UserLoginInfo;
import shop.alien.entity.store.dto.LifeUserPasswordDto;
import shop.alien.mapper.LifeUserMapper;
import shop.alien.store.service.LifeUserPasswordService;

import java.util.Objects;

@Service
@RequiredArgsConstructor
public class LifeUserPasswordServiceImpl implements LifeUserPasswordService {

    private final LifeUserMapper lifeUserMapper;

    @Override
    public R<String> setPassword(UserLoginInfo login, LifeUserPasswordDto dto) {
        if (login == null || login.getUserId() <= 0) {
            return R.fail("请先登录");
        }
        if (!"user".equals(login.getType()) && !"miniprogram_user".equals(login.getType())) {
            return R.fail("仅支持用户端操作");
        }
        if (dto == null || StringUtils.isBlank(dto.getPassword())) {
            return R.fail("密码不能为空");
        }
        if (!Objects.equals(dto.getPassword(), dto.getConfirmPassword())) {
            return R.fail("两次密码输入不一致");
        }
        LifeUser user = lifeUserMapper.selectById(login.getUserId());
        if (user == null) {
            return R.fail("用户不存在");
        }
        if (user.getIsBanned() != null && user.getIsBanned() == 1) {
            return R.fail("您的账户因严重违规导致被封禁");
        }
        LifeUser update = new LifeUser();
        update.setId(login.getUserId());
        update.setPassword(dto.getPassword());
        if (lifeUserMapper.updateById(update) <= 0) {
            return R.fail("设置密码失败");
        }
        return R.success("设置密码成功");
    }

    @Override
    public R<Boolean> hasLoginPassword(Integer userId) {
        if (userId == null) {
            return R.fail("用户id不能为空");
        }
        LifeUser user = lifeUserMapper.selectById(userId);
        if (user == null) {
            return R.fail("用户不存在");
        }
        return R.data(StringUtils.isNotBlank(user.getPassword()));
    }
}
