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 Category = mongoose.model("Category");
const CsvUpload = mongoose.model("CsvUpload");
// const ObjectsToCsv = require('objects-to-csv');
const WInward = mongoose.model("WInward");
const Wmsorder = mongoose.model("Wmsorder");
const Indiaoffshelf = mongoose.model("Indiaoffshelfs")
const Pincode = mongoose.model("Pincode")
const Baging = mongoose.model("Baging")
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 axios = require('axios');

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

const xlsx = require('xlsx');

const csv = require('csvtojson');

const ID = 'AKIAZQ3DPSAOW34EMAWP';
const SECRET = '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';
const BUCKET_NAME = 'test-bucket';
const s3 = new AWS.S3({
    accessKeyId: ID,
    secretAccessKey: SECRET,
    apiVersion: 'latest',
});


exports.getManifest = async (req, res) => {
	let resData ={};
	const dataRes = [];
	try {
		let method = req.body.method;
		
		let awb = req.body.awb;
		
		const wmsOrders = await Wmsorder.find(
			{ "ordership.ref_tracking_number": awb },
			{ "ordership.ref_tracking_number":1,"consignee_address2":1,"consignee_address1":1,"orders_code": 1,"consignee_city":1,"consignee_zip":1,"consignee_region":1,"consignee_first_name":1,"consignee_phone":1,"ordership.os_estimate_weight": 1,  "_id": 1 }
		);
		
		//console.log(wmsOrders,indiaOrders);return false;
		if(wmsOrders.length>0){
			const orderBagging = await new Baging({
				method: method,
				awb: awb,
				ref_number: wmsOrders[0].orders_code,
				city: wmsOrders[0].consignee_city,
				state: wmsOrders[0].consignee_region,
				pincode: wmsOrders[0].consignee_zip,
				name: wmsOrders[0].consignee_first_name,
				address1: wmsOrders[0].consignee_address1,
				address2: wmsOrders[0].consignee_address2,
				mobile: wmsOrders[0].consignee_phone,
				weight: wmsOrders[0].ordership[0].os_estimate_weight
			 });
			const manifestSave = await orderBagging.save();
			 const dataRes = [{
					_id:wmsOrders[0]._id,
					ordership:wmsOrders[0].ordership,
					orders_code:wmsOrders[0].orders_code,
					consignee_first_name:wmsOrders[0].consignee_first_name,
					consignee_zip:wmsOrders[0].consignee_zip,
					consignee_region:wmsOrders[0].consignee_region,
					consignee_city:wmsOrders[0].consignee_city,
					consignee_address1:wmsOrders[0].consignee_address1,
					consignee_address2:wmsOrders[0].consignee_address2,
					consignee_phone:wmsOrders[0].consignee_phone
				 }];
				 //console.log(dataRes);
				 resData = {
				success:1,
				orders:dataRes,
				error:0,
				msg:null
			};
				 
		} else {
			const indiaOrders = await Order.find(
				{ "order_shipping.os_tracking_no": awb },
				{ "order_shipping.os_tracking_no":1,"shippingAddress1":1,"shippingAddress2":1,"orderSerial": 1,"shippingCity":1,"shippingPostalCode":1,"shippingState":1,"recipientName":1,"shippingPhoneNumber":1,  "_id": 1 }
			);
			const orderBagging = await new Baging({
				method: method,
				awb: awb,
				ref_number: indiaOrders[0].orderSerial,
				city: indiaOrders[0].shippingCity,
				state: indiaOrders[0].shippingState,
				pincode: indiaOrders[0].shippingPostalCode,
				name: indiaOrders[0].consignee_first_name,
				address1: indiaOrders[0].shippingAddress1,
				address2: indiaOrders[0].shippingAddress2,
				mobile: indiaOrders[0].shippingPhoneNumber,
				weight: 0.0
			 });
			const manifestSave = await orderBagging.save();
			let order_shipping = [{
					ref_tracking_number:awb,
					os_estimate_weight:0.0
				}];
			
				
			 const dataRes = [{
					_id:indiaOrders[0]._id,
					ordership:order_shipping,
					orders_code:indiaOrders[0].orderSerial,
					consignee_first_name:indiaOrders[0].recipientName,
					consignee_zip:indiaOrders[0].shippingPostalCode,
					consignee_region:indiaOrders[0].shippingState,
					consignee_city:indiaOrders[0].shippingCity,
					consignee_address1:indiaOrders[0].shippingAddress1,
					consignee_address2:indiaOrders[0].shippingAddress2,
					consignee_phone:indiaOrders[0].shippingPhoneNumber
				 }];
			
				resData = {
				success:1,
				orders:dataRes,
				error:0,
				msg:null
			}; 
		}
		res.send(resData);
        
    } catch (error) {
        console.error("Error fetching wms:", error);
        res.status(500).json({ error: "Internal Server Error" });
    }

};

exports.getBagList = async (req, res) => {
	try {
		const results = {}
		const bagingData = await Baging.aggregate([
               // { $match: { createdAt: { $gte: new Date().toISOString() } } },
				{ $group: {_id: "$method", count: { $sum: 1 } }} ,
				{ $sort: { _id: 1} }
        ]);
        let orders = bagingData.map(async (item) => {
			return {
				"method": item._id,
				"count": item.count
			};

		});
	
		results.result = await Promise.all(orders);
		
        //console.log(results);
        res.send(results);
        
    } catch (error) {
        console.error("Error fetching wms:", error);
        res.status(500).json({ error: "Internal Server Error" });
    }

};

exports.DownloadBagList = async (req, res) => {
    
	let fromDate = req.body.fromDate;
	let bagList = req.body.bagList;
	let supplierId = req.body.userId;
	// console.log(supplierId)

	let d = new Date();

	try {

		const s3dir = "import_export/" + supplierId + d.getFullYear().toString() + "/" + (d.getMonth() + 1).toString() + "/";
        // console.log(s3dir)
        let filename = makeid(6) + '_' + supplierId + '.csv';
        let fullPath = s3dir + filename;


		endDate = fromDate + 'T23:59:59Z';

		let query = {
			createdAt : { $gte: fromDate, $lte: endDate },
			method : bagList
		}

		const bagingData = await Baging.find(query);
		// console.log(bagingData)

		const item_data = [];
        
		let orderData = await Promise.all(bagingData.map(async (item) => {
            
            let batchItemData = {
                'method': item.method,
                'awb': item.awb,
                'ref_number': item.ref_number,
                'city': item.city,
                'state': item.state,
                'pincode': item.pincode,
                name: item.name,
                address1: item.address1,
                address2: item.address2,
                mobile: item.mobile,
                weight: item.weight,
                createdAt: item.createdAt,
                updatedAt: item.updatedAt,
                
            };
        
            item_data.push(batchItemData);
        }));

		// console.log(item_data)
		// return false
		const excelBuffer = generateCSVFile(item_data);
		// const excelBuffer = generateExcelFile(item_data);
		
		var status = await uploadExcel(excelBuffer, s3dir + filename).then(async () => {
            var url = process.env.S3_BUCKET_FILE_URL
            url =  url + '/' + fullPath 
            // console.log(url)
            let result = { 'error': 0, 'message': url };
            return res.status(200).json(result);
        });

		// return res.send(bagingData)
	} catch (e) {
        res.status(500).json({ message: e.message })
    }

}

const generateCSVFile = (data) => {
    const worksheet = xlsx.utils.json_to_sheet(data);
    const csv = xlsx.utils.sheet_to_csv(worksheet);
    return csv;
};

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 {

        }
    });
};