const mongoose = require("mongoose");
const Products = mongoose.model("Products");
const jwt = require("jsonwebtoken");
const bcrypt = require("bcryptjs");
const solr = require("solr-client");
const moment = require('moment-timezone');
const { webAPiValidation } = require("../handlers/webValidation");
const request = require('request-promise');
var fs = require('fs');
const { Parser } = require('json2csv');
const AWS = require('aws-sdk');
const MainTag = mongoose.model("MainTag");//require("../../model/MainTag");
const BrowseNodes = mongoose.model("BrowseNodes");//require('../../model/BrowseNodes');
const SolrIndexingLog = mongoose.model("SolrIndexingLog");//require("../../model/SolrIndexingLog");
//const { updateShopperrPriceAlgo,getGlobalPrice} = require("../middlewares/priceAlgo");
const { result } = require('lodash');
const _ = require("lodash");
ID = 'AKIAZQ3DPSAOTI3ZHWEF';    
SECRET = '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';
// The name of the bucket that you have created
const BUCKET_NAME = 'test-bucket';
const s3 = new AWS.S3({
    accessKeyId: ID,
    secretAccessKey: SECRET
});

const connectSolr = () => {  
    const client = solr.createClient({
      host: process.env.SOLR_DEV_URL,
      port: "8983",
      core: "dsshopperr",
      path: "/solr",
    });
    return client;
};

exports.addproduct = async (req,res) => {
  let page = parseInt(req.query.page) || 1;
  const limitR = parseInt(req.query.limit) || 500;
  let startFrom = (page - 1) * limitR;
  try {
    let query = {};
    let product = await Products.find(query)
      .limit(limitR)
      .skip(startFrom)
      .lean()
      //.sort({ _id: -1})
      .select("imgUrl name _id tags tgs supplier_id handle price prices mrp sp quantity description code hsn weight uploaded_on cogs subtitle bcd igst swcOnBcd seaPrice invoicedesc cat pd_status pd_manage_status is_display options varientArray length width productMargin height bno channel spData category")
      // .explain();
     
    
    const countTotalProducts = await Products.countDocuments(query);
    //console.log(countTotalProducts);return false;
    const totalProductInsertedTillNow = limitR * page;
    const hasMoreProducts = countTotalProducts - totalProductInsertedTillNow;

    //await solrIndexing(product,'add');
    
    if(!product.length){
        return false;
    }
    
    let toAdd = [];
    product.forEach(async (singleProduct) => {
        toAdd.push(getAsyncArrayData(singleProduct));
    });
    if(!toAdd.length){
        return true;
    }
    toAdd = await Promise.all(toAdd);
    const client = connectSolr();
    client.autoCommit = true;
    client['add'](toAdd,(err,result)=>{
      if(err)
        //throw err;
        client.softCommit();
      
    });
    //return true;
    
    //console.log(countTotalProducts);return false;
    return res.status(200).json({
      input: {
        pageNumber: page,
        limit: limitR,
      },
      result: {
        status: 200,
        msg: "Inserted Successfully",
        totalProducts: countTotalProducts,
        Inserted: product.length,
        hasMore: hasMoreProducts >= 0 ? hasMoreProducts : 0,
      },
    });
  } catch (err) {
    let solrlog = new SolrIndexingLog({
      input: {
        pageNumber: page,
        limit: limitR,
      },
      output: {
        success: false,
        err,
      },
    });
    solrlog.save();
    return res.status(500).json({
      input: {
        pageNumber: page,
        limit: limitR,
      },
      result: { status: 500, msg: err.toString() },
    });
  } finally {
    console.clear();
  }
};

