'use strict'
const moment = require('moment')
const { QueryTypes } = require('sequelize');
const Hex = require('crypto-js/enc-hex');
const MD5 = require('crypto-js/md5');




async function getProjectType (ctx, next) {
   try {
      const models = ctx.fs.dc.models
      const sequelize = ctx.fs.dc.orm;
      const { } = ctx.query

      const res = await sequelize.query(`select distinct type from project`, { type: QueryTypes.SELECT });
      ctx.body = res
      ctx.status = 200
   } catch (error) {
      ctx.fs.logger.error(`path: ${ctx.path}, error: ${error}`)
      ctx.status = 400
      ctx.body = {
         message: '获取项目类型失败',
      }
   }
}

async function getProjectPublishList (ctx, next) {
   try {
      const models = ctx.fs.dc.models
      const { limit, page } = ctx.query
      let options = {
         where: {},
      }
      if (limit) {
         options.limit = Number(limit)
      }
      if (page && limit) {
         options.offset = Number(page) * Number(limit)
      }

      const res = await models.ProjectUser.findAndCountAll(options)
      ctx.body = res
      ctx.status = 200
   } catch (error) {
      ctx.fs.logger.error(`path: ${ctx.path}, error: ${error}`)
      ctx.status = 400
      ctx.body = {
         message: '获取项目发布列表失败',
      }
   }
}

async function postProjectPublish (ctx, next) {
   let message = '新增项目失败'
   try {
      const models = ctx.fs.dc.models
      const data = ctx.request.body
      const { id, password } = data

      if (id) {
         message = '修改项目失败'
         await models.ProjectUser.update(data, { where: { id } })
      } else {
         let passwords = Hex.stringify(MD5(password));
         await models.ProjectUser.create({ ...data, password: passwords, del: false })
      }
      ctx.status = 204
   } catch (error) {
      ctx.fs.logger.error(`path: ${ctx.path}, error: ${error}`)
      ctx.status = 400
      ctx.body = {
         message: message
      }
   }
}

async function delProjectPublish (ctx, next) {
   try {
      const models = ctx.fs.dc.models
      const { id } = ctx.params

      await models.ProjectUser.destroy({ where: { id } })
      
      ctx.status = 204
   } catch (error) {
      ctx.fs.logger.error(`path: ${ctx.path}, error: ${error}`)
      ctx.status = 400
      ctx.body = {
         message: '删除项目失败'
      }
   }
}

module.exports = {
   getProjectType,
   getProjectPublishList,
   postProjectPublish,
   delProjectPublish
}