// fulfillmentStatus = if 1 => unfullfilled
// pd_status = 5 then product is draft if pd_status = 1 then active
const mongoose = require("mongoose");
const {mongooseConstantValues,channelCodes} = require('../apps/common/systemConstents')
//const {solrIndexing,deleteSolrIndexing} = require('../apps/common/Solr');
//const generateBarcodeFn = require("../apps/common/updateBarcodeCron");
var fs = require('fs');

const {EJSON} = require('bson');

const ProductSchema = mongoose.Schema({
    supplier_id: {
        type:'String',
        //  type: mongoose.Schema.Types.ObjectId, ref: "User" 
    }, 
    is_listed_on_ds:{
        type:Number,
        default:0
    },
    name: {
        type: String,   
        // required: true,
    },
    subtitle: {
        type: String,
    },
    handle: {
        type: String,
        unique:true
    },
    price: {
        type: Number,
        required: true,
    }, 
    STK_Shopperr_price: {
        type: Number,
    },
    test:{
        type:Number,
        default:10
    },
    mrp: {
        type: Number,
        required: true,
    },
    pmrp: {
        type: Number, 
    },
    sp: {
        type: Number,
        required: true,
    }, 
    quantity: {
        type: Number, 
    },
    weight: {
        type: Number, 
    },
    warranty: {
        type: String, 
    },
    description: {
        type: String,
    },
    category: {
        type: String,
    }, 
    code: {
        type: String, 
    },
    productImage: {
        type: Number
    },
    imgUrl:{
        type:Array
    },
    imgFromUrl:{
        type:Array
    },
    uploaded_on: {
        type: Date,
    },
    updated_on: {
        type: Date,
    },
    hsn: {
        type: String,
        default: '3921'
    },
    internal_sku: {
        type: String,
    },
    tags: {
        type: Array,
    },
    // color: {
    //   type: String,
    // },
    size: {
        type: String,
    },
    // tag: {
    //   type: String,
    // },
    varients: {
        type: Array,
    },
    options: {
        type: Array,
    },
    vo : {
        type:Object
    },
    vd :{
        type:Object
    },
    productSkuInfos :{
        type:Object
    },
    selliingPrice:{
        type: Number
    },
    comparePrice:{
        type: Number
    },
    shippingCharge:{
        type:Object
    },
    pd_model: {
        type: String,
    },
    cat_id:  {
        type: String,
    },
    pd_visible:{
        type:String,
    },
    length:{
        type:String,
    },
    width:{
        type:String,
    },
    height:{
        type:String,
    },
    pd_pack_unit:{
        type:String,
    },
    g_id:{
        type:String,
    },
    gst:{
        type:String,
    },
    pd_sum:{
        type:String,
    },
    pd_manage_status:{
        type:String,
    },
    pd_status:{
        type:String, 
        default:'5'
    },
    pd_brand:{
        type:String, 
    },
    pd_location:{
        type:String,
    },
    subtitle:{
        type:String,
    },
    invoicedesc:{
        type:String,
    },
    stock:{
        type:Object
    },
    prices:{
        type:Object
    },
    sid : {
        type:Object
    },
    cid : {
        type:Object
    },
    suid : {
        type:Object
    },
    is_display : {
        type:String
    },
    is_delete : {
        type:String
    },
    tgs : {
        type:String
    }, 
    bcd : {
        type:Number
    },
    igst : {
        type:Number
    },
    seaPrice : {
        type:Object
    },
    swcOnBcd : {
        type:Number
    },
    spId : {
        type:Number
    },
    cogs : {
        type:Number
    },
    productMargin : {
        type:Number
    },
    upSku : {
        type:Number
    },
    varStatus : {
        type:Number
    },
    price_update_flag : {
        type:Number
    },
    mu: {
        type: String
    },
    tgs: {
        type: String
    },
    marketPlaceUrl: { 
        type: String
    },
    marketPlacePrice: {
        type: Number
    },
    marketPlaceMrp: {
        type: Number
    },
    amazon : {
        type:Object
    },
    is_amazon_templete: {
        type:Number,
        default:0
    },
    taggedSuppliers: {
        type: []
    },
    so: {
        type: Number
    },
    st: {
        type: Number
    },
    stt: {
        type: Number,
    },
    sf: {
        type: Number
    },
    paso: {
        type: Number
    },
    past: {
        type: Number
    },
    pastt: {
        type: Number
    },
    pasf: {
        type: Number
    },
    deliveryDaysFrom: {
        type: Number
    },
    deliveryDaysTo: {
        type: Number
    },
    [mongooseConstantValues.NUMBER_OF_ITEMS]:{
        type: String
    },
    [mongooseConstantValues.PACKAGE_INCLUDES]:{
        type: String
    },
    [mongooseConstantValues.YEAR_OF_MANUFACTURE]:{
        type: String
    },
    [mongooseConstantValues.PRODUCT_EXPIRY]:{
        type: String
    },
    [mongooseConstantValues.IS_LIQUID]:{
        type: String
    },
    [mongooseConstantValues.IS_BATTARY]:{
        type: String
    },
    [mongooseConstantValues.PRODUCT_BULLET_POINTS]:{
        type: Array
    },
    [mongooseConstantValues.PRODUCT_BROWSE_NODE]:{
        type: Number
    },
    catId:{
        type:Object
    },  
    customfields:{
      type: Array
    }, 
    barcode : {
        type: String,
        default:'' 
    },
    uc_status : {
        type: Number,
        default:0 
    },
    spData : {
        type: Object 
    },
    channel : {
        type: Array
        //enum:channelCodes
    },
    barcodes : {
        type: Array 
    },
    skus : {
        type: Array 
    }
    ,
    cbm: {
        type: Number,
        default:'' 
    },
    d2cStatus: {
        type: Number,
        default:0
    },
    shopifyProductId: {
        type: Number,
    },
    priceUpdate:{
        type: Number,
        default:0
    },
    subscribeProduct:[
        {
          merchantId: {
            type: String,
          }
          
        }
      ]
},  {
    timestamps: true,
    videoUrl:{
        type:String,
    }
  });

