const mongoose = require("mongoose");
const request = require('request-promise');
const Order = mongoose.model("Orders");
const Products = mongoose.model("Products");
const User = mongoose.model("User");
const bcrypt = require('bcryptjs')
const WInward = mongoose.model("WInward");
const OrderPickup = mongoose.model("OrderPickup");
const Wmsorder = mongoose.model("Wmsorder");
const Indiaoffshelf = mongoose.model("Indiaoffshelfs")
const Notindiaoffshelf = mongoose.model("Notindiaoffshelfs")
const Shelflocations = mongoose.model("Shelflocations")
const moment = require('moment-timezone');
var nodemailer = require("nodemailer");

const emailConfig = { 
    user: "AKIAZQ3DPSAO5V6HIJ53",
    password: "BLdhU1CZ9RB23yiTq0fuz6RzS5wwJo38OU9CeEmnwOuO",
    host: "email-smtp.us-east-1.amazonaws.com",
  };

function parseDateString(dateString) {
    // Split the date string into date and time parts
    const [datePart, timePart] = dateString.split(' ');
   
    // Split the date part into year, month, and day
    const [year, month, day] = datePart.split('-');
   
    // Split the time part into hour, minute, and second
    const [hour, minute, second] = timePart.split(':');
 
    // Create a Date object with parsed values
    return new Date(year, month - 1, day, hour, minute, second);
}

exports.InOffshelf1 = async (req,res) => {

    // startDate = moment().subtract(1, 'days').format('YYYY-MM-DD') + 'T00:00:00Z';
    const startDate = moment('2025-03-10').add(1, 'days').format('YYYY-MM-DD') + 'T00:00:00Z';
    // endDate = moment().subtract(1, 'days').format('YYYY-MM-DD') + 'T23:59:59Z';
 
    let query = {};
    
    query = {
        chinaProcess : {$in: [0,2,3]}, pStatus:{$in : ['PD', 'PP']}, oStatus: 'OB', inoffshelfStatus:0, sStatus: 'SS', orderDate: { $gte: startDate }
    }
    
    const orderList = await Order.find(query);
    // console.log(orderList.length);
    // return false;

    let number = 1;  // Starting number
    const width = 2; // Width for leading zeros

    let incNumberData = await Indiaoffshelf.find({}, {incNumber:1}).sort({_id:-1}).limit(1);
    
    let incNumber = 0;
    if(incNumberData.length>0){
        incNumber = incNumberData[0].incNumber;
        number = incNumber+1;
    }else{
        number = 1;
    }
     
    if(orderList.length>0){
        let x = 1;
        
        const ret = await ordersProcess(orderList, number, width);
        let result = { 'error': ret, 'msg': 'done' }
        // return res.status(200).json(result);
        // console.log(result)
        return;
        
    }else{
        let result = { 'error': 1, 'msg': 'Something went wrong' }
        // return res.status(400).json(result);
        // console.log(result)
        return;
    }

}

