'use strict';

const moment = require("moment/moment");

async function get(ctx) {
    try {
        const { limit, page } = ctx.query;
        const models = ctx.fs.dc.models;
        let res = await models.DeptTraining.findAndCountAll({
            where: {},
            offset: Number(page) * Number(limit),
            limit: Number(limit),
            order: [['id', 'ASC']]
        })
        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 importData(ctx) {
    let errorMsg = { message: '导入部门培训记录信息失败' };
    const transaction = await ctx.fs.dc.orm.transaction();
    try {
        const models = ctx.fs.dc.models;
        const data = ctx.request.body;
        await models.DeptTraining.bulkCreate(data, { 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 = errorMsg;
    }
}

async function modify(ctx) {
    try {
        const { models } = ctx.fs.dc;
        const { id, ...rest } = ctx.request.body;
        const existRes = await models.DeptTraining.findOne({ where: { id } });
        if (!existRes) {
            throw '当前部门培训记录信息不存在';
        }
        await models.DeptTraining.update({ updateDate: moment(), ...rest }, { where: { id: id } });
        ctx.status = 204;
    } catch (error) {
        ctx.fs.logger.error(`path: ${ctx.path}, error: ${error}`);
        ctx.status = 400;
        ctx.body = {
            message: '修改部门培训记录失败'
        }
    }
}
module.exports = {
    get,
    importData,
    modify
}