/**
 * 数据模型基类
 *
 * @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|String} id
     * @param {boolean} isString 设置是否为_id
     * @return {Promise}
     */
    async deleteById(id, isString = false) {
        let result = false;
        if (!isString) {
            id = parseInt(id);
            if (isNaN(id) || id <= 0) {
                return false;
            }
        }

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

        return result;
    }

    /**
     * 更新数据
     *
     * @param {Number|String} id
     * @param {Object} updateData
     * @return {Promise}
     */
    async updateById(id, updateData) {
        if (Object.keys(updateData).length <= 0) {
            return false;
        }
        let condition = typeof id === 'number' ? {id: id} : {_id: id};
        let result = await this.db.update(condition, updateData);

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

    isDef(value){
        return value !==undefined && value !==null
    }

}

export default BaseModel;