package cn.pluss.platform.userAddress.impl;

import cn.pluss.platform.entity.UserAddress;
import cn.pluss.platform.exception.MsgException;
import cn.pluss.platform.mapper.UserAddressMapper;
import cn.pluss.platform.userAddress.UserAddressService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 用户地址信息表 服务实现类
 * </p>
 *
 * @author bzg
 * @since 2021-11-17
 */
@Service
public class UserAddressServiceImpl extends ServiceImpl<UserAddressMapper, UserAddress> implements UserAddressService {


    @Override
    public List<UserAddress> getAddressList(Long userId, Integer type,boolean defFlag) {
        return baseMapper.getAddressList(userId,type,defFlag);
    }

    @Override
    public boolean saveOrUpdate(UserAddress entity) {
        checkSaveBefore(entity);
        if(UserAddress.DEFAULT_FLAG.equals(entity.getDefFlag())){
            UpdateWrapper<UserAddress> updateWrapper = new UpdateWrapper<>();
            updateWrapper.set("defFlag","0").eq("userId",entity.getUserId()).eq("type",1);
            this.update(updateWrapper);
        }
        return super.saveOrUpdate(entity);
    }

    public void checkSaveBefore(UserAddress entity) {
        MsgException.checkBlank(entity.getName(),"联系人姓名不能为空");
        MsgException.checkBlank(entity.getPhone(),"联系人手机号为空");
        MsgException.checkBlank(entity.getAddress(),"详细地址不能为空");
        MsgException.checkBlank(entity.getAreaCode(),"地区CODE不能为空");
        MsgException.checkBlank(entity.getAreaName(),"地区Name不能为空");
        if(entity.getId() == null){
            MsgException.checkNull(entity.getUserId(),"用户ID不能为空");
            QueryWrapper<UserAddress> queryWrapper = new QueryWrapper<UserAddress>().eq("userId",entity.getUserId());
            int count = this.count(queryWrapper);
            if(count > 10){
                MsgException.throwException("收货地址添加过多,请删除一些再添加哦");
            }
        }
    }
}
