package com.qs.mp.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.qs.mp.user.domain.UserAddr;
import com.qs.mp.user.mapper.UserAddrMapper;
import com.qs.mp.user.service.IUserAddrService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import java.util.List;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

/**
 * <p>
 * 渠道配送地址 服务实现类
 * </p>
 *
 * @author quanshu
 * @since 2022-03-02
 */
@Service
public class UserAddrServiceImpl extends ServiceImpl<UserAddrMapper, UserAddr> implements
    IUserAddrService {

  @Override
  public UserAddr getDefaultChannelAddr(Long userId) {
    List<UserAddr> userAddrList = list(new LambdaQueryWrapper<UserAddr>().eq(UserAddr::getUserId,
            userId)
        .eq(UserAddr::getCommonAddr, 1));
    if (CollectionUtils.isEmpty(userAddrList)) {
      return null;
    }
    return userAddrList.get(0);
  }

  @Override
  @Transactional
  public boolean updateDefaultChannelAddr(Long addrId, Long userId) {
    update(new LambdaUpdateWrapper<UserAddr>().set(UserAddr::getCommonAddr, 0)
        .eq(UserAddr::getUserId, userId).eq(UserAddr::getCommonAddr, 1));
    return update(new LambdaUpdateWrapper<UserAddr>().set(UserAddr::getCommonAddr, 1)
        .eq(UserAddr::getUserId, userId).eq(UserAddr::getAddrId, addrId));
  }

  @Override
  public boolean removeChannelAddrByUserId(Long addrId, Long userId) {
    return remove(new LambdaQueryWrapper<UserAddr>()
        .eq(UserAddr::getUserId, userId).eq(UserAddr::getAddrId, addrId));
  }

  @Override
  public UserAddr getChannelAddrByUserId(Long addrId, Long userId) {
    return getOne(new LambdaQueryWrapper<UserAddr>()
        .eq(UserAddr::getUserId, userId).eq(UserAddr::getAddrId, addrId));
  }
}
