'use strict';

async function getGroup(ctx, next) {
    let error = { name: 'FindError', message: '获取检查项分组失败' };
    let rslt = [];
    try {
        const models = ctx.fs.dc.models;
        let list = await models.CheckItemsGroup.findAll({
            include: [{
                model: models.CheckItems,
            }]
        });

        rslt = list;
        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 createGroup(ctx, next) {
    const models = ctx.fs.dc.models;
    try {
        const data = ctx.request.body;
        const rslt = await models.CheckItemsGroup.create(data);
        ctx.status = 200;
        ctx.body = { message: '新建分组成功', groupId: rslt.dataValues.id }
    } catch (error) {
        ctx.fs.logger.error(`path: ${ctx.path}, error: ${error}`);
        ctx.status = 400;
        ctx.body = { message: '新建分组失败' }
    }
}

async function delGroup(ctx, next) {
    const models = ctx.fs.dc.models;
    try {
        const { id } = ctx.params;
        await models.CheckItemsGroup.destroy({
            where: { id }
        });
        ctx.status = 200;
        ctx.body = { message: '删除分组成功' }
    } catch (error) {
        ctx.fs.logger.error(`path: ${ctx.path}, error: ${error}`);
        ctx.status = 400;
        ctx.body = { message: error.name === 'SequelizeForeignKeyConstraintError' ? '不能删除有检查项的分组' : '删除分组失败' }
    }
}

async function getCheckItems(ctx, next) {
    try {
        const models = ctx.fs.dc.models;
        const { limit, page, name } = ctx.query;
        let options = {
            where: {},
            order: [['id', 'asc']],
            include: [{
                required: true,
                model: models.CheckItemsGroup,
                attributes: ['id', 'name'],
            }, {
                model: models.PatrolTemplate
            }],
            distinct: true,
        }
        if (name) {
            options.where.name = { $like: `%${name}%` };
        }
        if (limit) {
            options.limit = Number(limit);
        }
        if (page && limit) {
            options.offset = Number(page) * Number(limit);
        }
        const userRes = await models.CheckItems.findAndCountAll(options)

        ctx.status = 200;
        ctx.body = userRes
    } catch (error) {
        ctx.fs.logger.error(`path: ${ctx.path}, error: ${error}`);
        ctx.status = 400;
        ctx.body = {
            "message": "获取检查项失败"
        }
    }
}

async function createCheckItems(ctx, next) {
    let errMsg = "新增检查项失败"
    try {
        const models = ctx.fs.dc.models;
        const data = ctx.request.body;

        await models.CheckItems.create(data);

        ctx.status = 204;
    } catch (error) {
        ctx.fs.logger.error(`path: ${ctx.path}, error: ${error}`);
        ctx.status = 400;
        ctx.body = {
            "message": errMsg
        }
    }
}


async function updateCheckItems(ctx, next) {
    let errMsg = "修改检查项失败"
    try {
        const models = ctx.fs.dc.models;
        const data = ctx.request.body;
        const { id } = ctx.params;

        await models.CheckItems.update(data, {
            where: {
                id: id
            }
        });

        ctx.status = 204;
    } catch (error) {
        ctx.fs.logger.error(`path: ${ctx.path}, error: ${error}`);
        ctx.status = 400;
        ctx.body = {
            "message": errMsg
        }
    }
}

async function deleteCheckItems(ctx, next) {
    try {
        const models = ctx.fs.dc.models;
        const { ids } = ctx.params;
        const userIds = ids.split(',');
        await models.CheckItems.destroy({
            where: {
                id: { $in: userIds },
            }
        });
        ctx.status = 204;
    } catch (error) {
        ctx.fs.logger.error(`path: ${ctx.path}, error: ${error}`);
        ctx.status = 400;
        ctx.body = {
            "message": "删除检查项失败"
        }
    }
}

module.exports = {
    getGroup,
    createGroup,
    delGroup,
    getCheckItems,
    createCheckItems,
    updateCheckItems,
    deleteCheckItems,
}