package com.ruoyi.dxp.service.impl;

import java.util.List;
import java.util.stream.Collectors;

import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.dxp.domain.TableColumn;
import com.ruoyi.dxp.mapper.TableColumnMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.dxp.mapper.TableMapper;
import com.ruoyi.dxp.domain.Table;
import com.ruoyi.dxp.service.ITableService;

/**
 * 数据源-Service业务层处理
 * 
 * @author jy
 * @date 2022-11-07
 */
@Service
public class TableServiceImpl implements ITableService 
{
    @Autowired
    private TableMapper tableMapper;

    @Autowired
    private TableColumnMapper tableColumnMapper;

    /**
     * 查询数据源-
     * 
     * @param id 数据源-主键
     * @return 数据源-
     */
    @Override
    public Table selectTableById(Long id)
    {
        return tableMapper.selectTableById(id);
    }

    /**
     * 查询数据源-列表
     * 
     * @param table 数据源-
     * @return 数据源-
     */
    @Override
    public List<Table> selectTableList(Table table)
    {
        return tableMapper.selectTableList(table);
    }

    /**
     * 新增数据源-
     * 
     * @param table 数据源-
     * @return 结果
     */
    @Override
    public int insertTable(Table table)
    {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        table.setCreateBy(loginUser.getUsername());
        table.setCreateTime(DateUtils.getNowDate());
        return tableMapper.insertTable(table);
    }

    /**
     * 修改数据源-
     * 
     * @param table 数据源-
     * @return 结果
     */
    @Override
    public int updateTable(Table table)
    {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        table.setUpdateBy(loginUser.getUsername());
        table.setUpdateTime(DateUtils.getNowDate());
        return tableMapper.updateTable(table);
    }

    /**
     * 删除数据源-信息
     * 
     * @param id 数据源-主键
     * @return 结果
     */
    @Override
    public int deleteTableById(Long id)
    {
        int result = tableMapper.deleteTableById(id);

        // 同步删除关联的字段
        TableColumn reqC = new TableColumn();
        reqC.setTableId(id);
        List<Long> columnIds = tableColumnMapper.selectTableColumnList(reqC).stream().map(t -> {
            return t.getId();
        }).collect(Collectors.toList());
        if (columnIds != null && columnIds.size() > 0) {
            tableColumnMapper.deleteTableColumnByIds(columnIds.toArray(new Long[0]));
        }

        return result;
    }
}
