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

// 表结构
exports.schema = [{
    title: { type: String, unique: false, required: true },
    is_default: { type: Number, unique: false, required: false },
    projects: { type: Schema.Types.ObjectId, ref: "Project" }
}, {
    // 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 () {
        // 如果没有project则设定为默认project;
        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];
        }
        // 如果没有is_default,设定为0；
        this.is_default = this.is_default || 0;
        // 当前项目下面不能有重复的名称，没有判断


        let tag = await this.save();
        
        return tag
    },
    /**
     *  二种情况不能删除
     *  1、is_default =1 的时候，且project 存在  不能删除
     *  2、当tag下面存在URL的时候
     */
    delete: async function (_id) {
        let item = await this.model("Tag").findOne({ "_id": _id })
        if(item.is_default == 1){
            let pros = await this.model("Project").find({ "_id": item.projects._id });
            if( pros.length > 0){
                return {
                    code: "0002",
                    msg: "默认Tag无法在项目存在时被删除"
                }
            }
        }
        let urls = await this.model("Url").find({ projects: item.projects});
        
        if (urls.length > 0){
            return {
                code:"0001",
                msg:"Tag下面存在多个Url"
            }
        }

        return await this.model("Tag").remove({ "_id": _id });
    },
    findByProjectId: async function (pro) {
        let items = await this.model("Tag").find({ projects: pro });
        return items || [];
    },
    updateById: async function (ques) {
        let item = await this.model("Tag").update({ _id: ques._id }, ques);
        return item
    }
}

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