async function ordersProcess(orderList, number, width) {
    
    const now = new Date();
    const year = now.getFullYear();
    const month = now.getMonth() + 1; // Adding 1 to make it 1-based (January is 1, December is 12)
    const monthFormatted = month.toString().padStart(2, '0');
    const day = now.getDate();
    
    let generateOffshelfnum = `IN${year}${monthFormatted}${day}`;
    let formatnum = formatNumber(number, width);
    let generateOffshelf = generateOffshelfnum + formatnum;
    
    
    // Iterate over the orderList array
    for (const item of orderList) {
        
        // Iterate over orderDetails for each item
        for (const i of item.orderDetails) {
            // number++;
            let sku = "STK01" + i.sku;
            const shelflocationData = await Shelflocations.find({code: i.sku}).sort({sort:1})
            
            let shelflocation = '';
            let sort = '';
            let quantityShelf = '';

            if(shelflocationData.length>0){
                for (const shelf of shelflocationData) {
                    quantityShelf = shelf.quantity
                    if(shelf.quantity>0){
                        shelflocation = shelf.shelf;
                        sort = shelf.sort;
                        break;
                    }
                }
            }

            let trackingNumber = 0;
            let carrierName = '';
            
            if(item.order_shipping.length>0){
                trackingNumber = item.order_shipping[0].os_tracking_no
                let carrierFullName = item.order_shipping[0].carrier_name
                
                if(carrierFullName){
                    let carrierNameAr = carrierFullName.split(/(\s+)/);
                    carrierName = carrierNameAr[0]
                }else{
                    carrierName = carrierFullName
                }
                
            }
            
            let in_qty = 0;
            let blk_qty = 0;
            let updateObj1 = {}
            let qtyUpdate = [];

            let qtyError = 0;
            let binError = 0;

            try {
                const abc1 = await Shelflocations.find({code: i.sku, }).sort({bin:-1}).limit(1);
                // console.log(abc1)

                if(abc1.length>0){

                    abc1.forEach((val) => {
                        if(val.quantity>0 && val.shelf!=''){

                            //val.quantity
                            let newQty = 0;
                            if(val.quantity>i.quantity){
                                newQty = val.quantity-i.quantity
                            }

                            const shelfData = {
                                sku: "STK01" + i.sku,
                                orderId: item._id,
                                orderSerial: item.orderSerial,
                                mkpOrderId: item.mkpOrderId,
                                productName: i.title,
                                amount: i.consumerPrice,
                                shelfNumber: generateOffshelf,
                                incNumber: formatnum,
                                createdDate: new Date(),
                                quantity: newQty,
                                shelflocation: shelflocation,
                                sort: sort,
                                trackingNumber:trackingNumber,
                                shippingMethod:carrierName,
                                bin:val.shelf
                            };
                            console.log(val.quantity,i.quantity)
                            console.log(shelfData)
                            // await Indiaoffshelf.create(shelfData);
                                
                            let updateObj = {
                                inoffshelfStatus: 1,
                                updatedAt: new Date()
                            }
                            
                            // await Order.updateOne({ "_id": mongoose.Types.ObjectId(item._id) }, { $set: updateObj }, { upsert: false });
                            
                        }else{
                            if(val.quantity==0){
                                qtyError++;
                                console.log('0 quantity');
                            }

                            if(val.shelf==''){
                                binError++;
                                console.log('bin empty');
                            }


                        }
                    })

                }else{
                    console.log('No data');
                }
                

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

}

//Generate IndiaOffshelf and update quantity in shelflocation and in product table
exports.InOffshelf = async (req,res) => {
			
	// Define startDate and endDate
	const startDate = moment().subtract(1, 'days').format('YYYY-MM-DD') + 'T00:00:00Z';
	const endDate = moment().subtract(1, 'days').format('YYYY-MM-DD') + 'T23:59:59Z';

	// Format yesterday's date for logging or display
	const formattedYesterdayText1 = moment().subtract(1, 'days').format('ddd, D MMM YYYY H:m:s A');


	query = {
		chinaProcess: { $in: [0, 2, 3] },
		pStatus: { $in: ['PD', 'PP'] },
		oStatus: 'OB',
		inoffshelfStatus: 0,
		sStatus: 'SS',
		orderDate: { $gte: startDate, $lte: endDate }
	};
	
	// Fetch orders based on the query
	const orderList = await Order.find(query);

    // console.log(orderList);
    
    let number = 1;  // Starting number
    const width = 2; // Width for leading zeros

    let incNumberData = await Indiaoffshelf.find({}, {incNumber:1}).sort({_id:-1}).limit(1);
    
    let incNumber = 0;
    if(incNumberData.length>0){
        incNumber = incNumberData[0].incNumber;
        number = incNumber+1;
    }else{
        number = 1;
    }
    //  console.log(orderList.length); return false;
    if(orderList.length>0){
        let x = 1;
        
        const ret = await processOrders(orderList, number, width);

        // const sendDate = '2025-03-13';
        const sendDate = moment().format('YYYY-MM-DD');
        await notindiaoffshelfData(sendDate);
        let result = { 'error': ret, 'msg': 'done' }
        // return res.status(200).json(result);
        // console.log(result)
        return;
        
    }else{
        let result = { 'error': 1, 'msg': 'Something went wrong' }
        // return res.status(400).json(result);
        // console.log(result)
        return;
    }
}

async function processOrders(orderList, number, width) {
    
    const now = new Date();
    const year = now.getFullYear();
    const month = now.getMonth() + 1; // Adding 1 to make it 1-based (January is 1, December is 12)
    const monthFormatted = month.toString().padStart(2, '0');
    const day = now.getDate();
    
    let generateOffshelfnum = `IN${year}${monthFormatted}${day}`;
    let formatnum = formatNumber(number, width);
    let generateOffshelf = generateOffshelfnum + formatnum;
    
    
    // Iterate over the orderList array
    for (const item of orderList) {
        
        
        // Iterate over orderDetails for each item
        for (const i of item.orderDetails) {
            // number++;
            let sku = "STK01" + i.sku;
            const shelflocationData = await Shelflocations.find({code: i.sku}).sort({sort:1})
            
            let shelflocation = '';
            let sort = '';
            let quantityShelf = '';

            if(shelflocationData.length>0){
                for (const shelf of shelflocationData) {
                    quantityShelf = shelf.quantity
                    if(shelf.quantity>0){
                        shelflocation = shelf.shelf;
                        sort = shelf.sort;
                        break;
                    }
                }
            }

            let trackingNumber = 0;
            let carrierName = '';
            
            if(item.order_shipping.length>0){
                trackingNumber = item.order_shipping[0].os_tracking_no
                let carrierFullName = item.order_shipping[0].carrier_name
                
                if(carrierFullName){
                    let carrierNameAr = carrierFullName.split(/(\s+)/);
                    carrierName = carrierNameAr[0]
                }else{
                    carrierName = carrierFullName
                }
                
            }
            
            let in_qty = 0;
            let blk_qty = 0;
            let updateObj1 = {}
            let qtyUpdate = [];

            try {
                const abc1 = await Shelflocations.find({code: i.sku}).sort({_id:-1});

                fulfillOrder(abc1, i.sku, i.quantity).then(async result => {

                    // console.log(result.length)

                    if(result){
                        result.forEach(async (k) => {
                        
                            const shelfData = {
                                sku: "STK01" + i.sku,
                                orderId: item._id,
                                orderSerial: item.orderSerial,
                                mkpOrderId: item.mkpOrderId,
                                productName: i.title,
                                amount: i.consumerPrice,
                                shelfNumber: generateOffshelf,
                                incNumber: formatnum,
                                createdDate: new Date(),
                                quantity: k.qty,
                                shelflocation: shelflocation,
                                sort: sort,
                                trackingNumber:trackingNumber,
                                shippingMethod:carrierName,
                                bin:k.bin
                            };
    
                            await Indiaoffshelf.create(shelfData);
                        })

                        let updateObj = {
                            inoffshelfStatus: 1,
                            updatedAt: new Date()
                        }
                        
                        await Order.updateOne({ "_id": mongoose.Types.ObjectId(item._id) }, { $set: updateObj }, { upsert: false });
                    }else{
                        // console.log(abc1)

                        let qty = 0;
                        let shelf = '';
                        let remark = '';
                        if(abc1.length>0){
                            qty = abc1[0].quantity;
                            shelf = abc1[0].shelf;

                            if(abc1[0].quantity==0){
                                remark = 'Quantity is less than Order Quantity'
                            }
                            
                        }else{
                            remark = 'Data not exist in Shelflocation'
                        }

                        const notShelfData = {
                            sku: "STK01" + i.sku,
                            orderSerial: item.orderSerial,
                            createdDate: new Date(),
                            orderQty: i.quantity,
                            quantity: qty,
                            bin: shelf,
                            remark: remark
                        };

                        await Notindiaoffshelf.create(notShelfData)

                        // console.log(notShelfData)

                    }
                
                });

                /*if(item.chinaProcess==0){
                    if(parseInt(in_qty)>0){
                        updateObj1 = {
                            'stock.in_qty':parseInt(in_qty)-parseInt(i.quantity)
                        }
                    }else{
                        updateObj1 = {
                            'stock.in_qty':parseInt(i.quantity)
                        }
                    }
                }
    
                if(item.chinaProcess==3){
                    if(parseInt(in_qty)>0){
                        updateObj1 = {
                            'stock.blk_qty':parseInt(blk_qty)-parseInt(i.quantity)
                        }
                    }else{
                        updateObj1 = {
                            'stock.blk_qty':parseInt(i.quantity)
                        }
                    }
                }
                
                await Products.updateOne({ "code": i.sku }, { $set: updateObj1 }, { upsert: false });*/

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

}

/******************************** */

exports.getWmsData = async (req,res) => {
    // console.log(req.body)
    uploadOrdersnew(req.body);
}

/******************************** */

/***************************************88 */

exports.UploadWmsOrders = async (req,res) => {

    processPages();

};

/************** Mail function for NotIndiaOffshelf Data****************** */

async function notindiaoffshelfData(sendDate){

    const formattedYesterdayText1 = moment(sendDate).format('ddd, D MMM YYYY H:m:s A');

    // const startDate = moment('2025-03-10').add(1, 'days').format('YYYY-MM-DD') + 'T00:00:00Z';
    // const startDate = moment(sendDate).startOf('day').toDate();
    const startDate = moment(sendDate).format('YYYY-MM-DD') + 'T00:00:00Z';
    const endDate = moment(sendDate).format('YYYY-MM-DD') + 'T23:59:59Z';
    // const endDate = moment(sendDate).endOf('day').toDate();

    // console.log(startDate)
    // console.log(endDate)

    const notpicklist = await Notindiaoffshelf.find({ createdDate: { $gte: startDate, $lte: endDate } });
    // console.log(notpicklist)
    if(notpicklist.length>0){
        let html = '';
        html += `<style>
                    table {
                    font-family: arial, sans-serif;
                    border-collapse: collapse;
                    width: 100%;
                    font-size: 10px;
                    }
                    thead th{
                    background-color: yellow;
                    }
                    tfoot th{
                    background-color: yellow;
                    }
                    td, th {
                    border: 1px solid #dddddd;
                    text-align: left;
                    padding: 4px;
                    }

                    tr:nth-child(even) {
                    background-color: #dddddd;
                    }
                    </style>
                <table border="2">
                    <thead>
                        <tr>
                            <th>Order Serial</th>
                            <th>SKU</th>
                            <th>Quantity</th>
                            <th>Bin</th>
                            <th>Remark</th>
                        </tr>
                    </thead>`;
        
        notpicklist.forEach((item) => {
            // console.log(item)
            html +=     `<tr>
                            <td>${item.orderSerial}</td>
                            <td>${item.sku}</td>
                            <td>${item.quantity}</td>
                            <td>${item.bin}</td>
                            <td>${item.remark}</td>
                        </tr>`;
        })

        html += `</table>`;

        // console.log(html)
        
        let transporter = nodemailer.createTransport({
            host: emailConfig.host,
            port: 465,
            secure: true,
            auth: {
            user: emailConfig.user,
            pass: emailConfig.password,
            },
        });
        await transporter.sendMail({
            from: 'Shopperr <support@shopperr.in>',
            // to: 'ashutosh.singh@shopperr.in',
            to: 'minakshi.kanoji@shopperr.in',
            subject: 'NotIndiaOffShelf - '+ formattedYesterdayText1,
            html: html,
            },
            function (error, info) {
                if(error){
                    // console.log(error)
                    // return res.send({'status' : 1 , 'response' : 'Something went wrong.' })
                }else{
                    // console.log('Mail successfully send')
                    // return res.send({'status' : 0 , 'response' : 'Mail successfully send' })
                }
            }
        );
    }
}

/***************Mail function for NotIndiaOffshelf Data End************** */

/******************** */

async function fulfillOrder(inventory, sku, orderQty) {
    let remainingQty = orderQty;
    let allocations = [];
 
    for (const bin of inventory) {
        if (bin.code === sku && bin.quantity > 0) {
            let qtyToTake = Math.min(bin.quantity, remainingQty);
            bin.quantity -= qtyToTake;
            remainingQty -= qtyToTake;
            allocations.push({ bin: bin.shelf, sku: sku, qtyTaken: qtyToTake,binqty: bin.quantity });
            
            if (remainingQty === 0) break;
        }
    }
 
    if (remainingQty > 0) {
        // console.log(` Not enough stock to fulfill order of ${orderQty} for SKU: ${sku}`);
        return null;
    } else {
        
        let bin = [];

        for(let i=0;i<allocations.length; i++){
            
            let obj = {
                bin:allocations[i].bin,
                qty:allocations[i].qtyTaken
            }

            bin.push(obj)

            let updateObjShelf = {
                quantity: allocations[i].binqty
            }
           await Shelflocations.findOneAndUpdate({code: allocations[i].sku, shelf:allocations[i].bin}, { $set:updateObjShelf }, { upsert: false })
        }
        
        return bin;
    }
}
 
/**************** */


let page = 1;
async function fetchData(page){
    
    const uri = 'https://admin.chinafulfill.com/sub-system/get-india-order-pickup?params=';
    //var xx = '{"header":{"warehouseId":"9"%2C"cooperationId"%3A"1"%2C"token"%3A"TUlJQ1hnSUJBQUtCZ1FDd04%3D"%2C"key"%3A"TUlJQ1hnSUJBQUtCZ1FDd05zc3M%3D"}%2C"data"%3A{"is_labelling"%3A[0%2C2]%2C"sort"%3A"+id+desc"%2C"opi_add_time_from"%3A"2023-03-01+00%3A00%3A00"%2C"opi_add_time_to"%3A"2023-03-29+23%3A59%3A59"%2C"page"%3A1%2C"page_size"%3A10%2C"warehouse_id"%3A"9"}}';
    const encoded = encodeURI(uri);

    var yesterday_date = new Date();
    yesterday_date.setDate(yesterday_date.getDate() - 1);

    var last2date = new Date();
    last2date.setDate(last2date.getDate() - 2);

    var current_date = new Date();
    // console.log(moment(last2date).format("YYYY-MM-DD 00:00:00")); 
    // console.log(moment(yesterday_date).format("YYYY-MM-DD 23:59:59")); 
    
    // return false;
    
    const encodedUrl = {
        "header": {
            "warehouseId": "9",
            "cooperationId": "1",
            "token": "TUlJQ1hnSUJBQUtCZ1FDd04=",
            "key": "TUlJQ1hnSUJBQUtCZ1FDd05zc3M="
        },
        "data": {
            "is_labelling": [
                0,
                2
            ],
            "sort": " id desc",
            // "opi_add_time_from": moment(last2date).format("YYYY-MM-DD 00:00:00"),
            "opi_add_time_from": "2024-08-01 00:00:00",
            "opi_add_time_to": moment(yesterday_date).format("YYYY-MM-DD 23:59:59"),
            "page": page,
            "page_size": 50,
            "warehouse_id": "9"
        }
    };
    
    const header = JSON.stringify(encodedUrl);
    const url = uri + header;
    const options = {
        'method': 'GET',
        'url': url,
        'headers': {
            'Cookie': 'PHPSESSID=m0gqi0nasbkka33aoiaqnpmta2'
        }
    };

    return new Promise((resolve, reject) => {
        request(options, function (error, response) {
            if (error) {
                // console.log('error')
                // console.log(error)
                reject(error);
            } else {
                // console.log(response.body)
                resolve(response.body);
            }
        });
    })
}

async function processPages(){
    try{
        while(true){
            const responseBody = await fetchData(page);
            if(responseBody!==''){
                // console.log(responseBody);
                uploadOrders(responseBody);
                page++;
            }else{
                break;
            }
        }
    } catch(error){
        console.error('Error:', error);
    }
}

async function uploadOrders(data){
    
    // let d = JSON.parse(data);
    // let allData = d.data;
    let allData = data.data;
    
    // console.log(data.data)

    // return false;
    Object.keys(allData).forEach(async(key) => {
        let element = allData[key];
        
        if(element.order.customer_id==='STK01'){
            
            let productMapData = element.order.product;

            let op_status = 0;
            let opm_status = 0;
            if(element.order_pickup.op_orders_type==0){
                op_status = 4;
                opm_status = 0;
            }


            const productmap_data = [];
            if(element.order_pickup.order_pickup_map.length>0){
                for(const key of Object.keys(element.order_pickup.order_pickup_map)){
                    let item1 = element.order_pickup.order_pickup_map[key];
    
                    productmap_data.push({
                        op_code: item1.op_code,
                        orders_code: item1.orders_code,
                        opm_sort: item1.opm_sort,
                        opm_sortcode: item1.opm_sortcode,
                        product_id: item1.product_id,
                        opm_quantity: item1.opm_quantity,
                        wpb_id: item1.wpb_id,
                        sort_number: item1.sort_number,
                        container_code: item1.container_code,
                        upload_status: item1.upload_status,
                        opm_orders_type: item1.opm_orders_type,
                        opm_type: item1.opm_type,
                        opm_exce_status: item1.opm_exce_status,
                        opm_note: item1.opm_note,
                        ws_code: item1.ws_code,
                        user_id: item1.user_id,
                        opm_status: opm_status,
                        opm_pda: item1.opm_pda,
                        opm_create_date: item1.opm_create_date,
                        opm_last_update: item1.opm_last_update,
                        opm_package_update: item1.opm_package_update,
                        opm_make_date: item1.opm_make_date,
                        opm_is_rebinding: item1.opm_is_rebinding,
                        opm_exception_quantity: item1.opm_exception_quantity,
                        abo_area_code: item1.abo_area_code,
                        opm_pickup_user_id: item1.opm_pickup_user_id,
    
                    });
                }
            }else{
                return;
            }
            
            
            
            const orderPickup = await new OrderPickup({
                op_code: element.order_pickup.op_code,
                op_creater_id: element.order_pickup.op_creater_id,
                op_order_cnt: element.order_pickup.op_order_cnt,
                op_product_cnt: element.order_pickup.op_product_cnt,
                op_sku_cnt: element.order_pickup.op_sku_cnt,
                op_status: op_status,
                op_orders_type: element.order_pickup.op_orders_type,
                op_note: element.order_pickup.op_note,
                op_create_date: element.order_pickup.op_create_date,
                op_last_update: convertToDateOrNull(element.order_pickup.op_last_update),
                warehouse_id: element.order_pickup.warehouse_id,
                op_is_import: element.order_pickup.op_is_import,
                op_is_create_labels: element.order_pickup.op_is_create_labels,
                back_id: element.order_pickup.back_id,
                pickup_user_id: element.order_pickup.pickup_user_id,
                op_start_time: convertToDateOrNull(element.order_pickup.op_start_time),
                op_end_time: convertToDateOrNull(element.order_pickup.op_end_time),
                pickup_finish_time: convertToDateOrNull(element.order_pickup.pickup_finish_time),
                pick_type: element.order_pickup.pick_type,
                op_ref_code: element.order_pickup.op_ref_code,
                op_order_qty: element.order_pickup.op_order_qty,
                op_dispatch_date: element.order_pickup.op_dispatch_date,
                op_cancel_date: element.order_pickup.op_cancel_date,
                op_rto_date: element.order_pickup.op_rto_date,
                op_return_date: element.order_pickup.op_return_date,
                op_ticketed_date: element.order_pickup.op_ticketed_date,
                map: productmap_data,
                 
            });
            
            const ordership_data = [];
            ordership_data.push({
                orders_code: element.ordership.orders_code,
                tracking_number: element.ordership.tracking_number,
                ref_tracking_number: element.ordership.ref_tracking_number,
                transfer_number: element.ordership.transfer_number,
                combine_code: element.ordership.combine_code,
                ae_tracking_number: element.ordership.ae_tracking_number,
                warehouse_id: element.ordership.warehouse_id,
                carrier_code: element.ordership.carrier_code,
                os_status: element.ordership.os_status,
                os_qty: element.ordership.os_qty,
                os_estimate_weight: element.ordership.os_estimate_weight,
                os_weight: element.ordership.os_weight,
                os_vol_weight: element.ordership.os_vol_weight,
                os_weight_rate: element.ordership.os_weight_rate,
                os_length: element.ordership.os_length,
                os_width: element.ordership.os_width,
                os_height: element.ordership.os_height,
                os_declared_value: element.ordership.os_declared_value,
                os_guarantee_value: element.ordership.os_guarantee_value,
                os_cost_fee: element.ordership.os_cost_fee,
                os_deal_fee: element.ordership.os_deal_fee,
                os_reg_fee: element.ordership.os_reg_fee,
                os_addons_fee: element.ordership.os_addons_fee,
                os_other_fee: element.ordership.os_other_fee,
                os_shipping_fee: element.ordership.os_shipping_fee,
                os_insurance_fee: element.ordership.os_insurance_fee,
                os_vat_fee: element.ordership.os_vat_fee,
                os_shipping_fee_estimate: element.ordership.os_shipping_fee_estimate,
                os_fee_area: element.ordership.os_fee_area,
                currency_code: element.ordership.currency_code,
                currency_rate: element.ordership.currency_rate,
                os_fee_deduction_date: element.ordership.os_fee_deduction_date,
                os_fee_deduction_time: element.ordership.os_fee_deduction_time,
                os_send_date: element.ordership.os_send_date,
                exist_label: element.ordership.exist_label,
                os_create_date: element.ordership.os_create_date,
                os_last_update: element.ordership.os_last_update,
                os_image: element.ordership.os_image,
                delivered_date: element.ordership.delivered_date,
                change_number: element.ordership.change_number,
            
            });

            let allProduct = element.order.product;
            const product_data = [];

            for(const key of Object.keys(element.order.product)){
                let item = element.order.product[key];

                product_data.push({
                    orders_code: item.orders_code,
                    product_id: item.product_id,
                    product_sku: item.product_sku,
                    product_type: item.product_type,
                    op_type: item.op_type,
                    op_title: item.op_title,
                    op_description: item.op_description,
                    op_quantity: item.op_quantity,
                    op_category: item.op_category,
                    op_weight: item.op_weight,
                    op_length: item.op_length,
                    op_width: item.op_width,
                    op_height: item.op_height,
                    op_unit_price: item.op_unit_price,
                    op_mrp: item.op_mrp,
                    cn_description: item.cn_description,
                    hs_code: item.hs_code,
                    op_subtotal: item.op_subtotal,
                    op_origin: item.op_origin,
                    op_declared_value: item.op_declared_value,
                    op_ref_tnx: item.op_ref_tnx,
                    op_ref_item_id: item.op_ref_item_id,
                    op_ref_line_item: item.op_ref_line_item,
                    op_ref_buyer_id: item.op_ref_buyer_id,
                    op_ref_sku: item.op_ref_sku,
                    op_ref_barcode: item.op_ref_barcode,
                    op_special_type: item.op_special_type,
                    op_ref_paydate: item.op_ref_paydate,
                    op_last_update: item.op_last_update,
                    product_cost_price: item.product_cost_price,
                    op_sales_link: item.op_sales_link,
                    op_wbp_json: item.op_wbp_json
                });
            }
            
            const wmsOrder = await new Wmsorder({
                orders_code: element.order.orders_code ? element.order.orders_code : '',
                customer_id:  element.order.customer_id ? element.order.customer_id : '',
                warehouse_id:  element.order.warehouse_id ? element.order.warehouse_id : '',
                consignee_first_name:  element.order.consignee_first_name ? element.order.consignee_first_name : '',
                consignee_last_name:  element.order.consignee_last_name ? element.order.consignee_last_name : '',
                consignee_company: element.order.consignee_company ? element.order.consignee_company : '',
                consignee_country_id: element.order.consignee_country_id ? element.order.consignee_country_id : '',
                consignee_zip: element.order.consignee_zip ? element.order.consignee_zip : '',
                consignee_region: element.order.consignee_region ? element.order.consignee_region : '',
                consignee_city: element.order.consignee_city ? element.order.consignee_city : '',
                consignee_address1: element.order.consignee_address1 ? element.order.consignee_address1 : '',
                consignee_address2: element.order.consignee_address2 ? element.order.consignee_address2 : '',
                doorplate: element.order.doorplate ? element.order.doorplate : '',
                consignee_phone: element.order.consignee_phone ? element.order.consignee_phone : '',
                consignee_email: element.order.consignee_email ? element.order.consignee_email : '',
                shipping_method: element.order.shipping_method ? element.order.shipping_method : '',
                sub_shipping_method: element.order.sub_shipping_method ? element.order.sub_shipping_method : '',
                ship_area: element.order.ship_area ? element.order.ship_area : '',
                parcel_declared_value: element.order.parcel_declared_value ? element.order.parcel_declared_value : '',
                parcel_contents: element.order.parcel_contents ? element.order.parcel_contents : '',
                parcel_quantity: element.order.parcel_quantity ? element.order.parcel_quantity : '',
                order_attribute: element.order.order_attribute ? element.order.order_attribute : '',
                orders_status: element.order.orders_status ? element.order.orders_status : '',
                process_status: element.order.process_status ? element.order.process_status : '',
                problem_status: element.order.problem_status ? element.order.problem_status : '',
                import_status: element.order.import_status ? element.order.import_status : '',
                underreview_status: element.order.underreview_status ? element.order.underreview_status : '',
                shipping_fee_estimate: element.order.shipping_fee_estimate ? element.order.shipping_fee_estimate : '',
                shipping_fee: element.order.shipping_fee ? element.order.shipping_fee : '',
                currency: element.order.currency ? element.order.currency : '',
                add_time: element.order.add_time ? element.order.add_time : '',
                submit_time: element.order.submit_time ? element.order.submit_time : '',
                package_time: element.order.package_time ? element.order.package_time : '',
                ship_date: element.order.ship_date ? element.order.ship_date : '',
                send_date: convertToDateOrNull(element.order.send_date),
                delivered_date: convertToDateOrNull(element.order.delivered_date),
                last_modified_time: convertToDateOrNull(element.order.last_modified_time),
                order_stop_date: convertToDateOrNull(element.order.order_stop_date),
                import_time: convertToDateOrNull(element.order.import_time),
                print_time: convertToDateOrNull(element.order.print_time),
                order_print_id: element.order.order_print_id ? element.order.order_print_id : '',
                orders_print_type: element.order.orders_print_type ? element.order.orders_print_type : '',
                customer_order_code: element.order.customer_order_code ? element.order.customer_order_code : '',
                init_pickup_user_id: element.order.init_pickup_user_id ? element.order.init_pickup_user_id : '',
                pickup_user_id: element.order.pickup_user_id ? element.order.pickup_user_id : '',
                package_user_id: element.order.package_user_id ? element.order.package_user_id : '',
                outbound_user_id: element.order.outbound_user_id ? element.order.outbound_user_id : '',
                sorting_user_id: element.order.sorting_user_id ? element.order.sorting_user_id : '',
                remark: element.order.remark ? element.order.remark : '',
                is_special_order: element.order.is_special_order ? element.order.is_special_order : '',
                order_print_area: element.order.order_print_area ? element.order.order_print_area : '',
                order_type: element.order.order_type ? element.order.order_type : '',
                order_area_mixed: element.order.order_area_mixed ? element.order.order_area_mixed : '',
                evaluate: element.order.evaluate ? element.order.evaluate : '',
                cn_region_id: element.order.cn_region_id ? element.order.cn_region_id : '',
                package_type: element.order.package_type ? element.order.package_type : '',
                isreturn: element.order.isreturn ? element.order.isreturn : '',
                withbattery: element.order.withbattery ? element.order.withbattery : '',
                pay_by: element.order.pay_by ? element.order.pay_by : '',
                taxes_number: element.order.taxes_number ? element.order.taxes_number : '',
                is_remote: element.order.is_remote ? element.order.is_remote : '',
                is_pdapickup: element.order.is_pdapickup ? element.order.is_pdapickup : '',
                customer_label: element.order.customer_label ? element.order.customer_label : '',
                vat_fee: element.order.vat_fee ? element.order.vat_fee : '',
                duty_forward: element.order.duty_forward ? element.order.duty_forward : '',
                operation_mode: element.order.operation_mode ? element.order.operation_mode : '',
                signature: element.order.signature ? element.order.signature : '',
                order_item: element.order.order_item ? element.order.order_item : '',
                orders_from: element.order.orders_from ? element.order.orders_from : '',
                operator: element.order.operator ? element.order.operator : '',
                custom_alone: element.order.custom_alone ? element.order.custom_alone : '',
                cod_amount: element.order.cod_amount ? element.order.cod_amount : '',
                sub_process_status: element.order.sub_process_status ? element.order.sub_process_status : '',
                supplier: element.order.supplier ? element.order.supplier : '',
                posun_create_user: element.order.posun_create_user ? element.order.posun_create_user : '',
                is_labelling: element.order.is_labelling ? element.order.is_labelling : '',
                product:product_data,
                ordership:ordership_data
            });

            // console.log(wmsOrder);

            try {
                const orderData = await Wmsorder.find({orders_code:element.order.orders_code});
                if(orderData.length==0){
                    
                    // console.log(element.order_pickup.op_code)
                    const orderPickData = await OrderPickup.find({op_code:element.order_pickup.op_code});
                    const orderPickmapData = await OrderPickup.findOne({"map.orders_code":{ "$in" : [element.order.orders_code]}});
                    //console.log("orderPickData"+orderPickmapData)
                    if(orderPickData.length>0 ){
                        
                        if(!orderPickmapData){
                            await OrderPickup.updateOne(
                                { op_code: orderPickData[0].op_code }, 
                                { $push: { map: productmap_data
                             } }
                             );
                            //  console.log('updated-'+element.order_pickup.op_code);
    
                        } else {
                            // console.log('elsepart-'+element.order_pickup.op_code);
                        }
                       
                    }else{
                        // console.log('insert');
                        const orderPickupSave = await orderPickup.save();
                    }
                    const saveProduct = await wmsOrder.save();
                    // console.log('success');
                }
                
            } catch (err) {
                // console.log(err);
            }
        }
    });
    
}

async function uploadOrdersnew(data){
    
    // let d = JSON.parse(data);
    // let allData = d.data;
    let allData = data.data;
    let jk = 0;

    (async () => {
        for (const key of Object.keys(allData)) {
            let element = allData[key];
            jk++;
            
            if(element.order.customer_id==='STK01'){
            

                let productMapData = element.order.product;
    
                let op_status = 0;
                let opm_status = 0;
                if(element.order_pickup.op_orders_type==0){
                    op_status = 4;
                    opm_status = 0;
                }
    
                const productmap_data = [];
                if(element.order_pickup.order_pickup_map.length>0){
                    for(const key of Object.keys(element.order_pickup.order_pickup_map)){
                        let item1 = element.order_pickup.order_pickup_map[key];
        
                        productmap_data.push({
                            op_code: item1.op_code,
                            orders_code: item1.orders_code,
                            opm_sort: item1.opm_sort,
                            opm_sortcode: item1.opm_sortcode,
                            product_id: item1.product_id,
                            opm_quantity: item1.opm_quantity,
                            wpb_id: item1.wpb_id,
                            sort_number: item1.sort_number,
                            container_code: item1.container_code,
                            upload_status: item1.upload_status,
                            opm_orders_type: item1.opm_orders_type,
                            opm_type: item1.opm_type,
                            opm_exce_status: item1.opm_exce_status,
                            opm_note: item1.opm_note,
                            ws_code: item1.ws_code,
                            user_id: item1.user_id,
                            opm_status: opm_status,
                            opm_pda: item1.opm_pda,
                            opm_create_date: item1.opm_create_date,
                            opm_last_update: item1.opm_last_update,
                            opm_package_update: item1.opm_package_update,
                            opm_make_date: item1.opm_make_date,
                            opm_is_rebinding: item1.opm_is_rebinding,
                            opm_exception_quantity: item1.opm_exception_quantity,
                            abo_area_code: item1.abo_area_code,
                            opm_pickup_user_id: item1.opm_pickup_user_id,
        
                        });
                    }
                }else{
                    return;
                }
    
                const orderPickup = await new OrderPickup({
                    op_code: element.order_pickup.op_code,
                    op_creater_id: element.order_pickup.op_creater_id,
                    op_order_cnt: element.order_pickup.op_order_cnt,
                    op_product_cnt: element.order_pickup.op_product_cnt,
                    op_sku_cnt: element.order_pickup.op_sku_cnt,
                    op_status: op_status,
                    op_orders_type: element.order_pickup.op_orders_type,
                    op_note: element.order_pickup.op_note,
                    op_create_date: element.order_pickup.op_create_date,
                    op_last_update: convertToDateOrNull(element.order_pickup.op_last_update),
                    warehouse_id: element.order_pickup.warehouse_id,
                    op_is_import: element.order_pickup.op_is_import,
                    op_is_create_labels: element.order_pickup.op_is_create_labels,
                    back_id: element.order_pickup.back_id,
                    pickup_user_id: element.order_pickup.pickup_user_id,
                    op_start_time: convertToDateOrNull(element.order_pickup.op_start_time),
                    op_end_time: convertToDateOrNull(element.order_pickup.op_end_time),
                    pickup_finish_time: convertToDateOrNull(element.order_pickup.pickup_finish_time),
                    pick_type: element.order_pickup.pick_type,
                    op_ref_code: element.order_pickup.op_ref_code,
                    op_order_qty: element.order_pickup.op_order_qty,
                    op_dispatch_date: element.order_pickup.op_dispatch_date,
                    op_cancel_date: element.order_pickup.op_cancel_date,
                    op_rto_date: element.order_pickup.op_rto_date,
                    op_return_date: element.order_pickup.op_return_date,
                    op_ticketed_date: element.order_pickup.op_ticketed_date,
                    map: productmap_data
                });
    
                const ordership_data = [];
                ordership_data.push({
                    orders_code: element.ordership.orders_code,
                    tracking_number: element.ordership.tracking_number,
                    ref_tracking_number: element.ordership.ref_tracking_number,
                    transfer_number: element.ordership.transfer_number,
                    combine_code: element.ordership.combine_code,
                    ae_tracking_number: element.ordership.ae_tracking_number,
                    warehouse_id: element.ordership.warehouse_id,
                    carrier_code: element.ordership.carrier_code,
                    os_status: element.ordership.os_status,
                    os_qty: element.ordership.os_qty,
                    os_estimate_weight: element.ordership.os_estimate_weight,
                    os_weight: element.ordership.os_weight,
                    os_vol_weight: element.ordership.os_vol_weight,
                    os_weight_rate: element.ordership.os_weight_rate,
                    os_length: element.ordership.os_length,
                    os_width: element.ordership.os_width,
                    os_height: element.ordership.os_height,
                    os_declared_value: element.ordership.os_declared_value,
                    os_guarantee_value: element.ordership.os_guarantee_value,
                    os_cost_fee: element.ordership.os_cost_fee,
                    os_deal_fee: element.ordership.os_deal_fee,
                    os_reg_fee: element.ordership.os_reg_fee,
                    os_addons_fee: element.ordership.os_addons_fee,
                    os_other_fee: element.ordership.os_other_fee,
                    os_shipping_fee: element.ordership.os_shipping_fee,
                    os_insurance_fee: element.ordership.os_insurance_fee,
                    os_vat_fee: element.ordership.os_vat_fee,
                    os_shipping_fee_estimate: element.ordership.os_shipping_fee_estimate,
                    os_fee_area: element.ordership.os_fee_area,
                    currency_code: element.ordership.currency_code,
                    currency_rate: element.ordership.currency_rate,
                    os_fee_deduction_date: element.ordership.os_fee_deduction_date,
                    os_fee_deduction_time: element.ordership.os_fee_deduction_time,
                    os_send_date: element.ordership.os_send_date,
                    exist_label: element.ordership.exist_label,
                    os_create_date: element.ordership.os_create_date,
                    os_last_update: element.ordership.os_last_update,
                    os_image: element.ordership.os_image,
                    delivered_date: element.ordership.delivered_date,
                    change_number: element.ordership.change_number,
                
                });
    
                let allProduct = element.order.product;
                const product_data = [];
                
                for(const key of Object.keys(element.order.product)){
                    let item = element.order.product[key];
    
                    product_data.push({
                        orders_code: item.orders_code,
                        product_id: item.product_id,
                        product_sku: item.product_sku,
                        product_type: item.product_type,
                        op_type: item.op_type,
                        op_title: item.op_title,
                        op_description: item.op_description,
                        op_quantity: item.op_quantity,
                        op_category: item.op_category,
                        op_weight: item.op_weight,
                        op_length: item.op_length,
                        op_width: item.op_width,
                        op_height: item.op_height,
                        op_unit_price: item.op_unit_price,
                        op_mrp: item.op_mrp,
                        cn_description: item.cn_description,
                        hs_code: item.hs_code,
                        op_subtotal: item.op_subtotal,
                        op_origin: item.op_origin,
                        op_declared_value: item.op_declared_value,
                        op_ref_tnx: item.op_ref_tnx,
                        op_ref_item_id: item.op_ref_item_id,
                        op_ref_line_item: item.op_ref_line_item,
                        op_ref_buyer_id: item.op_ref_buyer_id,
                        op_ref_sku: item.op_ref_sku,
                        op_ref_barcode: item.op_ref_barcode,
                        op_special_type: item.op_special_type,
                        op_ref_paydate: item.op_ref_paydate,
                        op_last_update: item.op_last_update,
                        product_cost_price: item.product_cost_price,
                        op_sales_link: item.op_sales_link,
                        op_wbp_json: item.op_wbp_json
                    });
                }
    
                const wmsOrder = await new Wmsorder({
                    orders_code: element.order.orders_code ? element.order.orders_code : '',
                    customer_id:  element.order.customer_id ? element.order.customer_id : '',
                    warehouse_id:  element.order.warehouse_id ? element.order.warehouse_id : '',
                    consignee_first_name:  element.order.consignee_first_name ? element.order.consignee_first_name : '',
                    consignee_last_name:  element.order.consignee_last_name ? element.order.consignee_last_name : '',
                    consignee_company: element.order.consignee_company ? element.order.consignee_company : '',
                    consignee_country_id: element.order.consignee_country_id ? element.order.consignee_country_id : '',
                    consignee_zip: element.order.consignee_zip ? element.order.consignee_zip : '',
                    consignee_region: element.order.consignee_region ? element.order.consignee_region : '',
                    consignee_city: element.order.consignee_city ? element.order.consignee_city : '',
                    consignee_address1: element.order.consignee_address1 ? element.order.consignee_address1 : '',
                    consignee_address2: element.order.consignee_address2 ? element.order.consignee_address2 : '',
                    doorplate: element.order.doorplate ? element.order.doorplate : '',
                    consignee_phone: element.order.consignee_phone ? element.order.consignee_phone : '',
                    consignee_email: element.order.consignee_email ? element.order.consignee_email : '',
                    shipping_method: element.order.shipping_method ? element.order.shipping_method : '',
                    sub_shipping_method: element.order.sub_shipping_method ? element.order.sub_shipping_method : '',
                    ship_area: element.order.ship_area ? element.order.ship_area : '',
                    parcel_declared_value: element.order.parcel_declared_value ? element.order.parcel_declared_value : '',
                    parcel_contents: element.order.parcel_contents ? element.order.parcel_contents : '',
                    parcel_quantity: element.order.parcel_quantity ? element.order.parcel_quantity : '',
                    order_attribute: element.order.order_attribute ? element.order.order_attribute : '',
                    orders_status: element.order.orders_status ? element.order.orders_status : '',
                    process_status: element.order.process_status ? element.order.process_status : '',
                    problem_status: element.order.problem_status ? element.order.problem_status : '',
                    import_status: element.order.import_status ? element.order.import_status : '',
                    underreview_status: element.order.underreview_status ? element.order.underreview_status : '',
                    shipping_fee_estimate: element.order.shipping_fee_estimate ? element.order.shipping_fee_estimate : '',
                    shipping_fee: element.order.shipping_fee ? element.order.shipping_fee : '',
                    currency: element.order.currency ? element.order.currency : '',
                    add_time: element.order.add_time ? element.order.add_time : '',
                    submit_time: element.order.submit_time ? element.order.submit_time : '',
                    package_time: element.order.package_time ? element.order.package_time : '',
                    ship_date: element.order.ship_date ? element.order.ship_date : '',
                    send_date: convertToDateOrNull(element.order.send_date),
                    delivered_date: convertToDateOrNull(element.order.delivered_date),
                    last_modified_time: convertToDateOrNull(element.order.last_modified_time),
                    order_stop_date: convertToDateOrNull(element.order.order_stop_date),
                    import_time: convertToDateOrNull(element.order.import_time),
                    print_time: convertToDateOrNull(element.order.print_time),
                    order_print_id: element.order.order_print_id ? element.order.order_print_id : '',
                    orders_print_type: element.order.orders_print_type ? element.order.orders_print_type : '',
                    customer_order_code: element.order.customer_order_code ? element.order.customer_order_code : '',
                    init_pickup_user_id: element.order.init_pickup_user_id ? element.order.init_pickup_user_id : '',
                    pickup_user_id: element.order.pickup_user_id ? element.order.pickup_user_id : '',
                    package_user_id: element.order.package_user_id ? element.order.package_user_id : '',
                    outbound_user_id: element.order.outbound_user_id ? element.order.outbound_user_id : '',
                    sorting_user_id: element.order.sorting_user_id ? element.order.sorting_user_id : '',
                    remark: element.order.remark ? element.order.remark : '',
                    is_special_order: element.order.is_special_order ? element.order.is_special_order : '',
                    order_print_area: element.order.order_print_area ? element.order.order_print_area : '',
                    order_type: element.order.order_type ? element.order.order_type : '',
                    order_area_mixed: element.order.order_area_mixed ? element.order.order_area_mixed : '',
                    evaluate: element.order.evaluate ? element.order.evaluate : '',
                    cn_region_id: element.order.cn_region_id ? element.order.cn_region_id : '',
                    package_type: element.order.package_type ? element.order.package_type : '',
                    isreturn: element.order.isreturn ? element.order.isreturn : '',
                    withbattery: element.order.withbattery ? element.order.withbattery : '',
                    pay_by: element.order.pay_by ? element.order.pay_by : '',
                    taxes_number: element.order.taxes_number ? element.order.taxes_number : '',
                    is_remote: element.order.is_remote ? element.order.is_remote : '',
                    is_pdapickup: element.order.is_pdapickup ? element.order.is_pdapickup : '',
                    customer_label: element.order.customer_label ? element.order.customer_label : '',
                    vat_fee: element.order.vat_fee ? element.order.vat_fee : '',
                    duty_forward: element.order.duty_forward ? element.order.duty_forward : '',
                    operation_mode: element.order.operation_mode ? element.order.operation_mode : '',
                    signature: element.order.signature ? element.order.signature : '',
                    order_item: element.order.order_item ? element.order.order_item : '',
                    orders_from: element.order.orders_from ? element.order.orders_from : '',
                    operator: element.order.operator ? element.order.operator : '',
                    custom_alone: element.order.custom_alone ? element.order.custom_alone : '',
                    cod_amount: element.order.cod_amount ? element.order.cod_amount : '',
                    sub_process_status: element.order.sub_process_status ? element.order.sub_process_status : '',
                    supplier: element.order.supplier ? element.order.supplier : '',
                    posun_create_user: element.order.posun_create_user ? element.order.posun_create_user : '',
                    is_labelling: element.order.is_labelling ? element.order.is_labelling : '',
                    product:product_data,
                    ordership:ordership_data
                });
    
                // console.log(wmsOrder)
    
                try {
                    const orderData = await Wmsorder.find({orders_code:element.order.orders_code});
                    // const orderData = await findwmsorder(element.order.orders_code)
                    // console.log(orderData)
                    if(orderData==0){
                        
                        // console.log(element.order_pickup.op_code)
                        const orderPickData = await OrderPickup.find({op_code:element.order_pickup.op_code});
                        // console.log(orderPickData)
                        const orderPickmapData = await OrderPickup.findOne({"map.orders_code":{ "$in" : [element.order.orders_code]}});
                        //console.log("orderPickData"+orderPickmapData)
                        if(orderPickData.length>0 ){
                            
                            if(!orderPickmapData){
                                await OrderPickup.updateOne(
                                    { op_code: orderPickData[0].op_code }, 
                                    { $push: { map: productmap_data
                                 } }
                                 );
                                //  console.log('updated-'+element.order_pickup.op_code);
        
                            } else {
                                // console.log('elsepart-'+element.order_pickup.op_code);
                            }
                           
                        }else{
                            // console.log('insert');
    
                            const orderPickupSave = await orderPickup.save();
                        }
    
                        const saveProduct = await wmsOrder.save();
                        // console.log('success');
                    }
                    
                } catch (err) {
                    // console.log(err);
                }
    
                // console.log(jk)
            }
    
            // console.log(jk);
        }
    })();

    
    return false;

    Object.keys(allData).forEach(async(key) => {
        let element = allData[key];
        jk++;
        
        if(element.order.customer_id==='STK01'){
            
            let productMapData = element.order.product;

            let op_status = 0;
            let opm_status = 0;
            if(element.order_pickup.op_orders_type==0){
                op_status = 4;
                opm_status = 0;
            }


            const productmap_data = [];
            if(element.order_pickup.order_pickup_map.length>0){
                for(const key of Object.keys(element.order_pickup.order_pickup_map)){
                    let item1 = element.order_pickup.order_pickup_map[key];
    
                    productmap_data.push({
                        op_code: item1.op_code,
                        orders_code: item1.orders_code,
                        opm_sort: item1.opm_sort,
                        opm_sortcode: item1.opm_sortcode,
                        product_id: item1.product_id,
                        opm_quantity: item1.opm_quantity,
                        wpb_id: item1.wpb_id,
                        sort_number: item1.sort_number,
                        container_code: item1.container_code,
                        upload_status: item1.upload_status,
                        opm_orders_type: item1.opm_orders_type,
                        opm_type: item1.opm_type,
                        opm_exce_status: item1.opm_exce_status,
                        opm_note: item1.opm_note,
                        ws_code: item1.ws_code,
                        user_id: item1.user_id,
                        opm_status: opm_status,
                        opm_pda: item1.opm_pda,
                        opm_create_date: item1.opm_create_date,
                        opm_last_update: item1.opm_last_update,
                        opm_package_update: item1.opm_package_update,
                        opm_make_date: item1.opm_make_date,
                        opm_is_rebinding: item1.opm_is_rebinding,
                        opm_exception_quantity: item1.opm_exception_quantity,
                        abo_area_code: item1.abo_area_code,
                        opm_pickup_user_id: item1.opm_pickup_user_id,
    
                    });
                }
            }else{
                return;
            }
            
            
            const orderPickup = await new OrderPickupnew({
                op_code: element.order_pickup.op_code,
                op_creater_id: element.order_pickup.op_creater_id,
                op_order_cnt: element.order_pickup.op_order_cnt,
                op_product_cnt: element.order_pickup.op_product_cnt,
                op_sku_cnt: element.order_pickup.op_sku_cnt,
                op_status: op_status,
                op_orders_type: element.order_pickup.op_orders_type,
                op_note: element.order_pickup.op_note,
                op_create_date: element.order_pickup.op_create_date,
                op_last_update: convertToDateOrNull(element.order_pickup.op_last_update),
                warehouse_id: element.order_pickup.warehouse_id,
                op_is_import: element.order_pickup.op_is_import,
                op_is_create_labels: element.order_pickup.op_is_create_labels,
                back_id: element.order_pickup.back_id,
                pickup_user_id: element.order_pickup.pickup_user_id,
                op_start_time: convertToDateOrNull(element.order_pickup.op_start_time),
                op_end_time: convertToDateOrNull(element.order_pickup.op_end_time),
                pickup_finish_time: convertToDateOrNull(element.order_pickup.pickup_finish_time),
                pick_type: element.order_pickup.pick_type,
                op_ref_code: element.order_pickup.op_ref_code,
                op_order_qty: element.order_pickup.op_order_qty,
                op_dispatch_date: element.order_pickup.op_dispatch_date,
                op_cancel_date: element.order_pickup.op_cancel_date,
                op_rto_date: element.order_pickup.op_rto_date,
                op_return_date: element.order_pickup.op_return_date,
                op_ticketed_date: element.order_pickup.op_ticketed_date,
                map: productmap_data,
                 
            });
            
            const ordership_data = [];
            ordership_data.push({
                orders_code: element.ordership.orders_code,
                tracking_number: element.ordership.tracking_number,
                ref_tracking_number: element.ordership.ref_tracking_number,
                transfer_number: element.ordership.transfer_number,
                combine_code: element.ordership.combine_code,
                ae_tracking_number: element.ordership.ae_tracking_number,
                warehouse_id: element.ordership.warehouse_id,
                carrier_code: element.ordership.carrier_code,
                os_status: element.ordership.os_status,
                os_qty: element.ordership.os_qty,
                os_estimate_weight: element.ordership.os_estimate_weight,
                os_weight: element.ordership.os_weight,
                os_vol_weight: element.ordership.os_vol_weight,
                os_weight_rate: element.ordership.os_weight_rate,
                os_length: element.ordership.os_length,
                os_width: element.ordership.os_width,
                os_height: element.ordership.os_height,
                os_declared_value: element.ordership.os_declared_value,
                os_guarantee_value: element.ordership.os_guarantee_value,
                os_cost_fee: element.ordership.os_cost_fee,
                os_deal_fee: element.ordership.os_deal_fee,
                os_reg_fee: element.ordership.os_reg_fee,
                os_addons_fee: element.ordership.os_addons_fee,
                os_other_fee: element.ordership.os_other_fee,
                os_shipping_fee: element.ordership.os_shipping_fee,
                os_insurance_fee: element.ordership.os_insurance_fee,
                os_vat_fee: element.ordership.os_vat_fee,
                os_shipping_fee_estimate: element.ordership.os_shipping_fee_estimate,
                os_fee_area: element.ordership.os_fee_area,
                currency_code: element.ordership.currency_code,
                currency_rate: element.ordership.currency_rate,
                os_fee_deduction_date: element.ordership.os_fee_deduction_date,
                os_fee_deduction_time: element.ordership.os_fee_deduction_time,
                os_send_date: element.ordership.os_send_date,
                exist_label: element.ordership.exist_label,
                os_create_date: element.ordership.os_create_date,
                os_last_update: element.ordership.os_last_update,
                os_image: element.ordership.os_image,
                delivered_date: element.ordership.delivered_date,
                change_number: element.ordership.change_number,
            
            });

            let allProduct = element.order.product;
            const product_data = [];
            
            for(const key of Object.keys(element.order.product)){
                let item = element.order.product[key];

                product_data.push({
                    orders_code: item.orders_code,
                    product_id: item.product_id,
                    product_sku: item.product_sku,
                    product_type: item.product_type,
                    op_type: item.op_type,
                    op_title: item.op_title,
                    op_description: item.op_description,
                    op_quantity: item.op_quantity,
                    op_category: item.op_category,
                    op_weight: item.op_weight,
                    op_length: item.op_length,
                    op_width: item.op_width,
                    op_height: item.op_height,
                    op_unit_price: item.op_unit_price,
                    op_mrp: item.op_mrp,
                    cn_description: item.cn_description,
                    hs_code: item.hs_code,
                    op_subtotal: item.op_subtotal,
                    op_origin: item.op_origin,
                    op_declared_value: item.op_declared_value,
                    op_ref_tnx: item.op_ref_tnx,
                    op_ref_item_id: item.op_ref_item_id,
                    op_ref_line_item: item.op_ref_line_item,
                    op_ref_buyer_id: item.op_ref_buyer_id,
                    op_ref_sku: item.op_ref_sku,
                    op_ref_barcode: item.op_ref_barcode,
                    op_special_type: item.op_special_type,
                    op_ref_paydate: item.op_ref_paydate,
                    op_last_update: item.op_last_update,
                    product_cost_price: item.product_cost_price,
                    op_sales_link: item.op_sales_link,
                    op_wbp_json: item.op_wbp_json
                });
            }
            
            const wmsOrder = await new Wmsordernew({
                orders_code: element.order.orders_code ? element.order.orders_code : '',
                customer_id:  element.order.customer_id ? element.order.customer_id : '',
                warehouse_id:  element.order.warehouse_id ? element.order.warehouse_id : '',
                consignee_first_name:  element.order.consignee_first_name ? element.order.consignee_first_name : '',
                consignee_last_name:  element.order.consignee_last_name ? element.order.consignee_last_name : '',
                consignee_company: element.order.consignee_company ? element.order.consignee_company : '',
                consignee_country_id: element.order.consignee_country_id ? element.order.consignee_country_id : '',
                consignee_zip: element.order.consignee_zip ? element.order.consignee_zip : '',
                consignee_region: element.order.consignee_region ? element.order.consignee_region : '',
                consignee_city: element.order.consignee_city ? element.order.consignee_city : '',
                consignee_address1: element.order.consignee_address1 ? element.order.consignee_address1 : '',
                consignee_address2: element.order.consignee_address2 ? element.order.consignee_address2 : '',
                doorplate: element.order.doorplate ? element.order.doorplate : '',
                consignee_phone: element.order.consignee_phone ? element.order.consignee_phone : '',
                consignee_email: element.order.consignee_email ? element.order.consignee_email : '',
                shipping_method: element.order.shipping_method ? element.order.shipping_method : '',
                sub_shipping_method: element.order.sub_shipping_method ? element.order.sub_shipping_method : '',
                ship_area: element.order.ship_area ? element.order.ship_area : '',
                parcel_declared_value: element.order.parcel_declared_value ? element.order.parcel_declared_value : '',
                parcel_contents: element.order.parcel_contents ? element.order.parcel_contents : '',
                parcel_quantity: element.order.parcel_quantity ? element.order.parcel_quantity : '',
                order_attribute: element.order.order_attribute ? element.order.order_attribute : '',
                orders_status: element.order.orders_status ? element.order.orders_status : '',
                process_status: element.order.process_status ? element.order.process_status : '',
                problem_status: element.order.problem_status ? element.order.problem_status : '',
                import_status: element.order.import_status ? element.order.import_status : '',
                underreview_status: element.order.underreview_status ? element.order.underreview_status : '',
                shipping_fee_estimate: element.order.shipping_fee_estimate ? element.order.shipping_fee_estimate : '',
                shipping_fee: element.order.shipping_fee ? element.order.shipping_fee : '',
                currency: element.order.currency ? element.order.currency : '',
                add_time: element.order.add_time ? element.order.add_time : '',
                submit_time: element.order.submit_time ? element.order.submit_time : '',
                package_time: element.order.package_time ? element.order.package_time : '',
                ship_date: element.order.ship_date ? element.order.ship_date : '',
                send_date: convertToDateOrNull(element.order.send_date),
                delivered_date: convertToDateOrNull(element.order.delivered_date),
                last_modified_time: convertToDateOrNull(element.order.last_modified_time),
                order_stop_date: convertToDateOrNull(element.order.order_stop_date),
                import_time: convertToDateOrNull(element.order.import_time),
                print_time: convertToDateOrNull(element.order.print_time),
                order_print_id: element.order.order_print_id ? element.order.order_print_id : '',
                orders_print_type: element.order.orders_print_type ? element.order.orders_print_type : '',
                customer_order_code: element.order.customer_order_code ? element.order.customer_order_code : '',
                init_pickup_user_id: element.order.init_pickup_user_id ? element.order.init_pickup_user_id : '',
                pickup_user_id: element.order.pickup_user_id ? element.order.pickup_user_id : '',
                package_user_id: element.order.package_user_id ? element.order.package_user_id : '',
                outbound_user_id: element.order.outbound_user_id ? element.order.outbound_user_id : '',
                sorting_user_id: element.order.sorting_user_id ? element.order.sorting_user_id : '',
                remark: element.order.remark ? element.order.remark : '',
                is_special_order: element.order.is_special_order ? element.order.is_special_order : '',
                order_print_area: element.order.order_print_area ? element.order.order_print_area : '',
                order_type: element.order.order_type ? element.order.order_type : '',
                order_area_mixed: element.order.order_area_mixed ? element.order.order_area_mixed : '',
                evaluate: element.order.evaluate ? element.order.evaluate : '',
                cn_region_id: element.order.cn_region_id ? element.order.cn_region_id : '',
                package_type: element.order.package_type ? element.order.package_type : '',
                isreturn: element.order.isreturn ? element.order.isreturn : '',
                withbattery: element.order.withbattery ? element.order.withbattery : '',
                pay_by: element.order.pay_by ? element.order.pay_by : '',
                taxes_number: element.order.taxes_number ? element.order.taxes_number : '',
                is_remote: element.order.is_remote ? element.order.is_remote : '',
                is_pdapickup: element.order.is_pdapickup ? element.order.is_pdapickup : '',
                customer_label: element.order.customer_label ? element.order.customer_label : '',
                vat_fee: element.order.vat_fee ? element.order.vat_fee : '',
                duty_forward: element.order.duty_forward ? element.order.duty_forward : '',
                operation_mode: element.order.operation_mode ? element.order.operation_mode : '',
                signature: element.order.signature ? element.order.signature : '',
                order_item: element.order.order_item ? element.order.order_item : '',
                orders_from: element.order.orders_from ? element.order.orders_from : '',
                operator: element.order.operator ? element.order.operator : '',
                custom_alone: element.order.custom_alone ? element.order.custom_alone : '',
                cod_amount: element.order.cod_amount ? element.order.cod_amount : '',
                sub_process_status: element.order.sub_process_status ? element.order.sub_process_status : '',
                supplier: element.order.supplier ? element.order.supplier : '',
                posun_create_user: element.order.posun_create_user ? element.order.posun_create_user : '',
                is_labelling: element.order.is_labelling ? element.order.is_labelling : '',
                product:product_data,
                ordership:ordership_data
            });

            // console.log(wmsOrder);

            // try {
            //     const orderData = await Wmsordernew.find({orders_code:element.order.orders_code});
            //     if(orderData.length==0){
                    
            //         console.log(element.order_pickup.op_code)
            //         const orderPickData = await OrderPickupnew.find({op_code:element.order_pickup.op_code});
            //         // console.log(orderPickData)
            //         const orderPickmapData = await OrderPickupnew.findOne({"map.orders_code":{ "$in" : [element.order.orders_code]}});
            //         //console.log("orderPickData"+orderPickmapData)
            //         if(orderPickData.length>0 ){
                        
            //             if(!orderPickmapData){
            //                 await OrderPickupnew.updateOne(
            //                     { op_code: orderPickData[0].op_code }, 
            //                     { $push: { map: productmap_data
            //                  } }
            //                  );
            //                  console.log('updated-'+element.order_pickup.op_code);
    
            //             } else {
            //                 console.log('elsepart-'+element.order_pickup.op_code);
            //             }
                       
            //         }else{
            //             console.log('insert');

            //             const orderPickupSave = await orderPickup.save();
            //         }
            //         const saveProduct = await wmsOrder.save();
            //         console.log('success');
            //     }
                
            // } catch (err) {
            //     console.log(err);
            // }


            try {
                const orderData = await Wmsordernew.find({ orders_code: element.order.orders_code });
                if (orderData.length === 0) {
                    // console.log('op_code:', element.order_pickup.op_code);
                    const orderPickData = await OrderPickupnew.find({ op_code: element.order_pickup.op_code });
                    // console.log('OrderPickData:', orderPickData);
                    const orderPickmapData = await OrderPickupnew.findOne({ "map.orders_code": { "$in": [element.order.orders_code] } });
                    // console.log('OrderPickmapData:', orderPickmapData);
        
                    if (orderPickData.length > 0) {
                        if (!orderPickmapData) {
                            await OrderPickupnew.updateOne(
                                { op_code: orderPickData[0].op_code },
                                { $push: { map: productmap_data } }
                            );
                            // console.log('Updated map for op_code:', element.order_pickup.op_code);
                        } else {
                            // console.log('Map already exists for op_code:', element.order_pickup.op_code);
                        }
                    } else {
                        // console.log(jk)
                        // console.log('Inserting new order pickup');
                        const orderPickupSave = await orderPickup.save();
                        // console.log('Order pickup saved:', orderPickupSave);
                    }
                    
                    const saveProduct = await wmsOrder.save();
                    // console.log('WMS order saved:', saveProduct);
                }
                
            } catch (err) {
                // console.log('Error:', err);
            }
        }

    });
    
}

async function findwmsorder(orders_code){
    const orderData = await Wmsordernew.find({orders_code:orders_code});

    if(orderData.length>0){
        return true;
    }else{
        return false;
    }
}

function convertToDateOrNull(dateString) {
    const date = new Date(dateString);
    return isNaN(date) ? null : date;
}

function formatNumber(num, width) {
    const numberString = num.toString();
    return numberString.padStart(width, '0');
}
