package com.kxs.user.biz.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kxs.common.core.util.R;
import com.kxs.common.security.util.SecurityUtils;
import com.kxs.user.api.dto.kxsapp.userAddress.UserAddressDTO;
import com.kxs.user.api.vo.kxsapp.userAddress.UserAddressListVO;
import com.kxs.user.biz.mapper.KxsUserAddressMapper;
import com.kxs.user.api.model.KxsUserAddress;
import com.kxs.user.biz.service.KxsUserAddressService;
import org.bouncycastle.jcajce.provider.symmetric.AES;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 用户收货地址表(KxsUserAddress)表服务实现类
 *
 * @author 系统
 * @since 2024-01-03 09:39:56
 */
@Service("kxsUserAddressService")
public class KxsUserAddressServiceImpl extends ServiceImpl<KxsUserAddressMapper, KxsUserAddress> implements KxsUserAddressService {

    @Override
    public List<UserAddressListVO> userAddressList() {

        return baseMapper.userAddressList(SecurityUtils.getUser().getId());
    }

    @Override
    public R userAddressSave(UserAddressDTO param) {
        Long id = SecurityUtils.getUser().getId();
        KxsUserAddress userAddress = new KxsUserAddress();
        BeanUtils.copyProperties(param, userAddress);
        userAddress.setUserId(id.intValue());
        this.saveOrUpdate(userAddress);
        //设置默认地址时,会将其他地址全部设为非默认
        if (param.getIsDefault() == 1){
            List<KxsUserAddress> list = list(Wrappers.<KxsUserAddress>query().lambda().ne(KxsUserAddress::getId, userAddress.getId()).eq(KxsUserAddress::getUserId, id));
            for (KxsUserAddress kxsUserAddress : list) {
                if (kxsUserAddress.getIsDefault() == 1) {
                    kxsUserAddress.setIsDefault(0);
                    updateById(kxsUserAddress);
                }
            }
        }
        return R.ok();
    }
}

