const mongoose = require("mongoose");
const request = require('request-promise');
const Order = mongoose.model("Orders");
const User = mongoose.model("User");
const bcrypt = require('bcryptjs')
const Adminuser = mongoose.model("Adminuser");
const Products = mongoose.model("Products");
const ProductNotInventorys = mongoose.model("ProductNotInventorys");
const CsvUpload = mongoose.model("CsvUpload");
const Shelflocations = mongoose.model("Shelflocations")
const BillHistory = mongoose.model("BillHistorys");
const Transaction = mongoose.model("Transaction");

const moment = require("moment-timezone")

let date_time = new Date();
let date = ("0" + date_time.getDate()).slice(-2);
let month = ("0" + (date_time.getMonth() + 1)).slice(-2);
let year = date_time.getFullYear();

let current_date = year + "-" + month + "-" + date;

const express = require('express');
const app = express();
app.use(express.static('public/' + current_date));

// const { updateShopperrPriceAlgo, getMsrp } = require("../../apps/middlewares/priceAlgo");
// const { userValidation } = require('../../validation')

const axios = require('axios');

const AWS = require('aws-sdk');
const _ = require('lodash');
var fs = require('fs');
const path = require('path');

const xlsx = require('xlsx');

const csv = require('csvtojson');

ID = 'AKIAZQ3DPSAOW34EMAWP';    
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
});

exports.UpdateShelfLocation = async (req, res) => {
    var fileContent = req.files.file.data
    
    // let csv_data = await csv().fromString(fileContent.toString());
    let workbook = await xlsx.read(fileContent, { type: 'buffer' });

    // console.log(workbook.SheetNames);

    const sheetName = workbook.SheetNames[0];  // First sheet
    const sheet = workbook.Sheets[sheetName];

    // Convert the sheet data to JSON
    const jsonData = xlsx.utils.sheet_to_json(sheet);

    let sku_list = [];
    var d = new Date();
    // console.log(jsonData)
    // return false;

    await Promise.all(jsonData.map(async (item) => {
      try {
        // let sku = item.SKU;
        // let qty = item.Total;
        // let bin = item.Bin;

        let bin = item.Bin;
        let sku = item.Sku;
        let qty = item.Quantity;

        console.log(item)
        // return false;

        // const orders = await Order.findOneAndUpdate({mkpOrderId: item.mkpOrderId}, {$set: obj}, {orderSerial:1}, { new: true })
        const existingOrder = await Shelflocations.findOne({ "shelf": bin, "code" : sku });
        // const existingOrder = await Shelflocations.findOne({ "_id": mongoose.Types.ObjectId(id) });
        // console.log(existingOrder)
        /*if(existingOrder){
            
            let new_qty = 0;
            if(parseInt(qty)>parseInt(existingOrder.quantity)){
                new_qty = parseInt(qty)-parseInt(existingOrder.quantity)
            }else{
                new_qty = parseInt(existingOrder.quantity)-parseInt(qty)
            }

            if(new_qty < 0){
                new_qty = 0
            }
            
            let updateObj = {
                // "quantity" : parseInt(existingOrder.quantity)+parseInt(qty)
                "quantity" : qty,

            }
            
            // console.log(bin+'--'+sku)
            console.log(updateObj)
            await Shelflocations.updateOne({ "_id": mongoose.Types.ObjectId(existingOrder._id) }, { $set: updateObj }, { upsert: false }).then(() => {
                // console.log('done-'+sku+'--'+new_qty)
            });

            return false;

        }else{*/

            const shelflocations1 = await Shelflocations.findOne({}, {sort:1}).sort({_id:-1}).limit(1);
            
            const shelflocations = new Shelflocations({
                code:sku,
                shelf:bin,
                quantity:qty,
                sort:shelflocations1.sort
              });
            console.log(shelflocations)
            await shelflocations.save();
            
            // console.log(bin+'--'+sku)
        // }
        
        let result = { 'error': 0, 'message': 'Product updated successfully' };
        return res.status(200).json(result);
        

      }catch(err){
        let result = { 'error': 1, 'message': err };
        return { 'error': 1, 'message': err };
        // return res.status(200).json(result);
      }
    }));
}

