const Base = require('../../base');

module.exports = class extends Base {
  async indexAction() {
    this.assign('currentPage', 'sys-log');
    this.assign('pageTitle', '操作日志');
    this.assign('breadcrumb', [
      { name: '系统管理', url: '/admin/system/user.html' },
      { name: '操作日志' }
    ]);
    return this.display();
  }

  async listAction() {
    const keyword = this.get('keyword') || '';
    const action = this.get('action') || '';
    const startDate = this.get('startDate') || '';
    const endDate = this.get('endDate') || '';
    const page = this.get('page') || 1;
    const pageSize = this.get('pageSize') || 20;

    const model = this.model('operation_log');
    const where = {};

    if (keyword) {
      where._complex = {
        username: ['like', `%${keyword}%`],
        description: ['like', `%${keyword}%`],
        _logic: 'or'
      };
    }
    if (action) {
      where.action = action;
    }
    if (startDate) {
      where.create_time = where.create_time || {};
      where.create_time = ['>=', startDate + ' 00:00:00'];
    }
    if (startDate && endDate) {
      where.create_time = ['between', [startDate + ' 00:00:00', endDate + ' 23:59:59']];
    } else if (endDate) {
      where.create_time = ['<=', endDate + ' 23:59:59'];
    }

    const list = await model.where(where)
      .order('id DESC')
      .page(page, pageSize)
      .countSelect();

    return this.json({ code: 0, data: list });
  }

  async clearAction() {
    const days = this.post('days') || 30;
    const date = new Date();
    date.setDate(date.getDate() - days);
    const dateStr = date.toISOString().slice(0, 10);
    await this.model('operation_log').where({ create_time: ['<', dateStr + ' 00:00:00'] }).delete();
    await this.log('delete', '操作日志', `清理${days}天前的日志`);
    return this.json({ code: 0, msg: `已清理${days}天前的日志` });
  }
};
