package cn.quantgroup.xyqb.service.user.impl;

import cn.quantgroup.xyqb.entity.Address;
import cn.quantgroup.xyqb.repository.IAddressRepository;
import cn.quantgroup.xyqb.service.user.IAddressService;
import cn.quantgroup.xyqb.util.AddressFilter;
import cn.quantgroup.xyqb.util.EmojiUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.util.List;

/**
 * Created by Miraculous on 2017/1/3.
 */
@Service
public class AddressServiceImpl implements IAddressService {

    @Autowired
    private IAddressRepository addressRepository;

    @Override
//    @Cacheable(value = "addresscache", key = "'address' + #userId", unless = "#result == null", cacheManager = "cacheManager")
    public Address findByUserId(Long userId) {
        Address address = addressRepository.findByUserId(userId);
        //过滤特殊字符
        if (null != address && null != address.getAddress() && AddressFilter.isIncSpeChar(address.getAddress())) {

            address.setAddress(AddressFilter.filterAddress(address.getAddress()));

        }
        return address;
    }

    @Override
    @CacheEvict(value = "addresscache", key = "'address' + #addressObj.userId", cacheManager = "cacheManager")
    public Address save(Address addressObj) {
        /* 替换所有,UTF-8编码时4字节的Emoji表情字符 */
        addressObj.setProvince(EmojiUtil.filterUnicode4(addressObj.getProvince()));
        addressObj.setCity(EmojiUtil.filterUnicode4(addressObj.getCity()));
        addressObj.setDistrict(EmojiUtil.filterUnicode4(addressObj.getDistrict()));
        addressObj.setAddress(EmojiUtil.filterUnicode4(addressObj.getAddress()));
        return addressRepository.save(addressObj);
    }

    @Override
    public List<Address> findByUserIds(List<Long> userIds) {
        return addressRepository.findAll((root, query, cb) -> {
            query.where(root.get("userId").in(userIds));
            return query.getRestriction();
        });
    }
}