exports.UpdateInQty = async (req, res) => {
    var fileContent = req.files.file.data
    
    let workbook = await xlsx.read(fileContent, { type: 'buffer' });

    // console.log(workbook.SheetNames);

    const sheetName = workbook.SheetNames[0];  // First sheet
    const sheet = workbook.Sheets[sheetName];

    // Convert the sheet data to JSON
    const jsonData = xlsx.utils.sheet_to_json(sheet);
    let sku_list = [];
    var d = new Date();
    // console.log(jsonData)

    // return false
    // const limitedCsvData = csv_data.slice(0, 15000);
    await Promise.all(jsonData.map(async (item) => {
      try {
        let sku = item.sku;
        let qty = item.qty;
        // let bucket = item.bucket;
        // let remark = item.remark;
        // console.log(item.sku+'--'+item.qty)

        // console.log(item)

        // const orders = await Order.findOneAndUpdate({mkpOrderId: item.mkpOrderId}, {$set: obj}, {orderSerial:1}, { new: true })
        const existingOrder = await Products.findOne({ "code": sku }, { stock:1, code:1 });
        // console.log(existingOrder)
        if(existingOrder){

            let newQty = '';
            let updateObj = {}

            // if(bucket=='Bulk'){

                newQty = existingOrder.stock.in_qty? parseInt(existingOrder.stock.in_qty)-parseInt(qty):qty;

                updateObj = {
                    "stock.in_qty" : parseInt(qty)
                }

            // }else if(bucket=='India'){
            //     newQty = existingOrder.stock.in_qty? parseInt(existingOrder.stock.in_qty)-parseInt(qty):qty;

            //     updateObj = {
            //         "stock.in_qty" : newQty
            //     }
            // }

            // console.log(remark)
            
            // if(remark=='India'){
            //     console.log(1111)
                // updateObj = {
                //     // "stock.in_qty" : newQty
                //     "stock.blk_qty" : parseInt(newQty)
                // }
            // }
            // else if(remark=='Bulk'){
                // updateObj = {
                //     "stock.blk_qty" : parseInt(newQty)
                // }
            // }
            
            // let updateObj = {
            //     // "stock.in_qty" : newQty
            //     "stock.in_qty" : parseInt(qty)
            // }
            // console.log(existingOrder.code)
            console.log(updateObj)
            // return false;
            await Products.updateOne({ "code": sku }, { $set: updateObj }, { upsert: false }).then(() => {
                console.log('done-'+sku+'--'+qty)
            });

            return false;

        }else{
            
            try{
                const productNotInventorys = new ProductNotInventorys({
                    code:item.sku
                  });
                await productNotInventorys.save();

            }catch(err){
                console.log(err)
            }

            // console.log('not found--'+item.sku+'--'+item.qty)
            //ProductNotInventorys
        }
        
        let result = { 'error': 0, 'message': 'Product updated successfully' };
        return res.status(200).json(result);
        

      }catch(err){
        let result = { 'error': 1, 'message': err };
        return { 'error': 1, 'message': err };
        // return res.status(200).json(result);
      }
    }));
}


