package com.template.services.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.template.common.utils.CommonUtil;
import com.template.mapper.SmartDataClassMapper;
import com.template.mapper.SmartDataSourceMapper;
import com.template.model.pojo.SmartDataClass;
import com.template.model.pojo.SmartDataSource;
import com.template.model.pojo.SmartDataTask;
import com.template.services.SmartDataSourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.stereotype.Service;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import static org.hibernate.validator.internal.util.Contracts.assertNotNull;

/**
 * <p>
 * 数据源配置 服务实现类
 * </p>
 *
 * @author ceshi
 * @since 2023-12-05
 */
@Service
public class SmartDataSourceServiceImpl extends ServiceImpl<SmartDataSourceMapper, SmartDataSource> implements SmartDataSourceService {

    @Autowired
    private SmartDataSourceMapper smartDataSourceMapper;

    @Autowired
    private SmartDataClassMapper smartDataClassMapper;

    private final static DriverManagerDataSource dataSource = new DriverManagerDataSource();

    /**
     * 添加数据源
     *
     * @param smartDataSource 数据源对象
     * @return 返回
     */
    @Override
    public Map<String, Object> insertSmartDataSource(SmartDataSource smartDataSource) {
        // 检测参数，还有是否存在重复记录
        if (smartDataSource.getDsClsId() == null) {
            return CommonUtil.getReturnMap("1", "【数据源类型id】不能为空！");
        }
        SmartDataClass smartDataClass = smartDataClassMapper.selectById(smartDataSource.getDsClsId());
        if (smartDataClass == null) {
            return CommonUtil.getReturnMap("1", "选择的【数据源类型】不存在！");
        }

        if (smartDataSource.getDsName() == null) {
            return CommonUtil.getReturnMap("1", "【数据源名称】不能为空！");
        }
        if (smartDataSource.getDsUrl() == null) {
            return CommonUtil.getReturnMap("1", "【数据源连接地址】不能为空！");
        }
        if (smartDataSource.getDsUser() == null) {
            return CommonUtil.getReturnMap("1", "【数据源用户】不能为空！");
        }
        if (smartDataSource.getDsPassword() == null) {
            return CommonUtil.getReturnMap("1", "【数据源密码】不能为空！");
        }
        if (smartDataSource.getDsDescrition() == null) {
            return CommonUtil.getReturnMap("1", "【数据源描述】不能为空！");
        }

        QueryWrapper<SmartDataSource> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(smartDataSource.getDsClsId() != null, "ds_cls_id", smartDataSource.getDsClsId());
        queryWrapper.eq(smartDataSource.getDsName() != null, "ds_name", smartDataSource.getDsName());
        queryWrapper.eq(smartDataSource.getDsUrl() != null, "ds_url", smartDataSource.getDsUrl());
        queryWrapper.eq(smartDataSource.getDsUser() != null, "ds_user", smartDataSource.getDsUser());
        queryWrapper.eq(smartDataSource.getDsPassword() != null, "ds_password", smartDataSource.getDsPassword());
        queryWrapper.eq(smartDataSource.getDsStatus() != null, "ds_status", smartDataSource.getDsStatus());
        queryWrapper.eq(smartDataSource.getDsDescrition() != null, "ds_descrition", smartDataSource.getDsDescrition());
        List<SmartDataSource> smartDataSources = smartDataSourceMapper.selectList(queryWrapper);
        if (smartDataSources.size() > 0) {
            return CommonUtil.getReturnMap("1", "有重复记录！");
        }

        Map<String, Object> stringObjectMap = vcoSmartDataSource(smartDataSource);
        if ("1".equals(stringObjectMap.get("code"))) {
            smartDataSource.setDsStatus(0);
        } else {
            smartDataSource.setDsStatus(1);
        }

        // 必填的参数不为null，则进行新增操作
        int result = smartDataSourceMapper.insert(smartDataSource);
        if (result > 0) {
            return CommonUtil.getReturnMap("0", "数据源添加成功！");
        } else {
            return CommonUtil.getReturnMap("1", "数据源添加失败！");
        }
    }

