'use strict';

// 新增数据源
function addDataSource(opts) {
    return async function (ctx, next) {

        const models = ctx.fs.dc.models;
        try {
            const { name, mountPath } = ctx.request.body
            const checkName = await models.DataSource.findOne({ where: { name: name } });
            const checkMountPath = await models.DataSource.findOne({ where: { mountPath: mountPath } });
            if (checkName) {
                ctx.status = 400;
                ctx.body = { message: '该数据源名称已存在' }
            } else if (checkMountPath) {
                ctx.status = 400;
                ctx.body = { message: '该资源路径已被使用' }
            } else {
                let rslt = ctx.request.body;
                await models.DataSource.create(Object.assign({}, rslt))
                let datasource = await models.DataSource.findOne({ where: { name } })
                ctx.status = 200;
                ctx.body = { message: '新建数据源成功', id: datasource.id }
            }
        } catch (error) {
            ctx.fs.logger.error(`path: ${ctx.path}, error: ${error}`);
            ctx.status = 400;
            ctx.body = { message: '新建数据源失败' }
        }
    }
}

function getDataSource(opts) {
    return async function (ctx, next) {

        const models = ctx.fs.dc.models;
        const { page, limit, name } = ctx.query;
        let errMsg = { message: '获取数据源失败' }
        const Op = ctx.fs.dc.ORM.Op;
        try {
            let searchWhere = {}
            let option = {
                where: searchWhere,
                order: [["id", "desc"]],
                include: [
                    { model: models.Adapter },
                    { model: models.ResourceCatalog },
                ]
            }

            if (name) {
                searchWhere.name = {
                    // 模糊查询
                    [Op.like]: '%' + name + '%',
                };
            }

            option.where = searchWhere

            let limit_ = limit || 10;
            let page_ = page || 1;
            let offset = (page_ - 1) * limit_;
            if (limit && page) {
                option.limit = limit_
                option.offset = offset
            }

            const res = await models.DataSource.findAndCount(option);
            ctx.status = 200;
            ctx.body = res;
        } catch (error) {
            ctx.fs.logger.error(`path: ${ctx.path}, error: ${error}`);
            ctx.status = 400;
            ctx.body = errMsg
        }
    }
}


// 修改数据源
function editDataSource(opts) {
    return async function (ctx, next) {

        try {
            const models = ctx.fs.dc.models;
            const { id } = ctx.params;
            const body = ctx.request.body;
            const { name } = ctx.request.body
            const checkName = await models.DataSource.findOne({ where: { id: { $not: id }, name, name } });
            if (checkName) {
                ctx.status = 400;
                ctx.body = { message: '该数据源名称已存在' }
            } else {
                await models.DataSource.update(
                    body,
                    { where: { id: id, } }
                )
                ctx.status = 204;
                ctx.body = { message: '修改数据源成功' }
            }
        } catch (error) {
            ctx.fs.logger.error(`path: ${ctx.path}, error: ${error}`);
            ctx.status = 400;
            ctx.body = { message: '修改数据源失败' }
        }
    }
}

// 删除数据源
function deleteDataSource(opts) {
    return async function (ctx, next) {

        try {
            const models = ctx.fs.dc.models;
            const { id } = ctx.params;
            const task = await models.AcquisitionTask.findOne({
                where: {
                    dataSourceId: id
                }
            })

            if (task) {
                ctx.status = 400;
                ctx.body = { message: '数据源下存在采集任务,请删除任务后再删除数据源!' }
            } else {
                const datasource = await models.DataSource.findOne({ where: { id: id } })
                await models.DataSource.destroy({
                    where: {
                        id: id
                    }
                })

                //删除数据源绑定的资源目录下的元数据
                await models.MetadataDatabase.destroy({
                    where: {
                        catalog: datasource.mountPath,
                    }
                })

                ctx.status = 204;
                ctx.body = { message: '删除数据源成功' }
            }
        } catch (error) {
            ctx.fs.logger.error(`path: ${ctx.path}, error: ${error}`);
            ctx.status = 400;
            ctx.body = { message: '删除数据源失败' }
        }
    }
}

module.exports = {
    addDataSource,
    getDataSource,
    editDataSource,
    deleteDataSource
}