'use strict';
const request = require('superagent');
const fs = require('fs');
const path = require('path')
const moment = require('moment');

async function reportList(ctx, next) {
    try {
        const models = ctx.fs.dc.models
        const { limit, page, name } = ctx.query
        let options = {
            where: {
   
            },
         }
         if (limit) {
            options.limit = Number(limit)
         }
         if (page && limit) {
            options.offset = Number(page) * Number(limit)
         }
         if (name) {
            options.where.name = { $like: `%${name}%` }
         }
       const  res = await models.ReportConfiguration.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 postReport (ctx) {
    try {
       const { models } = ctx.fs.dc;
       const data = ctx.request.body
 
       if (data.id) {
          await models.ReportConfiguration.update(data, {
             where: {
                id: data.id
             }
          })
       } else {
          await models.ReportConfiguration.create(data)
       }
       ctx.status = 204;
    } catch (error) {
       ctx.fs.logger.error(`path: ${ctx.path}, error: ${error}`);
       ctx.status = 400;
       ctx.body = {
          message: typeof error == 'string' ? error : undefined
       }
    }
 }

 async function delReport (ctx) {
    try {
       const { models } = ctx.fs.dc;
       const { id } = ctx.params
       await models.ReportConfiguration.destroy({
          where: {
             id: id
          }
       })
 
       ctx.status = 204;
    } catch (error) {
       ctx.fs.logger.error(`path: ${ctx.path}, error: ${error}`);
       ctx.status = 400;
       ctx.body = {
          message: typeof error == 'string' ? error : undefined
       }
    }
 }


 async function postGenerateReport (ctx) {
   try {
      const { models } = ctx.fs.dc;
      const data = ctx.request.body

      let res = await ctx.app.fs.reportGenerate.post('creatReport', {
         data: data
      })
      if (res.includes('xjGLReport')) {
         await models.ReportInfo.create({
            excelPath: res,
            reportTm: moment().format('YYYY-MM-DD HH:mm:ss'),
            structure:data.structIds,
            inspectTm:moment().format('YYYY-MM-DD HH:mm:ss')
         })
         ctx.status = 200;
         ctx.body = res
      } else {
         throw '生成报表失败'
      }

   } catch (error) {
      ctx.fs.logger.error(`path: ${ctx.path}, error: ${error}`);
      ctx.status = 400;
      ctx.body = {
         message: typeof error == 'string' ? error : undefined
      }
   }
}
 


 module.exports = {
    reportList,
    postReport,
    delReport,
    postGenerateReport
 }