    /**
     * 修改数据源
     *
     * @param smartDataSource 数据源对象
     * @return 返回
     */
    @Override
    public Map<String, Object> updateSmartDataSource(SmartDataSource smartDataSource) {
        // 检测参数，还有是否存在重复记录
        if (smartDataSource.getDsId() == null) {
            return CommonUtil.getReturnMap("1", "【数据源id】不能为空！");
        }
        SmartDataSource sdc = smartDataSourceMapper.selectById(smartDataSource.getDsId());
        if (sdc == null) {
            return CommonUtil.getReturnMap("1", "要修改的【数据源】不存在！");
        }
        // 检测必要参数是否为null
        if (smartDataSource.getDsClsId() == null) {
            return CommonUtil.getReturnMap("1", "【数据源类型id】不能为空！");
        }
        SmartDataClass smartDataClass = smartDataClassMapper.selectById(smartDataSource.getDsClsId());
        if (smartDataClass == null) {
            return CommonUtil.getReturnMap("1", "选择的【数据源类型】不存在！");
        }

        if (smartDataSource.getDsName() == null) {
            return CommonUtil.getReturnMap("1", "【数据源名称】不能为空！");
        }
        if (smartDataSource.getDsUrl() == null) {
            return CommonUtil.getReturnMap("1", "【数据源连接地址】不能为空！");
        }
        if (smartDataSource.getDsUser() == null) {
            return CommonUtil.getReturnMap("1", "【数据源用户】不能为空！");
        }
        if (smartDataSource.getDsPassword() == null) {
            return CommonUtil.getReturnMap("1", "【数据源密码】不能为空！");
        }
        if (smartDataSource.getDsDescrition() == null) {
            return CommonUtil.getReturnMap("1", "【数据源描述】不能为空！");
        }
        QueryWrapper<SmartDataSource> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(smartDataSource.getDsId() != null, "ds_id", smartDataSource.getDsId());
        queryWrapper.eq(smartDataSource.getDsClsId() != null, "ds_cls_id", smartDataSource.getDsClsId());
        queryWrapper.eq(smartDataSource.getDsName() != null, "ds_name", smartDataSource.getDsName());
        queryWrapper.eq(smartDataSource.getDsUrl() != null, "ds_url", smartDataSource.getDsUrl());
        queryWrapper.eq(smartDataSource.getDsUser() != null, "ds_user", smartDataSource.getDsUser());
        queryWrapper.eq(smartDataSource.getDsPassword() != null, "ds_password", smartDataSource.getDsPassword());
        queryWrapper.eq(smartDataSource.getDsStatus() != null, "ds_status", smartDataSource.getDsStatus());
        queryWrapper.eq(smartDataSource.getDsDescrition() != null, "ds_descrition", smartDataSource.getDsDescrition());
        List<SmartDataSource> smartDataSources = smartDataSourceMapper.selectList(queryWrapper);
        if (smartDataSources.size() > 0) {
            return CommonUtil.getReturnMap("1", "数据未修改，请修改后再提交！");
        }

        Map<String, Object> stringObjectMap = vcoSmartDataSource(smartDataSource);
        if ("1".equals(stringObjectMap.get("code"))) {
            smartDataSource.setDsStatus(0);
        } else {
            smartDataSource.setDsStatus(1);
        }

        int result = smartDataSourceMapper.updateById(smartDataSource);
        if (result > 0) {
            return CommonUtil.getReturnMap("0", "数据源修改成功！");
        } else {
            return CommonUtil.getReturnMap("1", "数据源修改失败！");
        }
    }

    /**
     * 数据源分页数据
     *
     * @param currentPage     当前页码
     * @param pageCount       每页显示数据条数
     * @param smartDataSource 数据源对象
     * @return 返回
     */
    @Override
    public PageInfo<SmartDataSource> queryPageSmartDataSources(int currentPage, int pageCount, SmartDataSource smartDataSource) {
        PageHelper.startPage(currentPage, pageCount);
        List<SmartDataSource> result = smartDataSourceMapper.selectPageDsSource(smartDataSource);
        return new PageInfo<>(result);
    }

    /**
     * 根据id删除数据源
     *
     * @param id 数据源id
     * @return 返回
     */
    @Override
    public int deleteSmartDataSourceById(int id) {
        return smartDataSourceMapper.deleteById(id);
    }

    @Override
    public SmartDataSource getSmartById(int id) {
        return smartDataSourceMapper.selectById(id);
    }

    /**
     * 验证数据源是否连接成功，是否是有效的连接
     *
     * @param smartDataSource 数据源对象
     * @return 返回
     */
    @Override
    public Map<String, Object> vcoSmartDataSource(SmartDataSource smartDataSource) {
        // 设置数据源信息
        if (smartDataSource.getDsClsId() == null) {
            return CommonUtil.getReturnMap("1", "【数据源类型id】不能为空！");
        }
        SmartDataClass smartDataClass = smartDataClassMapper.selectById(smartDataSource.getDsClsId());
        if (smartDataClass == null) {
            return CommonUtil.getReturnMap("1", "选择的【数据源类型】不存在！");
        }

        dataSource.setDriverClassName(smartDataClass.getDsClsDriver());
        dataSource.setUrl(smartDataSource.getDsUrl());
        dataSource.setUsername(smartDataSource.getDsUser());
        dataSource.setPassword(smartDataSource.getDsPassword());

        // 尝试获取数据库连接
        Connection connection = null;
        try {
            connection = dataSource.getConnection();
            assertNotNull(connection);
            return CommonUtil.getReturnMap(String.valueOf(0), "连接成功！");
        } catch (SQLException e) {
            return CommonUtil.getReturnMap(String.valueOf(1), "连接失败：" + e.getMessage());
        } finally {
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
