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.StoreUser;
import shop.alien.entity.store.UserLoginInfo;
import shop.alien.entity.store.dto.StoreUserPasswordDto;
import shop.alien.mapper.StoreUserMapper;
import shop.alien.store.service.StoreUserPasswordService;

import java.util.Objects;

@Service
@RequiredArgsConstructor
public class StoreUserPasswordServiceImpl implements StoreUserPasswordService {

    private final StoreUserMapper storeUserMapper;

    @Override
    public R<String> setPassword(UserLoginInfo login, StoreUserPasswordDto dto) {
        if (login == null || login.getUserId() <= 0) {
            return R.fail("请先登录");
        }
        if (!"store".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("两次密码输入不一致");
        }
        StoreUser storeUser = storeUserMapper.selectById(login.getUserId());
        if (storeUser == null || (storeUser.getDeleteFlag() != null && storeUser.getDeleteFlag() == 1)) {
            return R.fail("商户账号不存在");
        }
        if (storeUser.getStatus() != null && storeUser.getStatus() == 1) {
            return R.fail("账号被禁用");
        }
        if (storeUser.getLogoutFlag() != null && storeUser.getLogoutFlag() == StoreUser.LOGOUT_FLAG_DONE) {
            return R.fail("账号已注销");
        }
        StoreUser update = new StoreUser();
        update.setId(login.getUserId());
        update.setPassword(dto.getPassword());
        update.setPassType(1);
        if (storeUserMapper.updateById(update) <= 0) {
            return R.fail("设置密码失败");
        }
        return R.success("设置密码成功");
    }
}
