'use strict';

async function findSingleGraph(ctx, next) {
    let error = { name: 'FindSingleError', message: '查询单一数据失败' };
    let rslt = null;
    const { projectId } = ctx.params;
    try {
        rslt = await ctx.fs.dc.models.ProjectGraph.findOne({
            where: { projectId: projectId }
        });
        error = null;
    } catch (err) {
        ctx.fs.logger.error(`path: ${ctx.path}, error: ${err}`);
    }
    if (error) {
        ctx.status = 400;
        ctx.body = error;
    } else {
        ctx.status = 200;
        ctx.body = rslt;
    }
}

async function createGraph(ctx, next) {
    let error = { name: 'AddError', message: '添加数据失败' };
    let graphId = null;
    try {
        const data = ctx.request.body;
        let dataToSave = {
            projectId: data.projectId,
            graph: data.graph,
        }
        const t = await ctx.fs.dc.orm.transaction();
        try {
            let planarGraph = await ctx.fs.dc.models.ProjectGraph.create(dataToSave);
            graphId = planarGraph.id;
            await t.commit();
        } catch (e) {
            await t.rollback();
            throw e;
        }
        error = null;
        // 日志信息
        ctx.fs.api = ctx.fs.api || {};
        ctx.fs.api.actionParameter = JSON.stringify(data);
        ctx.fs.api.actionParameterShow = `新增graphId:${graphId}`;
    } catch (err) {
        ctx.fs.logger.error(`path: ${ctx.path}, error: ${err}`);
    }
    if (error) {
        ctx.status = 400;
        ctx.body = error;
    } else {
        ctx.status = 200;
        ctx.body = { id: graphId };
    }
}

async function updateGraph(ctx, next) {
    let error = { name: 'UpdateError', message: '修改数据失败' };
    const { id } = ctx.params;
    const data = ctx.request.body;
    if (id) {
        if (data && Object.keys(data).length) {
            try {
                const models = ctx.fs.dc.models;
                let planarGraph = await models.ProjectGraph.findOne({ where: { id: id } });
                const dataToSave = {};
                if (planarGraph) {
                    const { projectId, graph } = data;
                    if (projectId && !(projectId == planarGraph.projectId))
                        dataToSave.projectId = projectId;
                    if (graph && !(graph == planarGraph.graph))
                        dataToSave.graph = graph;
                }
                dataToSave.id = planarGraph.id;
                if (Object.keys(dataToSave).length) {
                    await models.ProjectGraph.update(dataToSave, { where: { id: planarGraph.id } });
                }
                error = null;
                // 日志信息
                ctx.fs.api = ctx.fs.api || {};
                ctx.fs.api.actionParameter = JSON.stringify(data);
                ctx.fs.api.actionParameterShow = `结构物平面图id:${data.id}`;
            } catch (err) {
                ctx.fs.logger.error(`path: ${ctx.path}, error: ${err}`);
            }
        }
    } else {
        error = { name: 'UpdateError', message: `不存在{id=${id}}的结构物平面图` };
    }
    if (error) {
        ctx.status = 400;
        ctx.body = error;
    } else {
        ctx.status = 200;
        ctx.body = { message: "结构物平面图修改成功" };
    }
}

async function delProjectGraph(ctx) {
    try {
        const { id } = ctx.params;
        const models = ctx.fs.dc.models;
        let info = await models.ProjectGraph.findOne({ where: { id: id } });
        if (info) {
            await models.ProjectPointsDeploy.destroy({ where: { graphId: id } });
            await models.ProjectGraph.destroy({ where: { id } })
            ctx.status = 204;
        } else {
            ctx.status = 400;
            ctx.body = { message: '数据不存在' }
        }
    } catch (error) {
        ctx.fs.logger.error(`path: ${ctx.path}, error: ${error}`);
        ctx.status = 400;
        ctx.body = {
            "message": "删除结构物布设图失败"
        }
    }
}

async function getProjectPoints(ctx) {
    let rslt = null
    try {
        const projectId = ctx.params.projectId;
        const models = ctx.fs.dc.models;
        rslt = await models.Point.findAll({
            attributes: ['id', 'name', 'equipmentNo', 'equipmentModel'],
            where: { projectId: projectId }
        })
        ctx.status = 200;
        ctx.body = rslt;
    } catch (err) {
        ctx.fs.logger.error(`path: ${ctx.path}, error: ${err}`);
        ctx.status = 400;
        ctx.body = {
            name: 'FindError',
            message: '获取结构物点位列表失败'
        }
    }
}

async function getDeployPoints(ctx) {
    let rslt = null;
    try {
        const pictureId = ctx.params.pictureId;
        const models = ctx.fs.dc.models;
        const heatmap = await models.ProjectGraph.findOne({ where: { id: pictureId } })
        if (heatmap) {
            rslt = await models.ProjectPointsDeploy.findAll({
                where: { graphId: pictureId }
            })
            ctx.status = 200;
            ctx.body = rslt;
        } else {
            throw new Error('pictureId not found');
        }
    } catch (err) {
        ctx.fs.logger.error(`path: ${ctx.path}, error: ${err}`);
        ctx.status = 400;
        ctx.body = {
            name: 'FindError',
            message: '获取结构物平面图测点布设失败'
        }
    }
}

async function setDeployPoints(ctx) {
    const pictureId = ctx.params.pictureId;
    const req = ctx.request.body;
    const models = ctx.fs.dc.models;
    const orm = ctx.fs.dc.orm;

    try {
        ctx.fs.api = ctx.fs.api || {};
        ctx.fs.api.actionParameter = req;
        ctx.fs.api.actionParameterShow = '结构物平面图测点部署: ' + JSON.stringify(req);

        const t = await orm.transaction();

        try {
            await models.ProjectPointsDeploy.destroy({ where: { graphId: pictureId }, transaction: t });

            const layout = req.spots.map((hotspot, index) => {
                let msg = {
                    graphId: pictureId,
                    pointId: hotspot.pointId,
                    position: JSON.stringify(hotspot.position)
                }
                return msg;
            });

            await models.ProjectPointsDeploy.bulkCreate(layout, { transaction: t });

            await t.commit();
        } catch (e) {
            await t.rollback();
            throw e;
        }
        ctx.status = 200;
        ctx.body = {
            name: "CreateSuccess",
            message: "结构物平面图测点部署成功"
        };

    } catch (err) {
        ctx.fs.logger.error(err);
        ctx.status = 400;
        ctx.body = {
            name: 'CreateError',
            message: "结构物平面图测点部署失败"
        }
    }
}

module.exports = {
    findSingleGraph,
    createGraph,
    updateGraph,
    delProjectGraph,
    getProjectPoints,
    getDeployPoints,
    setDeployPoints
};