/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.youchain.modules.system.service.impl;

import com.youchain.modules.system.domain.ApiDict;
import com.youchain.modules.system.domain.ApiDictDetail;
import com.youchain.modules.system.repository.ApiDictDetailRepository;
import com.youchain.modules.system.repository.ApiDictRepository;
import com.youchain.modules.system.service.ApiDictDetailService;
import com.youchain.modules.system.service.ApiDictService;
import com.youchain.modules.system.service.dto.ApiDictDetailDto;
import com.youchain.modules.system.service.dto.ApiDictDetailQueryCriteria;
import com.youchain.modules.system.service.mapstruct.ApiDictDetailMapper;
import com.youchain.utils.*;
import lombok.RequiredArgsConstructor;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
* @author Liu Xue
* @date 2019-04-10
*/
@Service
@RequiredArgsConstructor
@CacheConfig(cacheNames = "dict")
public class ApiDictDetailServiceImpl implements ApiDictDetailService {

    private final ApiDictRepository dictRepository;
    private final ApiDictDetailRepository dictDetailRepository;
    private final ApiDictDetailMapper dictDetailMapper;
    private final RedisUtils redisUtils;
    private final ApiDictService dictService;
    @Override
    public Map<String,Object> queryAll(ApiDictDetailQueryCriteria criteria, Pageable pageable) {
        Page<ApiDictDetail> page = dictDetailRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(dictDetailMapper::toDto));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void create(ApiDictDetail resources) {
        dictDetailRepository.save(resources);
        dictService.queryAllToSave();
        // 清理缓存
        delCaches(resources);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(ApiDictDetail resources) {
        ApiDictDetail dictDetail = dictDetailRepository.findById(resources.getId()).orElseGet(ApiDictDetail::new);
        ValidationUtil.isNull( dictDetail.getId(),"DictDetail","id",resources.getId());
        resources.setId(dictDetail.getId());
        dictDetailRepository.save(resources);
        dictService.queryAllToSave();
        // 清理缓存
        delCaches(resources);
    }

    @Override
    @Cacheable(key = "'name:' + #p0")
    public List<ApiDictDetailDto> getDictByName(String name) {
        return dictDetailMapper.toDto(dictDetailRepository.findByDictName(name));
    }

    @Override
    @Cacheable(key = "'name:' + #p0")
    public Map<String,ApiDictDetail> getDictDetailByName(String name) {
       List<ApiDictDetail> list= dictDetailRepository.findByDictName(name);
       Map<String,ApiDictDetail> map=new HashMap<>();
        for (ApiDictDetail d: list  ) {
            map.put(d.getLabel(),d);
        }
        return map;
    }



    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Long id) {
        ApiDictDetail dictDetail = dictDetailRepository.findById(id).orElseGet(ApiDictDetail::new);
        // 清理缓存
        delCaches(dictDetail);
        dictService.queryAllToSave();
        dictDetailRepository.deleteById(id);
    }

    public void delCaches(ApiDictDetail dictDetail){
        ApiDict dict = dictRepository.findById(dictDetail.getDict().getId()).orElseGet(ApiDict::new);
        redisUtils.del(CacheKey.DICT_NAME + dict.getName());
    }
}