async function getAsyncArrayData(product) {
    const imgUrlSrc = product.imgUrl.map(({ src }) => src);
    //console.log(product);return false;
    const options = {};
    product.options.forEach((f) => {
        switch(f.name.toLowerCase()){
        case "color":
        case "colour":
            options['color'] = f.values;
            break;
        case "size":
            options['size'] = f.values;
            break;
        case "style":
            options['style'] = f.values;
            break;
        }
    });

    const pbcd = parseFloat(product.bcd) || 10;
    const pigst = parseFloat(product.igst) || 18;
    const pswc = parseFloat(product.swcOnBcd) || 10;

    //find tags string
    const validateMongoTagsId = product.tags.filter((tg) => mongoose.isValidObjectId(tg));

    const maintags = await MainTag.find({
        _id: { $in: validateMongoTagsId },
    }).select("tag");

    let category = product.category;
    let cat = [product.category];
    let scat = [product.category];
    if(product.bno && categories && !categories[product.bno]){
        let browseNode = await BrowseNodes.findOne({node:Number(product.bno)});
        if(browseNode){
            categories[product.bno] = browseNode;
            let path = browseNode.path.split("/");
            scat = catUris([...path]);

            category = path.shift();
            cat = path;
        }
    }
    let slug = "";
    if(product.bno && categories[product.bno]){
        slug = categories[product.bno].slug;
        let path = categories[product.bno].path.split("/");
        scat = catUris([...path])
        category = path.shift();
        cat = path;
    }
    
    const tagsArray = maintags.map((t) => t.tag.trim() );
    let factoryPrice = product.prices.STK_price;
    //console.log(product.prices);return false;
    const sp = chinaPriceAlgoSFC(factoryPrice, product.weight);
    //console.log(sp);return false;

    return {
        description: product.description?.replace(/<[^>]*>?/gm, "").replace(/\n/g, "")+" Sku:- "+product.code+", "+product?.vd?.map(e=>e.sku).join(", ") || "",
        id: product._id,
        imgUrl: imgUrlSrc,
        author: product.supplier_id,
        title: product.name,
        tags: product.tgs,
        url: product.handle,
        //efp: Math.ceil(getGlobalPrice(product.price)),
        exfactoryprice: factoryPrice,
        price: factoryPrice,
        inStock: parseInt(product.quantity) > 0,
        sku: product.code,
        mrp: sp.mrp,
        //sp: sp.price,
        hsncode: product.hsn,
        weight:product.weight,
        last_modified: new Date(product.uploaded_on),
        //cogs: Math.round(priceAlgo.dropshipperPrice.cogs ? priceAlgo.dropshipperPrice.cogs : 0).toFixed(2),
        content: product?.subtitle || "",
        bcd:pbcd,
        igst:pigst,
        swc: pswc,
        //seacogs: Math.round(priceAlgo.seaPrice.cogs ? Number(priceAlgo.seaPrice.cogs) : 0).toFixed(2),
        //seamrp: Math.round(priceAlgo.seaPrice.mrp ? Number(priceAlgo.seaPrice.mrp) : 0).toFixed(2),
        resourcename: product?.invoicedesc || "",
        productstatus: product.pd_status,
        productmanagestatus: product.pd_manage_status,
        displaystatus: product.is_display || 0,
        size: options?.size || [],
        color: options?.color || [],
        style: options?.style || [],
        //variantDescription: RemoveSeaPrice(product?.vd || []),
        variantOptions: product.options,
        tags: tagsArray,
        source: 1,
        category,
        cat,
        scat,
        //channel:getDomainName({channel:product.channel}),
        slug_s:slug
    };
}

function chinaPriceAlgoSFC (factoryPrice, product_weight) {
	var STK_Shopperr_price 	  = factoryPrice;
	var product_weight 		    = (product_weight/1000)*1.81;
	var ppPrice 			        = STK_Shopperr_price*12*1.22;
	var getDuty 				      = (ppPrice*38/100);
	var getLandedCost 			  = getDuty+ppPrice;
	var getFrieghtCost 		    = (795*product_weight*1.18);
	var chaCost 				      = 0;   
	var processingCost 		    = 12; 
	var lastMileCost 			    = 85;
	var getTotalCOCGS 			  = getLandedCost+getFrieghtCost+chaCost+processingCost+lastMileCost;
	var profitAdd15Percent 	  = (getTotalCOCGS*15/100)+getTotalCOCGS;
	var gstImpact 				    = ((profitAdd15Percent-getTotalCOCGS)*18/100);
	var gst_price 				    = profitAdd15Percent+gstImpact;
	
	var FourPercentAddInPrice = (gst_price*4)/100;
	var finalShopperrPrice 	  = gst_price+FourPercentAddInPrice;
	var product_msrp 			    = finalShopperrPrice*2.5;
	
	var GSTPrice              = finalShopperrPrice.toFixed(2);
  var productPricemrp       = product_msrp.toFixed(2);
  var totalCOCGS            = getTotalCOCGS.toFixed(2);
  var data                  = { 'price': GSTPrice, 'cogs': totalCOCGS, 'mrp': productPricemrp }
  return data;
}