ProductSchema.pre(['save'],async function (doc){
    try{
        this.set({ handle: generate_handle(doc.name) });
    } catch(err){
        console.log(err);
    }
}); 
 
ProductSchema.pre(['updateOne'],async function (doc){
    try{
        if(this._update.$set.name){
            this._update.$set.handle = generate_handle(this._update.$set.name);
        }
    } catch(err){
        console.log(err);
    }
}); 


ProductSchema.post(['save','insertMany'],async function (doc){
    try{
        let products = [];
        if(Array.isArray(doc)){
            products = doc;
        } else {
            products = [doc];
        }
        // solrIndexing(products,'add').then((result)=>{
        //     console.log(result,"solrIndexing");
        // });
        // generateBarcodeFn.updateProductsBarcode(products,productModel).then((result)=>{
        //     console.log(result,"updateProductsBarcode");
        // });
    } catch(err){
        console.log(err);
    }
});

ProductSchema.post(['updateMany','updateOne','findOneAndUpdate'],async function (doc){
    try{
        let docToUpdate = null;
        if(this._update.$set.uc_status || this._update.$set.poProcess){
            return true;
        }
        // if(this.op === 'updateOne' || this.op === "findOneAndUpdate"){
        //     docToUpdate = await this.model.findOne(this.getQuery());
        //     solrIndexing([docToUpdate],'update')
        // } else {
        //     docToUpdate = await this.model.find(this.getQuery());
        //     solrIndexing(docToUpdate,'update')
        // }
    } catch(err){
        console.log(err);
    }
}); 

ProductSchema.pre(['deleteOne','remove'],async function (doc){
    try{
        let docToUpdate = null;
        // if(this.op === 'deleteOne'){
        //     docToUpdate = await this.model.findOne(this.getQuery());
        //     await deleteSolrIndexing([docToUpdate]);
        // } else {
        //     docToUpdate = await this.model.find(this.getQuery());
        //     await deleteSolrIndexing(docToUpdate);
        // }
    } catch(err){
        console.log(err);
    }
}); 

ProductSchema.pre(/.*/i,async function (doc){
    try{
        if(this.getQuery){
            let query = this.getQuery();
            query = JSON.stringify(EJSON.serialize(query)).replace(/varientArray/g,'vd');
            query = JSON.parse(query);
            this.setQuery(EJSON.deserialize(query));
        }
        if(this.projection){
            let projection = this.projection();
            if(projection && projection.varientArray){
                projection.vd = 1;
                this.projection(projection);
            }
        }
        
        if(this.select && this.isSelected && this.isSelected('varientArray') && !this.isSelected('vd')){  
            this.select({vd:1});
        }
    } catch(err){
        console.log(err);
    }
}); 

ProductSchema.virtual('varientArray').
  get(function() {
    return this.vd;
  }).
  set(function(v) {
    this.vd = v;
});

async function generate_handle(title){
    return title.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/-$/, '').replace(/^-/, '');
}

ProductSchema.set('toJSON', { getters: true, virtuals: true });
ProductSchema.set('toObject', { getters: true, virtuals: true });
const productModel = mongoose.model("Products", ProductSchema);

module.exports = productModel;
// varStatus = Update shopify varient status if status update then it will 1
// price_update_flag = 1 if product uploaded by excel  0 = 
