'use strict';
/**
 *  URL 的 模板
 *  具体关系是 URL跟它是1对多。
 */

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
// model名称，即表名
exports.model = 'TemplateUrlRoute';

// 表结构
exports.schema = [{
  key: { type: String, required: true },
  is_default: { type: Number },
  fun: { type: String, required: true },
  url: { type: Schema.Types.ObjectId, ref: "Url" },
  devices: [{ type: Schema.Types.ObjectId, ref: "DeviceProjectRoute" }]
}, {
  // autoIndex: true,
  versionKey: false
}];

// 静态方法:http://mongoosejs.com/docs/guide.html#statics
exports.statics = {}
var reg = /^[\u4E00-\u9FA5]+$/;
// http://mongoosejs.com/docs/guide.html#methods
exports.methods = {
  saveByKey: async function () {
    this.key = this.key.replace(/^\s+|\s+$/g, '');
    let aa = await this.model("TemplateUrlRoute").find({
      key: this.key,
      url: this.url
    });
    if(this.url == undefined){
      return { code : "0001"}
    }
    if (aa.length != 0) {
      return false
    }
    if (reg.test(this.key)) return false;
    let template = await this.save();
    let url = await this.model("Url").find({ _id: this.url })
    if(url.length!=0){
      url[0].templates.push(template);
      await url[0].save();  
    }
    // 更新Url ,告知URL版本迭代，需要重新发布
    let flg = new Date().getTime();
    let urlques = {};
    urlques.last_version = flg;
    urlques.relace_flg = 0;
    await this.model("Url").update({_id:this.url},urlques);


    return template
  },
  updateById: async function(ques){
    // 更新Url ,告知URL版本迭代，需要重新发布
    let item = await this.model("TemplateUrlRoute").update({_id:ques._id},ques);
    let flg = new Date().getTime();
    let urlques = {};
    urlques.last_version = flg;
    urlques.relace_flg = 0;
    await this.model("Url").update({_id:this.url},urlques);
    
    return item
  },
  delete: async function(_id){
    let item = await this.model("TemplateUrlRoute").remove({ "_id": _id });

    let flg = new Date().getTime();
    let urlques = {};
    urlques.last_version = flg;
    urlques.relace_flg = 0;
    await this.model("Url").update({_id:this.url},urlques);

    return item
  }
}
