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

class PermissionGroupModel extends BaseModel {

    /**
     * 构造函数
     *
     * @return {void}
     */
    constructor() {
        let parent = super();
        parent.model = mongoose.model('permission_group');
        parent.init();
    }

    /**
     * 新增权限
     *
     * @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 = 30) {
        page = parseInt(page);
        page = page <= 1 ? 1 : page;
        let option = {pageSize: pageSize, offset: parseInt((page - 1) * pageSize)};
        console.log(condition);
        let list = await this.db.find(condition, null, option);
        list = list.length > 0 ? list : [];

        return list;
    }

    /**
     * 根据条件返回数据数量
     *
     * @param {object} condition
     * @return {Promise}
     */
    async count(condition = null) {
        let total = 0;
        try {
            total = await this.db.count(condition);
        } catch (error) {
            total = 0;
        }
        return total;
    }

    /**
     * 新增权限组
     *
     * @param {Object} data
     * @return {Promise}
     */
    async createPermissionGroup(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} data
     * @return {Promise}
     */
    async savePermissionGroup(data) {
        if (Object.keys(data).length <= 0) {
            throw '数据格式错误';
        }
        let permission = {
            top: data.topPermission !== undefined ? data.topPermission : [],
        };
        for (let index in data) {
            if (index.indexOf('permission_') > -1) {
                let key = index.split('_')[1];
                permission[key] = data[index];
            }
        }
        let postData = {
            name: data.name,
            permission: JSON.stringify(permission),
        };
        let result = await this.updateById(data.id, postData);

        return result;
    }

}

export default PermissionGroupModel;
