/**
 * 孵化器验证码 表 
 * 用于管理 孵化器 所用的验证码
 * 
 */

import {Schema} from 'mongoose';
import { baseDB } from '../../db/mongo/dbInit';

const codeSchema = new Schema({
    id:{type:String},
    code:String,
    sendMs:Number,//下发时间时间戳
    uscc:{type:String, index:true},//统一信用代码
    type:Number,//验证码类型 遵循 CODETYPE 
    isUse:{type:Boolean, default:false},//是否使用  默认false
});

var codeModel;
export function initModel(){
    codeModel = baseDB.model('fuhuaqicode', codeSchema);
    codeModel.selectOnceData = async function (paramater:object) {
        let selectInfo = await codeModel.findOne(paramater).exec();
        if (selectInfo) {
            if (!selectInfo.runSave) {
                selectInfo.runSave = selectInfo.save;
                selectInfo.save = save.bind(selectInfo)
            }
        }
        return selectInfo;
    }
}
export async function save(throwError=false) {
    if (!this.isModified()) return;
    await this.runSave({validateBeforeSave:false}).catch(err=>{
        console.log(err);
    });
}


/**
 * 获取今日目标孵化器下发的code
 * @param uscc 
 * @returns []
 */
export async function findTodayCodeByUscc(uscc:string, todayMs:number) {
    let findParam = {uscc, sendMs:{"$gt":todayMs} }
    let res = await codeModel.find(findParam);
    return res || [];
}


/**
 * 修改状态
 * @param uscc 
 * @returns []
 */
export async function updateCodeState(codeId:string) {
    await codeModel.update({codeId}, {$set:{isUse:true}});
}



/**
 * 创建code
 * @param uscc 孵化器统一信用代码
 * @param id code的id
 * @param code code码
 * @param type 类型
 * @returns 
 */
export async function createCode(uscc:string, id:string, code:string, type:number, sendMs:number) {
    let addInfo = {
        id, 
        code,
        sendMs,
        uscc,
        type,
        isUse:false
    };
    return await codeModel.create(addInfo);
}