/*exports.updateInQty = async (req, res) => {
    var fileContent = req.files.file.data
    
    let csv_data = await csv().fromString(fileContent.toString());
    let sku_list = [];
    var d = new Date();
    // console.log(csv_data)

    // return false
    const limitedCsvData = csv_data.slice(0, 17000);
    await Promise.all(limitedCsvData.map(async (item) => {
      try {
        
        // console.log(item.sku+'--'+item.qty)

        // const orders = await Order.findOneAndUpdate({mkpOrderId: item.mkpOrderId}, {$set: obj}, {orderSerial:1}, { new: true })
        const existingOrder = await Products.findOne({ "code": item.sku }, { stock:1 });
        // console.log(existingOrder)
        if(existingOrder){
            let updateObj = {
                "stock.in_qty" : item.qty
            }

            // console.log(item.sku+'--'+item.qty)
            // console.log(updateObj)

            await Products.updateOne({ "code": item.sku }, { $set: updateObj }, { upsert: false }).then(() => {
                console.log('done-'+item.sku+'--'+item.qty)
            });

            return false;

        }
        
        let result = { 'error': 0, 'message': 'Safe-T Claim updated successfully' };
        return res.status(200).json(result);
        

      }catch(err){
        let result = { 'error': 1, 'message': err };
        return { 'error': 1, 'message': err };
        // return res.status(200).json(result);
      }
    }));
}*/

exports.UpdateCategory = async (req, res) => {
    var fileContent = req.files.file.data
    
    let csv_data = await csv().fromString(fileContent.toString());
    let sku_list = [];
    var d = new Date();
    // console.log(csv_data)

    // return false
    const limitedCsvData = csv_data.slice(0, 100000);
    await Promise.all(limitedCsvData.map(async (item) => {
      try {
        
        // console.log(item.sku+'--'+item.qty)

        // const orders = await Order.findOneAndUpdate({mkpOrderId: item.mkpOrderId}, {$set: obj}, {orderSerial:1}, { new: true })
        const existingOrder = await Products.findOne({ "code": item.istore_product_id });
        // console.log(existingOrder)
        if(existingOrder){
            let updateObj = {
                "cat_id" : item.category_id
            }

            // console.log(item.sku+'--'+item.qty)
            // console.log(updateObj)

            // await Products.updateOne({ "code": item.sku }, { $set: updateObj }, { upsert: false }).then(() => {
            //     console.log('done-'+item.sku+'--'+item.qty)
            // });

            return false;

        }
        
        let result = { 'error': 0, 'message': 'Product updated successfully' };
        return res.status(200).json(result);
        

      }catch(err){
        let result = { 'error': 1, 'message': err };
        return { 'error': 1, 'message': err };
        // return res.status(200).json(result);
      }
    }));
}

exports.UpdateProductFinalPrice = async (req, res) => {
    try {
        var data = req.body.addProductRequestInfo;
		let orderDetails = [];
		let order_shipping = []; 

        console.log(data)
        // return false;

        data.forEach(async function (order) {

            console.log(order.orders_serial+"---"+order.final_price)
            // console.log(order.final_price)
            // console.log(order.final_price)
            
            const productData = await Order.findOne({ orderSerial: order.orders_serial }, {orderDetails:1})
            if(productData){
                
                // orderDetails = {
				// 	'finalPrice': order.final_price,
				// }

                // let updateObj = {
                //     orderDetails:orderDetails,
                // }
                
                // console.log(updateObj)
                console.log(productData._id)
                // await Order.updateOne({  _id: mongoose.Types.ObjectId(productData._id) }, { $push: updateObj }, { upsert: false }).then(() => {
                //     // console.log('done-'+istore_product_id+'--'+hsn_gst)
                // });

                await Order.updateOne({  _id: mongoose.Types.ObjectId(productData._id) }, { $set: {
                    "orderDetails.$[].finalPrice": order.final_price
                  } }, { upsert: false }).then(() => {
                    console.log('done-'+productData._id)
                });
            }


        })


    }catch(err){
        
    }
};

exports.AllUser = async (req, res) => {
    
    // console.log(req.body.searchUser)
    
    try{
        
        var query = {
            email: { $regex: new RegExp(req.body.searchUser, 'i') } // 'i' for case-insensitive
        };
        
        let data = [];
        const users = await User.find(query, {email:1});

        if(users.length>0){

            let obj = [];

            users.forEach((item) => {
                obj = {
                    id: item._id,
                    name: item.email
                }
                data.push(obj)
            })
            
            let result = { 'error': 0, 'message': data };
            return res.status(200).json(result);
        }else{
            return { 'error': 1, 'message': 'User not found' };
        }
    }catch(err){
        let result = { 'error': 1, 'message': err };
        return res.status(200).json(result);
    }
    
};

