/*
 *  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 admin.modules.system.service.impl;

import admin.base.PageInfo;
import admin.base.QueryHelpMybatisPlus;
import admin.base.impl.CommonServiceImpl;
import admin.modules.system.domain.Dict;
import admin.modules.system.domain.DictDetail;
import admin.modules.system.service.DictService;
import admin.modules.system.service.dto.DictDetailDto;
import admin.modules.system.service.dto.DictDto;
import admin.modules.system.service.dto.DictQueryCriteria;
import admin.modules.system.service.mapper.DictDetailMapper;
import admin.modules.system.service.mapper.DictMapper;
import admin.utils.*;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.RequiredArgsConstructor;
import org.springframework.cache.annotation.CacheConfig;
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.*;

/**
* @date 2019-04-10
*/
@Service
@RequiredArgsConstructor
@CacheConfig(cacheNames = "dict")
public class DictServiceImpl extends CommonServiceImpl<DictMapper, Dict> implements DictService {

    private final DictMapper dictMapper;
    private final DictDetailMapper detailMapper;
    private final RedisUtils redisUtils;

    @Override
    public PageInfo<DictDto> queryAll(DictQueryCriteria dict, Pageable pageable){
        IPage<Dict> page = PageUtil.toMybatisPage(pageable, false);
        IPage<Dict> pageList = dictMapper.selectPage(page, QueryHelpMybatisPlus.getPredicate(dict));
        return ConvertUtil.convertPage(pageList, DictDto.class);
    }

    @Override
    public List<DictDto> queryAll(DictQueryCriteria dict) {
        List<Dict> list = dictMapper.selectList(QueryHelpMybatisPlus.getPredicate(dict));
        return ConvertUtil.convertList(list, DictDto.class);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void create(Dict resources) {
        dictMapper.insert(resources);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Dict resources) {
        // 清理缓存
        delCaches(resources);
        Dict dict = dictMapper.selectById(resources.getId());
        ValidationUtil.isNull( dict.getId(),"Dict","id",resources.getId());
        resources.setId(dict.getId());
        dictMapper.updateById(resources);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Set<Long> ids) {
        // 清理缓存
        List<Dict> dicts = dictMapper.findByIdIn(ids);
        for (Dict dict : dicts) {
            detailMapper.lambdaUpdate().eq(DictDetail::getDictId, dict.getId()).remove();
            delCaches(dict);
        }
        dictMapper.deleteByIdIn(ids);
    }

    @Override
    public void download(List<DictDto> dictDtos, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (DictDto dictDTO : dictDtos) {
            if(CollectionUtil.isNotEmpty(dictDTO.getDictDetails())){
                for (DictDetailDto 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);
    }

    public void delCaches(Dict dict){
        redisUtils.del("dept::name:" + dict.getName());
    }
}