'use strict';

const moment = require('moment');

module.exports = app => {
  const { STRING, INTEGER, DATE, ENUM } = app.Sequelize;
  const Icon = app.blockModel.define('icon', {
    id: { type: STRING, primaryKey: true },
    block_id: STRING,
    title: STRING,
    subtitle: STRING,
    description: STRING,
    link: STRING,
    logo: STRING,
    sort: INTEGER,
    status: ENUM('online', 'offline'),
    tags: STRING,
    start_time: DATE,
    expire_time: DATE,
    valid: INTEGER,
    field1: STRING,
    field2: STRING,
    field3: STRING,
    extends: STRING,
  }, {
    timestamps: false,
    tableName: 'icon',
  });

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


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

  Icon.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 Icon.findAndCountAll(condition);
    return { page, count, rows };
  };

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

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


  return Icon;

};
