package easydo.technology.system.service.impl;

import java.util.List;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import easydo.technology.system.domain.Dict;
import easydo.technology.system.domain.DictDetail;
import easydo.technology.system.dto.DictDetailDto;
import easydo.technology.system.dto.DictDetailQueryParam;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import easydo.technology.base.PageInfo;
import easydo.technology.base.QueryHelpMybatisPlus;
import easydo.technology.base.impl.CommonServiceImpl;
import easydo.technology.system.mapper.DictDetailMapper;
import easydo.technology.system.mapper.DictMapper;
import easydo.technology.system.service.DictDetailService;
import easydo.technology.utils.ConvertUtil;
import easydo.technology.utils.PageUtil;
import easydo.technology.utils.RedisUtils;
import lombok.AllArgsConstructor;

// 默认不使用缓存
//import org.springframework.cache.annotation.CacheConfig;
//import org.springframework.cache.annotation.CacheEvict;
//import org.springframework.cache.annotation.Cacheable;

/**
* @author jinjin
* @date 2020-09-24
*/
@Service
@AllArgsConstructor
//@CacheConfig(cacheNames = "dictDetail")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class DictDetailServiceImpl extends CommonServiceImpl<DictDetail> implements DictDetailService {

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

    @Override
    //@Cacheable
    public PageInfo<DictDetailDto> queryAll(DictDetailQueryParam query, Pageable pageable) {
        IPage<DictDetail> page = PageUtil.toMybatisPage(pageable);
        IPage<DictDetail> pageList = dictDetailMapper.selectPage(page, QueryHelpMybatisPlus.getPredicate(query));
        return ConvertUtil.convertPage(pageList, DictDetailDto.class);
    }

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

    @Override
    public List<DictDetailDto> getDictByName(String dictName) {
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(Dict::getName, dictName);
        Dict dict = dictMapper.selectOne(wrapper);
        DictDetailDto detailDto = new DictDetailDto();
        detailDto.setDictName(dictName);
        List<DictDetailDto> ret = dictDetailMapper.getDictDetailsByDictName(detailDto);
        redisUtils.set("dictDetail::dictId:"+dict.getId(), ret);
        return ret;
    }

    @Override
    public PageInfo<DictDetailDto> getDictByName(String dictName, Pageable pageable) {
        IPage<DictDetailDto> page = PageUtil.toMybatisPage(pageable, true);
        return ConvertUtil.convertPage(dictDetailMapper.getDictDetailsByDictName(dictName, page), DictDetailDto.class);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateById(DictDetailDto resources) {
        DictDetail detail = ConvertUtil.convert(resources, DictDetail.class);
        boolean ret = dictDetailMapper.updateById(detail) > 0;
        // 清理缓存
        delCaches(detail.getDictId());
        return ret;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean save(DictDetailDto resources){
        DictDetail detail = ConvertUtil.convert(resources, DictDetail.class);
        detail.setDictId(resources.getDict().getId());
        boolean ret = dictDetailMapper.insert(detail) > 0;
        // 清理缓存
        delCaches(detail.getDictId());
        return ret;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removeById(Long id) {
        DictDetail dictDetail = dictDetailMapper.selectById(id);
        boolean ret = dictDetailMapper.deleteById(id) > 0;
        // 清理缓存
        delCaches(dictDetail.getDictId());
        return ret;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removeByDictId(Long id) {
        UpdateWrapper<DictDetail> wrapper1 = new UpdateWrapper<>();
        wrapper1.lambda().eq(DictDetail::getDictId, id);
        boolean ret = dictDetailMapper.delete(wrapper1) > 0;
        delCaches(id);
        return ret;
    }

    private void delCaches(Long dictId){
        redisUtils.del("dictDetail::dictId:" + dictId);
    }


    /**
     * 根据父表 dictId 和 子表 detailLabel 查询 dictDetail 相关行数据信息*
     * @param dictId
     * @param dictDetailLabel
     * @return
     */
    @Override
    public DictDetail getDictIdAndDictName(String dictId, String dictDetailLabel){
        //查询数据库中是否存在
        DictDetail dictDetail = dictDetailMapper.selectOne(Wrappers.<DictDetail>lambdaQuery()
                .eq(DictDetail::getLabel, dictDetailLabel)
                .eq(DictDetail::getDictId, dictId));
        if(ObjectUtils.isEmpty(dictDetail)){
            dictDetail = new DictDetail();
        }
        return dictDetail;
    }

    /**
     * 获取dict*
     * @param dictName
     * @return
     */
    @Override
    public Dict getDictByDictName(String dictName){
        //检查是否存在健康指标字段
        Dict dict = dictMapper.selectOne(Wrappers.<Dict>lambdaQuery()
                .eq(Dict::getName, dictName).last("limit 1"));
        if(ObjectUtils.isEmpty(dict)){
            dict = new Dict();
        }
        return dict;
    }
}
