/**
 * 数据模型基类
 *
 * @author CaiAoLin
 * @date 2017/6/22
 * @version
 */
import MongooseHelper from "../helper/mongoose_helper";

class BaseModel {

    /**
     * mongoose数据模型
     *
     * @var {object}
     */
    model = null;

    /**
     * 构造函数
     *
     * @return {void}
     */
    constructor() {
        if (new.target === BaseModel) {
            throw new Error('BaseModel不能实例化,只能继承使用。');
        }
    }

    /**
     * 初始化函数
     *
     * @return {void}
     */
    init() {
        if (this.model === null) {
            throw new Error('子类数据有误');
        }

        this.db = new MongooseHelper();
        this.db.model = this.model;
    }

    /**
     * 根据id查找对应数据
     *
     * @param {Object} condition
     * @param {Object} fields
     * @param {boolean} singleData
     * @param {String} indexBy
     * @return {Promise}
     */
    async findDataByCondition(condition, fields = null, singleData = true, indexBy = null) {
        let result = [];
        if (Object.keys(condition).length <= 0) {
            return result;
        }

        result = singleData ? await this.db.findOne(condition, fields) : await this.db.find(condition, fields);

        if (indexBy !== null && !singleData && result.length > 0) {
            let tmpResult = {};
            for(let tmp of result) {
                tmpResult[tmp[indexBy]] = tmp;
            }
            result = tmpResult;
        }
        return result;
    }

    /**
     * 根据条件返回数据数量
     *
     * @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;
    }

    /**
     * 根据id删除
     *
     * @param {Number} id
     * @return {Promise}
     */
    async deleteById(id) {
        let result = false;
        id = parseInt(id);
        if (isNaN(id) || id <= 0) {
            return false;
        }

        try {
            let deleteResult = await this.db.delete({id: id});
            result = deleteResult.result.ok === 1;
        } catch (error) {
            console.log(error);
            result = false;
        }

        return result;
    }

    /**
     * 更新数据
     *
     * @param {Number} id
     * @param {Object} updateData
     * @return {Promise}
     */
    async updateById(id, updateData) {
        id = parseInt(id);
        if (isNaN(id) || id <= 0 || Object.keys(updateData).length <= 0) {
            return false;
        }

        let result = await this.db.update({id: id}, updateData);

        return result.ok !== undefined && result.ok === 1;
    }

}

export default BaseModel;