'use strict';

async function getPatrolTemplate (ctx, next) {
    try {
        const models = ctx.fs.dc.models;
        const { userId } = ctx.fs.api
        const { limit, page, id, name } = ctx.query;
        let options = {
            where: {},
            order: [['id', 'desc']],
            include: [{
                required: true,
                model: models.User,
                attributes: ['id', 'name'],
            }, {
                model: models.CheckItems,
            }, {
                model: models.PatrolPlan,
                attributes: ['structure_id','name'],
            }]
        };
        if (id) {
            options.where.id = id;
        }
        if (name) {
            options.where.name = { $like: `%${name}%` };
        }
        if (limit) {
            options.limit = Number(limit);
        }
        if (page && limit) {
            options.offset = Number(page) * Number(limit);
        }
        let res = await models.PatrolTemplate.findAndCountAll(options);
        ctx.status = 200;
        ctx.body = res;
    } catch (error) {
        ctx.fs.logger.error(`path: ${ctx.path}, error: ${error}`);
        ctx.status = 400;
        ctx.body = {
            "message": "获取巡检模板失败"
        }
    }
}

async function createPatrolTemplate (ctx, next) {
    const transaction = await ctx.fs.dc.orm.transaction();
    try {
        const models = ctx.fs.dc.models;
        const { userId } = ctx.fs.api
        const data = ctx.request.body;
        const { name, describe, checkItems = [] } = data;

        let Template = {
            name, describe, createUserId: userId
        };

        const templateRes = await models.PatrolTemplate.create(
            Template,
            {
                transaction
            }
        );
        await models.PatrolTemplateCheckItems.bulkCreate(
            checkItems.map(cid => {
                return {
                    templateId: templateRes.id,
                    checkItemsId: cid
                }
            })
            , {
                transaction
            })

        await transaction.commit();
        ctx.status = 204;
    } catch (error) {
        await transaction.rollback();
        ctx.fs.logger.error(`path: ${ctx.path}, error: ${error}`);
        ctx.status = 400;
        ctx.body = {
            "message": '新增巡检模板失败'
        }
    }
}

async function updatePatrolTemplate (ctx, next) {
    const transaction = await ctx.fs.dc.orm.transaction();
    try {
        let errMsg = '修改巡检模板失败';
        const models = ctx.fs.dc.models;
        const data = ctx.request.body;
        const { name, describe, checkItems } = data;

        let Template = { name, describe, checkItems };

        if (data && data.id) {
            await models.PatrolTemplate.update(Template, {
                where: { id: data.id },
                transaction
            })
            await models.PatrolTemplateCheckItems.destroy({
                where: {
                    templateId: data.id
                },
                transaction
            })
            await models.PatrolTemplateCheckItems.bulkCreate(
                checkItems.map(cid => {
                    return {
                        templateId: data.id,
                        checkItemsId: cid
                    }
                })
                , {
                    transaction
                })
        } else {
            errMsg = '请传入巡检模板id';
            throw errMsg;
        }
        await transaction.commit();
        ctx.status = 204;
    } catch (error) {
        await transaction.rollback();
        ctx.fs.logger.error(`path: ${ctx.path}, error: ${error}`);
        ctx.status = 400;
        ctx.body = {
            "message": errMsg
        }
    }
}

async function delPatrolTemplate (ctx, next) {
    const transaction = await ctx.fs.dc.orm.transaction();
    try {
        let errMsg = '删除巡检模板失败';

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

        const record = await models.PatrolPlan.findOne({
            where: { templateId: id }
        });

        if (record) {
            errMsg = '不能删除已绑定巡检计划的模板';
            throw errMsg;
        }

        await models.PatrolTemplateCheckItems.destroy({
            where: { templateId: id },
            transaction
        })

        await models.PatrolTemplate.destroy({
            where: { id },
            transaction
        })
       
        await transaction.commit();
        ctx.status = 204;
    } catch (error) {
        await transaction.rollback();
        ctx.fs.logger.error(`path: ${ctx.path}, error: ${error}`);
        ctx.status = 400;
        ctx.body = { message: error }
    }
}

module.exports = {
    getPatrolTemplate,
    createPatrolTemplate,
    updatePatrolTemplate,
    delPatrolTemplate,
}