/*
 *  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 cn.hutool.core.collection.CollectionUtil;
import com.youchain.modules.system.domain.ApiDict;
import com.youchain.modules.system.domain.ApiDictDetail;
import com.youchain.modules.system.repository.ApiDictRepository;
import com.youchain.modules.system.service.ApiDictService;
import com.youchain.modules.system.service.dto.ApiDictDetailDto;
import com.youchain.modules.system.service.dto.ApiDictDto;
import com.youchain.modules.system.service.dto.ApiDictQueryCriteria;

import com.youchain.modules.system.service.mapstruct.ApiDictMapper;
import com.youchain.utils.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

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

    private final ApiDictRepository dictRepository;
    private final ApiDictMapper dictMapper;
    private final RedisUtils redisUtils;

    @Override
    public Map<String, Object> queryAll(ApiDictQueryCriteria dict, Pageable pageable){
        Page<ApiDict> page = dictRepository.findAll((root, query, cb) -> QueryHelp.getPredicate(root, dict, cb), pageable);
        return PageUtil.toPage(page.map(dictMapper::toDto));
    }

    @Override
    public List<ApiDictDto> queryAll(ApiDictQueryCriteria dict) {
        List<ApiDict> list = dictRepository.findAll((root, query, cb) -> QueryHelp.getPredicate(root, dict, cb));
        return dictMapper.toDto(list);
    }

    @Override
    public void queryAllToSave() {
        List<ApiDict> list = dictRepository.findAll();

        RedisUtils redisUtils = SpringContextHolder.getBean(RedisUtils.class);

        for (ApiDict api:list ) {
            List<ApiDictDetail> dictDetails=api.getDictDetails();
            for (ApiDictDetail apiDictDetail:dictDetails) {
                log.info("API字典:    "+api.getName()+"_"+apiDictDetail.getLabel()+"      "+apiDictDetail.getValue());
                redisUtils.del(api.getName()+"_"+apiDictDetail.getLabel());
                redisUtils.set(api.getName()+"_"+apiDictDetail.getLabel(),apiDictDetail.getValue());
            }
        }

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void create(ApiDict resources) {
        dictRepository.save(resources);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(ApiDict resources) {
        // 清理缓存
        delCaches(resources);
        ApiDict dict = dictRepository.findById(resources.getId()).orElseGet(ApiDict::new);
        ValidationUtil.isNull( dict.getId(),"Dict","id",resources.getId());
        dict.setName(resources.getName());
        dict.setDescription(resources.getDescription());
        dictRepository.save(dict);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Set<Long> ids) {
        // 清理缓存
        List<ApiDict> dicts = dictRepository.findByIdIn(ids);
        for (ApiDict dict : dicts) {
            delCaches(dict);
        }
        dictRepository.deleteByIdIn(ids);
    }

    @Override
    public void download(List<ApiDictDto> dictDtos, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (ApiDictDto dictDTO : dictDtos) {
            if(CollectionUtil.isNotEmpty(dictDTO.getDictDetails())){
                for (ApiDictDetailDto dictDetail : dictDTO.getDictDetails()) {
                    Map<String,Object> map = new LinkedHashMap<>();
                    map.put("字典名称", dictDTO.getName());
                    map.put("字典描述", dictDTO.getDescription());
                    map.put("字典标签", dictDetail.getLabel());
                    map.put("字典值", dictDetail.getValue());
                    map.put("创建日期", dictDetail.getCreateTime());
                    list.add(map);
                }
            } else {
                Map<String,Object> map = new LinkedHashMap<>();
                map.put("字典名称", dictDTO.getName());
                map.put("字典描述", dictDTO.getDescription());
                map.put("字典标签", null);
                map.put("字典值", null);
                map.put("创建日期", dictDTO.getCreateTime());
                list.add(map);
            }
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    public ApiDict getDictDescription(String name) {
        return dictRepository.getDictDescription(name);
    }

    public void delCaches(ApiDict dict){
        redisUtils.del(CacheKey.DICT_NAME + dict.getName());
    }
}