package com.hai.goods.service.impl;

import com.hai.dao.GoodsDeliveryAddressMapper;
import com.hai.entity.GoodsDeliveryAddress;
import com.hai.entity.GoodsDeliveryAddressExample;
import com.hai.goods.service.DeliveryAddressService;
import org.apache.commons.collections4.MapUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("deliveryAddressService")
public class DeliveryAddressServiceImpl implements DeliveryAddressService {

    @Resource
    private GoodsDeliveryAddressMapper deliveryAddressMapper;

    @Override
    public void insertDeliveryAddress(GoodsDeliveryAddress deliveryAddress) {
        deliveryAddressMapper.insert(deliveryAddress);
    }

    @Override
    public void updateDeliveryAddress(GoodsDeliveryAddress deliveryAddress) {
        deliveryAddressMapper.updateByPrimaryKey(deliveryAddress);
    }

    @Override
    public List<GoodsDeliveryAddress> getDeliveryAddressList(Map<String, Object> map) {

        GoodsDeliveryAddressExample example = new GoodsDeliveryAddressExample();
        GoodsDeliveryAddressExample.Criteria criteria = example.createCriteria();

        if (MapUtils.getLong(map, "userId") != null) {
            criteria.andUserIdEqualTo(MapUtils.getLong(map, "userId"));
        }
        if (MapUtils.getBoolean(map, "whetherDefault") != null) {
            criteria.andWhetherDefaultEqualTo(MapUtils.getBoolean(map, "whetherDefault"));
        }

        return deliveryAddressMapper.selectByExample(example);
    }

    @Override
    public GoodsDeliveryAddress findDeliveryAddressById(Long id) {
        return deliveryAddressMapper.selectByPrimaryKey(id);
    }

    @Override
    public void deleteDeliveryAddress(Long id) {
        deliveryAddressMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void cleanDeliveryAddressDefault(Long userId) {

        Map<String , Object> map = new HashMap<>();
        map.put("userId" , userId);
        List<GoodsDeliveryAddress> list = getDeliveryAddressList(map);

        if (list.size()>1) {
            for (GoodsDeliveryAddress deliveryAddress : list) {
                deliveryAddress.setWhetherDefault(false);
                updateDeliveryAddress(deliveryAddress);
            }
        }

    }
}
