/*
 *  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.DictDetailService;
import admin.modules.system.service.dto.DictDetailDto;
import admin.modules.system.service.dto.DictDetailQueryCriteria;
import admin.modules.system.service.mapper.DictDetailMapper;
import admin.modules.system.service.mapper.DictMapper;
import admin.utils.ConvertUtil;
import admin.utils.PageUtil;
import admin.utils.RedisUtils;
import admin.utils.ValidationUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.RequiredArgsConstructor;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
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;
import java.util.stream.Collectors;

/**
* @date 2019-04-10
*/
@Service
@RequiredArgsConstructor
@CacheConfig(cacheNames = "dict")
public class DictDetailServiceImpl extends CommonServiceImpl<DictDetailMapper, DictDetail> implements DictDetailService {

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

    @Override
    public PageInfo<DictDetailDto> queryAll(DictDetailQueryCriteria criteria, Pageable pageable) {
        QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", criteria.getDictName());
        List<Dict> dicts = dictMapper.selectList(queryWrapper);
        IPage<DictDetail> page = PageUtil.toMybatisPage(pageable, false);
        if(dicts.size()>0) {
            QueryWrapper<DictDetail> predicate = QueryHelpMybatisPlus.getPredicate(criteria);
            predicate.in("dict_id", dicts.stream().map(Dict::getId).collect(Collectors.toList()));
            IPage<DictDetail> pageList = dictDetailMapper.selectPage(page, predicate);
            return ConvertUtil.convertPage(pageList, DictDetailDto.class);
        }
        return new PageInfo<>();
    }

    @Override
    public List<DictDetailDto> queryAll(DictDetailQueryCriteria query) {
        return ConvertUtil.convertList(dictDetailMapper.selectList(QueryHelpMybatisPlus.getPredicate(query)), DictDetailDto.class);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void create(DictDetail resources) {
        dictDetailMapper.insert(resources);
        // 清理缓存
        delCaches(resources);
    }

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

    @Override
    @Cacheable(key = "'name:' + #p0")
    public List<DictDetailDto> getDictByName(String name) {
        List<DictDetail> byDictName = dictDetailMapper.findByDictName(name);
        return ConvertUtil.convertList(byDictName, DictDetailDto.class);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Long id) {
        DictDetail dictDetail = dictDetailMapper.selectById(id);
        // 清理缓存
        delCaches(dictDetail);
        dictDetailMapper.deleteById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addAll(String json) {
        List<DictDetail> list = JSONObject.parseArray(json,  DictDetail.class);
        for (DictDetail dictDetail:list){
            dictDetail.setDictId(18L);
            dictDetail.setDictSort(999);
            this.create(dictDetail);
        }
    }

    @Override
    public DictDetailDto findById(Long id) {
        DictDetail dictDetail = dictDetailMapper.selectById(id);
        ValidationUtil.isNull(dictDetail.getId(),"DictDetail","dictDetail",id);
        return ConvertUtil.convert(dictDetail, DictDetailDto.class);
    }

    @Override
    public Map<String, Object> getXcx() {
        DictDetailQueryCriteria criteria = new DictDetailQueryCriteria();
        criteria.setDictName("xcx_config");
        QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", criteria.getDictName());
        List<Dict> dicts = dictMapper.selectList(queryWrapper);
        Map<String, Object> map = new HashMap<>();
        if(dicts.size()>0) {
            QueryWrapper<DictDetail> predicate = QueryHelpMybatisPlus.getPredicate(criteria);
            predicate.in("dict_id", dicts.stream().map(Dict::getId).collect(Collectors.toList()));
            List<DictDetail> dictDetailList = dictDetailMapper.selectList(predicate);
            if(dictDetailList!=null&&dictDetailList.size()>0){
                dictDetailList.forEach(v->{
                    map.put(v.getXcxKey(),v.getValue());
                });
            }
        }
        return map;
    }

    @Override
    public DictDetail getDictByNameOne(String label) {
        DictDetailQueryCriteria criteria = new DictDetailQueryCriteria();
        criteria.setLabelEq(label);
        return dictDetailMapper.selectOne(QueryHelpMybatisPlus.getPredicate(criteria));
    }

    public void delCaches(DictDetail dictDetail){
        Dict dict = dictMapper.selectById(dictDetail.getDictId());
        redisUtils.del("dept::name:" + dict.getName());
    }
}
