import { Controller, Context } from 'egg';
import { trim, omitBy } from 'lodash';
import { v1 as uuidv1 } from 'uuid';
import * as path from 'path';
export default class EditorController extends Controller {

  public async login(ctx: Context) {
    await ctx.renderClient('login.js', {});
  }

  public async home(ctx: Context) {
    let apollo = {};
    if (process.env.NODE_ENV === 'production' && process.env.EGG_SERVER_ENV === 'sit') {
      apollo = ctx.app.config.apollo || {};
    }

    await ctx.renderClient('editor.js', { apollo });
  }

  public async save(ctx: Context) {
    const pageInfo = ctx.request.body;
    const result = await ctx.model.PageInfo.create({ ...pageInfo, uuid: uuidv1().replace(/-/g, '')});
    await ctx.service.redis.set(`pageInfo:${result.dataValues.uuid}`, result.dataValues);
    ctx.body = ctx.helper.ok(result);
  }

  public async update(ctx: Context) {
    const pageInfo = ctx.request.body;
    if (!pageInfo.uuid) {
      pageInfo.uuid = uuidv1().replace(/-/g, '');
    }
    const result = await ctx.model.PageInfo.update(pageInfo, {where: { uuid: pageInfo.uuid }});
    await ctx.service.redis.set(`pageInfo:${pageInfo.uuid}`, pageInfo);
    await ctx.service.redis.del(`page:${pageInfo.uuid}`);
    ctx.body = ctx.helper.ok(result);
  }

  public async get(ctx: Context) {
    let pageInfo = await ctx.service.redis.get(`pageInfo:${ctx.params.uuid}`);
    if (!pageInfo) {
      pageInfo = await ctx.model.PageInfo.findOne({where: { uuid: ctx.params.uuid }});
      await ctx.service.redis.set(`pageInfo:${ctx.params.uuid}`, pageInfo);
    }
    ctx.body = ctx.helper.ok(pageInfo);
  }

  public async getList(ctx: Context) {
    const { type, pageSize, pageNo, author, pageName, isPublish, pageDescribe } = ctx.query;
    const { like } = ctx.model.Sequelize.Op;
    let where = omitBy({
      author: author && { like: `%${author}%`},
      pageName: pageName && { like: `%${pageName}%`},
      pageDescribe: pageDescribe && { like: `%${pageDescribe}%`},
      isPublish,
      enable: 1
    }, v => !v);
    if (type === 'list') {
      where = { ...where, isPublish: 1 };
    } else if (type === 'my') {
      where = { ...where };
    } else if (type === 'template') {
      where = { ...where, isTemplate: 1 };
    }
    const { count: total, rows: data } = await ctx.model.PageInfo.findAndCountAll({ where, limit: +pageSize || 10,
      offset: (+pageNo - 1) * +pageSize || 0,  order: [['updated_at', 'DESC']] });
    ctx.body = ctx.helper.ok({ total, data });
  }

  public async getTemplateList(ctx: Context) {
    const list = await ctx.model.PageInfo.findAll({ where: { isTemplate: 1 } });
    ctx.body = ctx.helper.ok(list);
  }

  public async clearCache(ctx: Context) {
    const where = {
      updated_at: {
        [ctx.model.Sequelize.Op.lt]: Date.now(),
        [ctx.model.Sequelize.Op.gt]: new Date(Date.now() - 1000 * 60 * 60 * 24 * 7)
      },
      enable: 1,
      isPublish: 1
    };
    const pageInfo = await ctx.model.PageInfo.findAll({
      attributes: ['uuid'],
      where
    });
    pageInfo.forEach(async item => {
      await ctx.service.redis.del(`page:${item.uuid}`);
    });
    ctx.body = ctx.helper.ok();
  }

  public async delete(ctx: Context) {
    const pageInfo = await ctx.model.PageInfo.update({ enable: 0 }, {where: { id: +ctx.params.pageId }});
    ctx.body = ctx.helper.ok(pageInfo);
  }
}