package cn.datax.service.data.metadata.service.impl;

import cn.datax.common.core.DataConstant;
import cn.datax.common.core.RedisConstant;
import cn.datax.common.redis.service.RedisService;
import cn.datax.service.data.metadata.api.dto.MetadataColumnDto;
import cn.datax.service.data.metadata.api.entity.MetadataColumnEntity;
import cn.datax.service.data.metadata.api.entity.MetadataSourceEntity;
import cn.datax.service.data.metadata.api.entity.MetadataTableEntity;
import cn.datax.service.data.metadata.api.enums.DataLevel;
import cn.datax.service.data.metadata.api.query.MetadataColumnQuery;
import cn.datax.service.data.metadata.api.vo.MetadataTreeVo;
import cn.datax.service.data.metadata.service.MetadataColumnService;
import cn.datax.service.data.metadata.mapstruct.MetadataColumnMapper;
import cn.datax.service.data.metadata.dao.MetadataColumnDao;
import cn.datax.common.base.BaseServiceImpl;
import cn.hutool.core.util.StrUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * <p>
 * 元数据信息表 服务实现类
 * </p>
 *
 * @author yuwei
 * @since 2020-07-29
 */
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class MetadataColumnServiceImpl extends BaseServiceImpl<MetadataColumnDao, MetadataColumnEntity> implements MetadataColumnService {

    @Autowired
    private MetadataColumnDao metadataColumnDao;

    @Autowired
    private MetadataColumnMapper metadataColumnMapper;

    @Autowired
    private RedisService redisService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public MetadataColumnEntity saveMetadataColumn(MetadataColumnDto metadataColumnDto) {
        MetadataColumnEntity metadataColumn = metadataColumnMapper.toEntity(metadataColumnDto);
        metadataColumnDao.insert(metadataColumn);
        return metadataColumn;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public MetadataColumnEntity updateMetadataColumn(MetadataColumnDto metadataColumnDto) {
        MetadataColumnEntity metadataColumn = metadataColumnMapper.toEntity(metadataColumnDto);
        metadataColumnDao.updateById(metadataColumn);
        return metadataColumn;
    }

    @Override
    public MetadataColumnEntity getMetadataColumnById(String id) {
        MetadataColumnEntity metadataColumnEntity = super.getById(id);
        return metadataColumnEntity;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteMetadataColumnById(String id) {
        metadataColumnDao.deleteById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteMetadataColumnBatch(List<String> ids) {
        metadataColumnDao.deleteBatchIds(ids);
    }

    @Override
    public List<MetadataTreeVo> getDataMetadataTree(String level, MetadataColumnQuery metadataColumnQuery) {
        List<MetadataSourceEntity> sourceList = (List<MetadataSourceEntity>) redisService.get(RedisConstant.METADATA_SOURCE_KEY);
        Stream<MetadataSourceEntity> stream = Optional.ofNullable(sourceList).orElseGet(ArrayList::new).stream().filter(s -> DataConstant.EnableState.ENABLE.getKey().equals(s.getStatus()));
        if (StrUtil.isNotBlank(metadataColumnQuery.getSourceId())) {
            stream = stream.filter(s -> metadataColumnQuery.getSourceId().equals(s.getId()));
        }
        List<MetadataTreeVo> list = stream.map(m -> {
                    MetadataTreeVo tree = new MetadataTreeVo();
                    tree.setId(m.getId());
                    tree.setType(DataLevel.DATABASE.getKey());
                    tree.setLabel(m.getSourceName());
                    if (DataLevel.getLevel(level).getLevel() >= DataLevel.TABLE.getLevel()) {
                        tree.setChildren(getTableChildrens(m.getId(), level, metadataColumnQuery.getTableId()));
                    }
                    return tree;
                }).collect(Collectors.toList());
        return list;
    }

    private List<MetadataTreeVo> getTableChildrens(String id, String level, String tableId) {
        List<MetadataTableEntity> tableList = (List<MetadataTableEntity>) redisService.hget(RedisConstant.METADATA_TABLE_KEY, id);
        Stream<MetadataTableEntity> stream = Optional.ofNullable(tableList).orElseGet(ArrayList::new).stream();
        if (StrUtil.isNotBlank(tableId)) {
            stream = stream.filter(s -> tableId.equals(s.getId()));
        }
        List<MetadataTreeVo> children = stream.map(m -> {
                    MetadataTreeVo tree = new MetadataTreeVo();
                    tree.setId(m.getId());
                    tree.setType(DataLevel.TABLE.getKey());
                    tree.setLabel(StrUtil.isBlank(m.getTableComment()) ? m.getTableName() : m.getTableComment());
                    if (DataLevel.getLevel(level).getLevel() >= DataLevel.COLUMN.getLevel()) {
                        tree.setChildren(getColumnChildrens(m.getId()));
                    }
                    return tree;
                }).collect(Collectors.toList());
        return children;
    }

    private List<MetadataTreeVo> getColumnChildrens(String id) {
        List<MetadataColumnEntity> columnList = (List<MetadataColumnEntity>) redisService.hget(RedisConstant.METADATA_COLUMN_KEY, id);
        List<MetadataTreeVo> children = Optional.ofNullable(columnList).orElseGet(ArrayList::new).stream()
                .map(m -> {
                    MetadataTreeVo tree = new MetadataTreeVo();
                    tree.setId(m.getId());
                    tree.setType(DataLevel.TABLE.getKey());
                    tree.setLabel(StrUtil.isBlank(m.getColumnComment()) ? m.getColumnName() : m.getColumnComment());
                    return tree;
                }).collect(Collectors.toList());
        return children;
    }
}
