/**
 * 后台权限数据模型
 *
 * @author EllisRan
 * @date 2018/12/06
 * @version
 */
import mongoose from "mongoose";
import BaseModel from "../../common/base/base_model";

class PermissionModel extends BaseModel {

    /**
     * 构造函数
     *
     * @return {void}
     */
    constructor() {
        let parent = super();
        parent.model = mongoose.model('permission');
        parent.init();
    }
    /**
     * 设置场景
     *
     * @param {string} scene
     * @return {void}
     */
    setScene(scene = '') {
        switch (scene) {
            // 新增权限
            case 'insert':
                // this.model.schema.path('ID').required(true);
                this.model.schema.path('name').required(true);
                this.model.schema.path('controller').required(true);
                this.model.schema.path('url').required(true);
                this.model.schema.path('pid').required(true);
                break;
        }
    }

    /**
     * 新增权限
     *
     * @param {Object} data
     * @return {Promise}
     */
    async createPermission(data) {
        if (Object.keys(data).length <= 0) {
            throw '数据格式错误';
        }
        data.create_time = new Date().getTime();
        let result = await this.db.create(data);

        return result;
    }

    /**
     * 获取列表
     *
     * @param {object} condition
     * @param {number} page
     * @return {Promise}
     */
    async getList(condition = null, page = 1, pageSize = 100) {
        page = parseInt(page);
        page = page <= 1 ? 1 : page;
        let option = {pageSize: pageSize, offset: parseInt((page - 1) * pageSize), sort: {ID:1}};
        let list = await this.db.find(condition, null, option);
        list = list.length > 0 ? list : [];

        return list;
    }

}

export default PermissionModel;
