package org.springblade.etl.service;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import org.apache.commons.collections4.CollectionUtils;
import org.springblade.datasource.transform.RunnerLoadOne;
import org.springblade.etl.entity.SqlColumn;
import org.springblade.etl.mapper.SqlColumnMapper;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;

/**
 *
 */
@Service
public class SqlColumnService extends ServiceImpl<SqlColumnMapper, SqlColumn> {

    /**
     * 保存或者修改sql类型映射
     */
    public String saveOrUpdateDo(SqlColumn sqlColumn) {

        this.saveOrUpdate(sqlColumn);
        setSqlMap();
        return "操作成功";
    }

    private void setSqlMap() {
        Map<Integer, List<SqlColumn>> sqlColumnMap = new ConcurrentHashMap<>();
        List<SqlColumn> sqlColumnList = this.list();
        Optional.ofNullable(sqlColumnList).ifPresent(list -> list.forEach(v -> {
            List<SqlColumn> sqlColumns = sqlColumnMap.get(v.getDsType());
            if (CollectionUtils.isEmpty(sqlColumns)) {
                sqlColumnMap.put(v.getDsType(), Lists.newArrayList(v));
                return;
            }
            sqlColumns.add(v);
        }));
        if (CollectionUtil.isNotEmpty(sqlColumnMap)) {
            RunnerLoadOne.setInfo(sqlColumnMap);
        }
    }

    /**
     * 删除sql字段对应关系
     */
    public String removeSqlColumns(List<Integer> ids) {

        this.removeBatchByIds(ids);
        setSqlMap();

        return "操作成功";
    }
}




