package com.cf.imes.module.system.service.datasource;

import com.cf.imes.framework.mybatis.core.query.LambdaQueryWrapperX;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import com.cf.imes.module.system.controller.admin.datasource.vo.*;
import com.cf.imes.module.system.dal.dataobject.datasource.DataSourceDO;
import com.cf.imes.framework.common.pojo.PageResult;
import com.cf.imes.framework.common.pojo.PageParam;
import com.cf.imes.framework.common.util.object.BeanUtils;
import com.cf.imes.module.system.dal.mysql.datasource.DataSourceMapper;
import javax.annotation.Resource;
import static com.cf.imes.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.cf.imes.module.system.enums.ErrorCodeConstants.*;

/**
 * 系统数据源 Service 实现类
 *
 * @author 晨丰科技
 */
@Service
@Validated
public class DataSourceServiceImpl implements DataSourceService {

    @Resource
    private DataSourceMapper dataSourceMapper;

    @Override
    public Long createDataSource(DataSourceSaveReqVO createReqVO) {
        // 插入
        DataSourceDO dataSource = BeanUtils.toBean(createReqVO, DataSourceDO.class);
        dataSourceMapper.insert(dataSource);
        // 返回
        return dataSource.getId();
    }

    @Override
    public void updateDataSource(DataSourceSaveReqVO updateReqVO) {
        // 校验存在
        validateDataSourceExists(updateReqVO.getId());
        // 更新
        DataSourceDO updateObj = BeanUtils.toBean(updateReqVO, DataSourceDO.class);
        dataSourceMapper.updateById(updateObj);
    }

    @Override
    public void deleteDataSource(Long id) {
        // 校验存在
        validateDataSourceExists(id);
        // 删除
        dataSourceMapper.deleteById(id);
    }

    private void validateDataSourceExists(Long id) {
        if (dataSourceMapper.selectById(id) == null) {
            throw exception(DATA_SOURCE_NOT_EXISTS);
        }
    }

    @Override
    public DataSourceDO getDataSource(Long id) {
        return dataSourceMapper.selectById(id);
    }

    @Override
    public PageResult<DataSourceDO> getDataSourcePage(DataSourcePageReqVO pageReqVO) {
        return dataSourceMapper.selectPage(pageReqVO);
    }

    @Override
    public List<DataSourceDO> list(Integer type) {
        return dataSourceMapper.selectList(new LambdaQueryWrapperX<DataSourceDO>().eqIfPresent(DataSourceDO::getType, type));
    }

    @Override
    public List<DataSourceRespVO> list() {
        return dataSourceMapper.selectListVO();
    }

}