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

import cn.datax.common.core.DataConstant;
import cn.datax.common.exception.DataException;
import cn.datax.service.data.visual.api.entity.ChartEntity;
import cn.datax.service.data.visual.api.dto.ChartDto;
import cn.datax.service.data.visual.service.ChartService;
import cn.datax.service.data.visual.mapstruct.ChartMapper;
import cn.datax.service.data.visual.dao.ChartDao;
import cn.datax.common.base.BaseServiceImpl;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
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.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

/**
 * <p>
 * 可视化图表配置信息表 服务实现类
 * </p>
 *
 * @author yuwei
 * @since 2020-11-04
 */
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class ChartServiceImpl extends BaseServiceImpl<ChartDao, ChartEntity> implements ChartService {

    @Autowired
    private ChartDao chartDao;

    @Autowired
    private ChartMapper chartMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ChartEntity saveChart(ChartDto chartDto) {
        ChartEntity chart = chartMapper.toEntity(chartDto);
        chartDao.insert(chart);
        return chart;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ChartEntity updateChart(ChartDto chartDto) {
        ChartEntity chart = chartMapper.toEntity(chartDto);
        chartDao.updateById(chart);
        return chart;
    }

    @Override
    public ChartEntity getChartById(String id) {
        ChartEntity chartEntity = super.getById(id);
        return chartEntity;
    }

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

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

    @Override
    public void copyChart(String id) {
        ChartEntity chartEntity = Optional.ofNullable(super.getById(id)).orElseThrow(() -> new DataException("获取失败"));
        ChartEntity copy = new ChartEntity();
        copy.setChartName(chartEntity.getChartName() + "_副本" + DateUtil.format(LocalDateTime.now(), DatePattern.PURE_DATETIME_PATTERN));
        copy.setChartThumbnail(chartEntity.getChartThumbnail());
        copy.setChartConfig(chartEntity.getChartConfig());
        copy.setStatus(DataConstant.EnableState.ENABLE.getKey());
        chartDao.insert(copy);
    }
}
