/**
 * 数据模型基类
 *
 * @author CaiAoLin
 * @date 2017/6/22
 * @version
 */
import MongooseHelper from "../helper/mongoose_helper";
let mongoose = require('mongoose');
let counterModel =  mongoose.model('counter');

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) {
                let key="";
                if (indexBy instanceof Array){
                    key = this.getIndex(tmp,indexBy);
                }else {
                    key =tmp[indexBy]?tmp[indexBy]:"";
                }
                tmpResult[key] = 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;
    }

    async setIDfromCounter(name,list,map,keyfield){
      let update = {$inc: {sequence_value: list.length}};
      let condition = {_id: name};
      let options = {new: true};
    
      // 先查找更新
      let counter = await counterModel.findOneAndUpdate(condition, update, options);
      let firstID = counter.sequence_value - (list.length - 1);
      for(let a of list){
          a.id = firstID;
          firstID+=1
          if(map && keyfield){
            let key = a[keyfield];
            map[key]?map[key].push(a):map[key]=[a]
          }
      }
    }

    /**
     * 更新数据
     *
     * @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;
    }
    getIndex(obj,tpops){
        let pops = tpops?tpops:['code','name','specs','unit','type'];
        let t_index = '';
        let k_arr=[];
        for(let p of pops){
            let tmpK = (obj[p]==undefined||obj[p]==null||obj[p]=='')?'null':obj[p];
            k_arr.push(tmpK);
        }
        t_index=k_arr.join("|-|");
        return t_index;
    }

}

export default BaseModel;