'use strict';
const request = require('superagent')
const moment = require('moment');
function getBackupsList(opts) {
    return async function (ctx, next) {

        const models = ctx.fs.dc.models;
        const { page, limit, name } = ctx.query;
      
        let errMsg = { message: '获取数据备份失败' }
        try {
            let searchWhere = {

            }
            let option = {
                where: searchWhere,
                order: [["id", "desc"]],
                attributes: { exclude: ['password'] },
            }

            if (name) {
                searchWhere.note = { $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.Backups.findAndCount(option);
            res.time = moment()
            ctx.status = 200;
            ctx.body = res;
        } catch (error) {
            ctx.fs.logger.error(`path: ${ctx.path}, error: ${error}`);
            ctx.status = 400;
            ctx.body = errMsg
        }
    }
}

// 新增数据备份
function addBackups(opts) {
    return async function (ctx, next) {
        const { backupsUrl } = opts;
        const models = ctx.fs.dc.models;
        try {
            let rslt = ctx.request.body;
            const { database, host, password, port, user } = ctx.request.body.databases
            let backup = await models.Backups.create(Object.assign({}, rslt))

            //调用后端备份接口
            // const url = '10.8.30.160:8085/dumpDB?dbHost=10.8.30.75&dbPort=5432&user=postgres&password=1234&dbName=Anxinyun0916'//测试使用
            const url = backupsUrl + `/dumpDB?dbHost=${host}&dbPort=${port}&user=${user}&password=${password}&dbName=${database}`;
            request.post(url).then(res => {
                const { fileInfo: { name, size }, code, message } = res.body
                models.Backups.update({
                    size, source: name, state: code == 200 ? '备份成功' : '备份失败', completeTime: moment(),
                    log: code == 200 ? '' : message
                }, { where: { id: backup.id } })
                if (code != 200) ctx.fs.logger.error(`path: ${ctx.path}, error: ${message}`);
            })

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

// 修改数据备份
function editBackups(opts) {
    return async function (ctx, next) {

        try {
            const models = ctx.fs.dc.models;
            const { id } = ctx.params;
            const body = ctx.request.body;


            await models.Backups.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 deleteBackups(opts) {
    return async function (ctx, next) {

        try {
            const models = ctx.fs.dc.models;
            const { id } = ctx.params;

            await models.Backups.destroy({
                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 restore(opts) {
    return async function (ctx, next) {
        const { backupsUrl } = opts;
        const models = ctx.fs.dc.models;
        try {
            let rslt = ctx.request.body;
            const { id, source, databases: { database, host, password, port, user } } = ctx.request.body
            await models.Backups.update({
                state: '恢复中',
                restoreStart: moment()
            }, { where: { id: id } })
            //调用后端备份接口
            const url = backupsUrl + `/restoreDB?dbHost=${host}&dbPort=${port}&user=${user}&password=${password}&dbName=${database}&backFileName=${source}`;
            request.post(url).then(res => {
                const { code, message } = res.body
                models.Backups.update({
                    state: code == 200 ? '恢复成功' : '恢复失败',
                    log: code == 200 ? '' : message,
                    restoreEnd: moment(),
                    restoreDatabases: ctx.request.body.databases
                }, { where: { id: id } })
                if (code != 200) ctx.fs.logger.error(`path: ${ctx.path}, error: ${message}`);
            })

            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 = {
    getBackupsList,
    addBackups,
    editBackups,
    deleteBackups,
    restore
}