exports.UpdateTxn = async (req, res) => {
    
    // console.log(req.body)

    const userId = req.body.user
    const txn_id = req.body.txn_id
    const amt = parseInt(req.body.amt)
    const method = req.body.method


    const userEmail = await User.findOne({_id: mongoose.Types.ObjectId(userId)}, {email:1, phoneNo:1})
    
    // return false;
    try{

        const txnTable = new Transaction({
            user_id : userId,
            trans_id: txn_id,
            amount_paid : amt,
            pmethod : method,
            order_id: txn_id,
            email:userEmail.email,
            phone:userEmail.phoneNo,
            paymentAt:new Date()
        });

        await txnTable.save();
        
        const user = await User.findOne({ _id : mongoose.Types.ObjectId(userId) }, { balance:1 })
        if(user){
            const updateObj = {
                'balance' : user.balance + amt
            }
            
            await User.updateOne({ _id: mongoose.Types.ObjectId(user._id) }, { $set: updateObj }, { upsert: false });
        }

        const billhistory = await BillHistory.find({ merchantId : userId }).sort({_id:-1}).limit(1);
        if(billhistory.length>0){
            billhistory.forEach(async (item) => {
                // console.log(item)

                let beforeAmount = item.afterAmt;
                let afterAmt = item.afterAmt+amt;

                const updateBill = new BillHistory({
                    merchantId:userId,
                    pgOrderId:txn_id,
                    billType:2,
                    billAmt:amt,
                    beforeAmt: beforeAmount,
                    afterAmt : afterAmt,
                    crDate: new Date(),
                    modDate: new Date(),
                    comment: 'Recharge from System Admin'
                });

                await updateBill.save();

            })
        }else{
            const updateBill = new BillHistory({
                merchantId:userId,
                pgOrderId:txn_id,
                billType:2,
                billAmt:amt,
                beforeAmt: amt,
                afterAmt : amt,
                crDate: new Date(),
                modDate: new Date(),
                comment: 'Recharge from System Admin'
            })

            await updateBill.save();
        }

        let result = { 'error': 0, 'message': 'Balance updated successfully' };
        return res.status(200).json(result);
        
    }catch(err){
        let result = { 'error': 1, 'message': err };
        return res.status(200).json(result);
    }
    
};

const generateExcelFile = (data) => {
    const worksheet = xlsx.utils.json_to_sheet(data);
    const workbook = xlsx.utils.book_new();
    xlsx.utils.book_append_sheet(workbook, worksheet, 'Sheet1');
  
    // Write the workbook to a buffer
    const buffer = xlsx.write(workbook, { bookType: 'xlsx', type: 'buffer' });
    return buffer;
  };

async function uploadSupplierCsv(fileContent, path, Id, csvtype, file_name) {
    let supplierId = Id;
    await uploadExcel(fileContent, path)
    var url = process.env.S3_BUCKET_FILE_URL;
    const csvUpload = await new CsvUpload({
        type: csvtype,
        cond: [{ 'supplier_id': supplierId }],
        spId: mongoose.Types.ObjectId(supplierId),
        url: url + '/' + path,
        date: new Date(),
        localFile: file_name
    });
    try {
        const saveProduct = await csvUpload.save();
        return 'success';
    } catch (err) {
        return 'error';
    }
}
function makeid(length) {
    var result = '';
    var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    var charactersLength = characters.length;
    for (var i = 0; i < length; i++) {
        result += characters.charAt(Math.floor(Math.random() * charactersLength));
    }
    return result;
}
async function uploadExcel(file, key) {
    const params = {
        Bucket: process.env.S3_FILE_BUCKET,
        Key: key,
        Body: file
    };

    s3.upload(params, async function (err, data) {
        if (err) {
            throw err;
        }
        else {

        }
    });
};

