'use strict';

const moment = require('moment');

module.exports = app => {
  const { STRING, INTEGER, DATE, ENUM } = app.Sequelize;
  const Block = app.blockModel.define('block', {
    id: { type: STRING, primaryKey: true },
    app_id: INTEGER,
    channel_id: STRING,
    city_id: STRING,
    position_id: STRING,
    title: STRING,
    subtitle: STRING,
    description: STRING,
    status: ENUM('online', 'offline'),
    tags: STRING,
    valid: INTEGER,
    start_time: DATE,
    expire_time: DATE,
  }, {
    timestamps: false,
    tableName: 'block',
  });

  Block.one = async data => {
    const attributes = data.attributes ? data.attributes : {};
    const where = data.where ? data.where : {};
    return await Block.findOne({
      attributes,
      where,
    });
  };


  Block.all = async data => {
    const attributes = data.attributes ? data.attributes : {};
    const where = data.where ? data.where : {};
    return await Block.findAll({
      attributes,
      where,
    });
  };

  Block.list = async (data = {}) => {
    const limit = data.limit ? data.limit : 10;
    const page = data.page ? data.page : 1;
    const order = data.order ? data.order : [];
    const attributes = data.attributes ? data.attributes : {};
    const where = data.where ? data.where : {};
    const condition = {
      offset: (page - 1) * limit,
      limit,
      where,
      order,
      attributes,
    };
    const { count, rows } = await Block.findAndCountAll(condition);
    return { page, count, rows };
  };

  Block.add = async data => {
    try {
      // 返回promise对象实力 instance
      const res = await Block.create(data);
      // 从promise 实例中中获得需要的id号，id 必须是自增长，而且必须主键，否则返回null
      return res.id;
    } catch (error) {
      ctx.status = 500;
      throw (error);
    }
  };

  Block.edit = async data => {
    const where = data.where;
    const params = data.params;
    Block.update(params, {
      where,
    }).catch(e => res.json({ status: 500, error: e }));
  };

  return Block;

};
