'use strict';
const moment = require('moment')

async function list (ctx) {
   try {
      const models = ctx.fs.dc.models;
      const { keyword, alarmType, state, } = ctx.request.body

      let findOption = {
         where: {

         }
      }

      if (keyword) {
         findOption.where.$or = [
            {
               name: { $like: `%${keyword}%` }
            },
         ]
      }
      if (alarmType) {
         findOption.where.alarmType = { $contains: [alarmType] }
      }
      if (state) {
         if (state == 'enable') {
            findOption.where.disable = false
         } else if (state == 'disable') {
            findOption.where.disable = true
         } else if (state == 'overtime') {

         }
      }

      const listRes = await models.AlarmPushConfig.findAndCountAll(findOption)

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

async function edit (ctx) {
   try {
      const models = ctx.fs.dc.models;
      const { userId, pepUserId } = ctx.fs.api
      const { pushId, name, pepProjectId = [], alarmType = [], receiverPepUserId = [], timeType = [], disable } = ctx.request.body

      let storageData = {
         name, pepProjectId, alarmType, receiverPepUserId, timeType, disable
      }
      if (pushId) {
         await models.AlarmPushConfig.update(storageData, {
            where: {
               id: pushId
            }
         })
      } else {
         storageData.createTime = moment().format()
         storageData.createUserId = userId
         await models.AlarmPushConfig.create(storageData)
      }

      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 state (ctx) {
   try {
      const models = ctx.fs.dc.models;
      const { pushId } = ctx.params
      const { disable = undefined, del = undefined, } = ctx.request.body

      if (del) {
         await models.AlarmPushConfig.destroy({
            where: {
               id: pushId
            }
         })
      } else {
         await models.AlarmPushConfig.update({
            disable,
         }, {
            where: {
               id: pushId
            }
         })
      }

      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
      }
   }
}



module.exports = {
   list, edit, state
};