package com.hfkj.service.goods.impl;

import com.hfkj.dao.GoodsUserAddressMapper;
import com.hfkj.entity.GoodsUserAddress;
import com.hfkj.entity.GoodsUserAddressExample;
import com.hfkj.service.goods.GoodsUserAddressService;
import org.apache.commons.collections4.MapUtils;
import org.springframework.stereotype.Service;

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

@Service("goodsUserAddressService")
public class GoodsUserAddressServiceImpl implements GoodsUserAddressService {

    @Resource
    private GoodsUserAddressMapper goodsUserAddressMapper;

    @Override
    public void create(GoodsUserAddress goodsUserAddress) {
        goodsUserAddressMapper.insert(goodsUserAddress);
    }

    @Override
    public void update(GoodsUserAddress goodsUserAddress) {
        goodsUserAddressMapper.updateByPrimaryKeySelective(goodsUserAddress);
    }

    @Override
    public void delete(Long id) {
        goodsUserAddressMapper.deleteByPrimaryKey(id);
    }

    @Override
    public GoodsUserAddress queryDetail(Long id) {
        return goodsUserAddressMapper.selectByPrimaryKey(id);
    }

    @Override
    public GoodsUserAddress queryDetailByMap(Map<String, Object> map) {
        GoodsUserAddressExample example = new GoodsUserAddressExample();
        GoodsUserAddressExample.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"));
        }

        List<GoodsUserAddress> list = goodsUserAddressMapper.selectByExample(example);

        if (!list.isEmpty()) {
            return list.get(0);
        }

        return null;
    }

    @Override
    public List<GoodsUserAddress> getList(Map<String, Object> map) {
        GoodsUserAddressExample example = new GoodsUserAddressExample();
        GoodsUserAddressExample.Criteria criteria = example.createCriteria();

        if (MapUtils.getLong(map, "userId") != null) {
            criteria.andUserIdEqualTo(MapUtils.getLong(map, "userId"));
        }
        return goodsUserAddressMapper.selectByExample(example);
    }

    @Override
    public void cleanDeliveryAddressDefault(Long userId) {
        Map<String , Object> map = new HashMap<>();
        map.put("userId" , userId);
        List<GoodsUserAddress> list = getList(map);

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

    @Override
    public void insertUserAddressBatch(List<GoodsUserAddress> list) {
        goodsUserAddressMapper.insertAddressList(list);
    }
}
