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

// 表结构
exports.schema = [{
  name: { type: String, unique: true, required: true },
  path: { type: String, required: true },
  fun: { type: String, required: true },
  last_version: { type: String, required: true },
  relace_version: { type: String, required: true },
  relace_flg: { type: Number, required: true },
  projects: { type: Schema.Types.ObjectId, ref: "Project" },
  templates: [{ type: Schema.Types.ObjectId, ref: "TemplateUrlRoute" }]
}, {
  // autoIndex: true,
  versionKey: false
}];

// 静态方法:http://mongoosejs.com/docs/guide.html#statics
exports.statics = {}

// http://mongoosejs.com/docs/guide.html#methods
exports.methods = {
  saveByKey: async function () {
    //如果项目中没有url的时候，回有循环调用的情况出现
    console.log("----------------1")
    let project_id = this.projects;
    if (project_id == undefined) {
      let temp = await this.model("Project").find({ is_default: 1 })
      this.projects = temp[0]
    }else{
      let aaa = await this.model("Project").find({_id: project_id});
      this.projects = aaa[0];
    }
    console.log("----------------2")
    let aa = await this.model("Url").find({
      path: this.path,
      projects: this.projects
    });
    if (aa.length != 0) {
      return false
    }
    console.log("----------------3")
    let flg = new Date().getTime();
    this.last_version = flg;
    this.relace_version = flg;
    this.relace_flg = 0;
    let url = await this.save();
    this.projects.urls.push(url);
    console.log("----------------4")
    await this.projects.save();
    console.log("----------------5")
    return url
  },
  delete: async function(_id){
    let items = await this.model("Url").find({"_id":_id})
    let item = items[0];
    console.log(item.projects)
    await this.model("Project").update( {_id:item.projects}, { $pullAll: { urls: [item] } } )

    await this.model("TemplateUrlRoute").remove({url:_id});
    // item.projects.slice("urls",[1])
    return await this.model("Url").remove({ "_id": _id });
  },
  findProByProjectId: async function(pro){
    let items =  await this.model("Url").find({ projects: pro });
    let res = [];
    items.forEach(function(element) {
      res.push({
        _id: element._id,
        name: element.name,
        path: element.path,
        relace_flg: element.relace_flg
      })
    }, this);
    return res;
  },
  findUrlRelaceFlgById: async function(_id){
    let item = this.model("Url").findOne({_id:_id});
    return {
      _id: item._id,
      relace_flg: item.flg,
      relace_version: item.relace_version,
      last_version: item.last_version
    }
  },
  findByProjectId: async function (pro) {
    return await this.model("Url").find({ projects: pro })
  },
  findItemBytId: async function (_id) {
    return await this.model("Url").findOne({_id:_id})
  },
  findByObj: async function(obj){
    console.log(obj)
    return await this.model("Url").find(obj);
  },
  release: async function(_id){
    let flg = new Date().getTime();
    let ques = {};
    ques.last_version = flg;
    ques.relace_version = flg;
    ques.relace_flg = 1;
    await this.model("Url").update({_id:_id},ques);
    // let temp = await this.model("Url").find({_id: _id});
    return true
  },
  updateById: async function(ques){
    let flg = new Date().getTime();
    ques.last_version = flg;
    ques.relace_flg = 0;
    console.log(ques);
    console.log("---------------");
    await this.model("Url").update({_id:ques._id},ques);
    console.log("----------0-----")
    let temp = await this.model("Url").find({_id:ques._id});
    return temp[0]
  },
  findUrlTemplatesByUrlId: async function(_id){
    return await this.model("Url").find({_id:_id}).populate("templates").exec();
  },
  findUrlTemplatesById: async function(obj){
    let url = await this.model("Url").find(obj)
    let _this = this;
    let re_url = {
      name: url[0].name,
      path: url[0].path,
      fun: url[0].fun,
      projects: url[0].projects,
      templates: []
    }
    let null_temp = [];
    for(var i = 0 ;i < url[0].templates.length;i++){
      let temp = await _this.model("TemplateUrlRoute").find({_id:url[0].templates[i]})
      if(temp.length == 0){
        null_temp.push(url[0].templates[i])
      }else{
        re_url.templates.push(temp[0])
      }
    }
    if(null_temp.length != 0){
      await this.model("Url").update( obj, { $pullAll: { templates: null_temp } } )
    }
    return re_url
  },
  list: async function () {
    return this.model('Url').find();
  }
}

// db.templateurlroutes.update({},{$set:{last_version:"",relace_version:"",relace_flg:1}},{ multi: true })