const mongoose = require("mongoose");
const Product = mongoose.model("Products");
const Order = mongoose.model("Orders");
const User = mongoose.model("User");
const OrderPickup = mongoose.model("OrderPickup");
const Wmsorder = mongoose.model("Wmsorder");
const WInward = mongoose.model("WInward");
// const Transaction = mongoose.model("transaction");
const jwt = require("jsonwebtoken");
const bcrypt = require("bcryptjs");
const moment = require('moment-timezone');
const { webAPiValidation } = require("../../handlers/webValidation");
const request = require('request-promise');
var fs = require('fs');
const AWS = require('aws-sdk');
const { result } = require('lodash');
const _ = require("lodash");
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.getWmsOrderUingPostman = async (req,res) => {
	try {
		  var dataWms = req.body.data;
		  //console.log(dataWms);return false;
		  (async () => {
		  for (const key of Object.keys(dataWms)) {
		  //Object.keys(dataWms).forEach(async function(key) {
			var element = dataWms[key];
			//console.log(key);return false;
			  const orderData = await Wmsorder.find({orders_code:key});
			  //console.log(orderData);return false;
			  if(orderData.length==0){
				  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 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,
					  
					  });
				  //console.log(element);return false;
				  const wmsOrder = 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
				  });
				  const saveProduct = await wmsOrder.save();
				  
				  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 = [];
				  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,
	  
					  });
				  }
				  //console.log(element.order_pickup.op_code);
				  const orderPickData = await OrderPickup.find({op_code:element.order_pickup.op_code});
				  //console.log(orderPickData);
				  if(orderPickData.length==0){
					  const orderPickup = 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 orderPickupSave = await orderPickup.save();
				  } else {
					  await OrderPickup.updateOne(
								  { op_code: orderPickData[0].op_code }, 
								  { $push: { map: productmap_data
							   } }
							   );
				  }
			  }
				  
		 }
	  })();
		  return false;
	  } catch (error) {
		  
	  }	
  };
  

exports.getOrdersLegacy = async (req,res) => {
  try {
	    var data = req.body.addProductRequestInfo;
		let orderDetails = [];
		let order_shipping = []; 
		
		data.forEach(async function (order) {
			// console.log(order);return false;
			let buyerEmail = order.customer_email_address;

			var ordersData = await Order.findOne({orderSerial:order.orders_serial}).exec();
			if(ordersData){

				// console.log('update' + order.orders_serial)
				// return false;
				
				let sales_amount = 0;
				if(order.sales_amount!=null){
					
					if(order.sales_amount== '#N/A'){
						sales_amount = 0
					}else{
						sales_amount =order.sales_amount.replace(/\,/g,''); // 1125, but a string, so convert it to number
						sales_amount=parseInt(sales_amount);
					}
					
				}else{
					sales_amount = order.sales_amount
				}
				
				orderDetails = {
					'orderItemId': order.order_item_id,
					'sku': order.istore_product_id,
					'sellerSku': order.istore_product_id,
					'quantity': order.product_quantity,
					'quantityShipped': order.product_quantity,
					'consumerPrice': sales_amount,
					'title': order.pd_name,
					'chinaProcess': order.china_process,
					'productPrice': order.product_price,
					'finalPrice' : order.final_price
				}
				order_shipping = {
					'sm_title': order.sm_title,
					'os_tracking_no': order.os_tracking_no,
					'os_date_deliver': order.os_date_deliver,
					'os_date_add': order.os_date_add,
					'os_status': order.os_status,
					'os_apply_status': order.os_apply_status,
					'os_apply_modi_date': order.os_apply_modi_date,
					'carrier_name': order.carrier_name,
					'shipping_method': order.shipping_method,
					'sku': order.istore_product_id
				}

				// console.log(order.date_purchased)
				
				
				var updateObj = {
					pStatus:order.orders_status_payment,
					oStatus:order.orders_status,
					sStatus:order.orders_status_shipping,
					chinaProcess:order.china_process,
					paidDate:order.paid_time,
					orderDetails:orderDetails,
					order_shipping:order_shipping,
					consumerPrice: sales_amount,
					shippingMethod:order.sm_title,
					orderDate:order.date_purchased,
					shipDate:order.os_date_add,
					cancelDate:order.cancel_time,
					// orderDate:order.date_purchased
				}

				// console.log(order.orders_serial)
				// console.log(ordersData.orderDetails)
				// console.log(updateObj)
				
				await Order.updateOne({orderSerial:order.orders_serial}, {$set: updateObj})

				// return false;
				ordersData.orderDetails.forEach(async (val) => {
					
					let condition = {
						'code': val.sku,
					}
					let resultProducts = await Product.findOne(condition);
					
					// let userData = await User.findOne({_id: mongoose.Types.ObjectId(data.merchantId)});
					
					// let order_status = 0;
					// if(order.os_tracking_no!=null || order.os_tracking_no!=''){
					// 	order_status = 12
					// }
					// console.log(resultProducts);
					
					// if(resultProducts.sp==null){
					// 	console.log(val.sku+'----'+ordersData.orderSerial+'----'+resultProducts.sp)
					// }

					// console.log(val.sku+'----'+ordersData.orderSerial)
					
					const winwardUpdateObj = {
						qty:val.quantity,
						orderUnitPrice:resultProducts.sp,
						OrderTotalPrice:resultProducts.sp*val.quantity,
						// order_status:order_status,
						sellerId: ordersData.merchantId,
						ship_phone:ordersData.shippingPhoneNumber,
						processBy:ordersData.chinaProcess,
						courierName: order.sm_title,
						trackingId: order.os_tracking_no,
						shipDate:order.os_date_add
					}
					// console.log(val.sku+'----'+ordersData.orderSerial+'----'+resultProducts.sp)
					// return false;
					// console.log(ordersData.orderSerial)
					// console.log(winwardUpdateObj)
					// await winward.save();

					// return false;
					await WInward.findOneAndUpdate({s_orderno: ordersData.orderSerial}, {$set: winwardUpdateObj}, { new: true })
					

				})


			}else{
				
				// console.log(order); 
				// console.log(order.orders_id)
				// return false;
				var ordersData1 = await Order.findOne({legacyOrderid:order.orderId}).exec();
				if(ordersData1){
					// console.log('a'+order.orderid)
					return;
				}else{
					
					// console.log(order.orders_serial)
					
					var userData = await User.findOne({email:buyerEmail}).exec();
					var userOrderIdData = await Order.findOne({mkpOrderId:order.amazon_order_id},{}).exec();
					var userProductIdData = await Product.find({code:order.istore_product_id},{}).exec();
					// console.log(order.istore_product_id);//return false;

					if(userData){
						let sales_amount = 0;
						// console.log(order)

						if(order.sales_amount!=null){
							
							if(order.sales_amount== '#N/A'){
								sales_amount = 0
							}else{
								sales_amount =order.sales_amount.replace(/\,/g,''); // 1125, but a string, so convert it to number
								sales_amount=parseInt(sales_amount);
							}
							
						}else{
							sales_amount = order.sales_amount
						}
						// console.log(sales_amount);
						// console.log(userProductIdData.length);
						// console.log(order.orders_serial);
						// return false
						if(userProductIdData.length>0){
							// console.log(order.istore_product_id); //return false;
							orderDetails = {
								'orderItemId': order.order_item_id,
								'sku': order.istore_product_id,
								'sellerSku': order.istore_product_id,
								'quantity': order.product_quantity,
								'quantityShipped': order.product_quantity,
								'consumerPrice': sales_amount,
								'title': order.pd_name,
								'chinaProcess': order.china_process,
								'productPrice': order.product_price,
								'finalPrice' : order.final_price
							}
							order_shipping = {
								'sm_title': order.sm_title,
								'os_tracking_no': order.os_tracking_no,
								'os_date_deliver': order.os_date_deliver,
								'os_date_add': order.os_date_add,
								'os_status': order.os_status,
								'os_apply_status': order.os_apply_status,
								'os_apply_modi_date': order.os_apply_modi_date,
								'carrier_name': order.carrier_name,
								'shipping_method': order.shipping_method,
								'sku': order.istore_product_id
							}
							
							var sp_id = '';
                            if(order.orders_seller_id==1443){
                                sp_id="5ff1fb6cb5a4c4a27a0580dd";
                            }else{
                                sp_id="6717797be42fb644b449b9fa";
                            }
                            let store_domain = '';
                            regexp = /^[0-9\-]+$/i;
                            if(order.amazon_order_id == null || order.amazon_order_id == ""){
								store_domain = 'Shopperr (Dropship)'
							} else {
								if (regexp.test(order.amazon_order_id))
								{
									store_domain = 'Amazon.in'
								}
								else
								{
									store_domain = 'Shopify'
								}
							}
                            
							/*var xx = {
								merchantId: userData._id,
								supplierId: sp_id,
								orderSerial: order.orders_serial,
								storeDomain: 'Amazon.in',
								mkpOrderId: order.amazon_order_id,
								consumerPrice: order.sales_amount,
								orderDetails:orderDetails,
								shippingPhoneNumber:order.delivery_phone,
								recipientName:order.delivery_name,
								shippingAddress1:order.delivery_street_address,
								shippingAddress2:order.delivery_suburb,
								shippingAddress3:order.delivery_address,
								shippingCity:order.delivery_city,
								shippingState:order.delivery_state,
								shippingPostalCode:order.delivery_postcode,
								shippingCountry:'IN',
								pStatus:order.orders_status_payment,
								oStatus:order.orders_status,
								sStatus:order.orders_status_shipping,
								dStatus:order.orders_status_dispute,
								rStatus:order.orders_status_return,
								commentStatus:order.orders_status_comment,
								disputeRole:order.orders_dispute_role,
								chinaProcess:order.china_process,
								orderDate:order.date_purchased,
								paidDate:order.paid_time,
								shipDate:order.os_date_add,
								cancelDate:order.cancel_time,
								shippingMethod:order.sm_title,
								order_shipping:order_shipping
							};
							console.log(xx);return false;*/
							const data = new Order({
								merchantId: userData._id,
								legacyOrderid: order.orderId,
								supplierId: sp_id,
								orderSerial: order.orders_serial,
								storeDomain: store_domain,
								mkpOrderId: order.amazon_order_id,
								consumerPrice: sales_amount,
								orderDetails:orderDetails,
								shippingPhoneNumber:order.delivery_phone,
								recipientName:order.delivery_name,
								shippingAddress1:order.delivery_street_address,
								shippingAddress2:order.delivery_suburb,
								shippingAddress3:order.delivery_address,
								shippingCity:order.delivery_city,
								shippingState:order.delivery_state,
								shippingPostalCode:order.delivery_postcode,
								shippingCountry:'IN',
								pStatus:order.orders_status_payment,
								oStatus:order.orders_status,
								sStatus:order.orders_status_shipping,
								dStatus:order.orders_status_dispute,
								rStatus:order.orders_status_return,
								commentStatus:order.orders_status_comment,
								disputeRole:order.orders_dispute_role,
								chinaProcess:order.china_process,
								china1: order.china1,
								china2: order.china2,
								china3: order.china3,
								orderDate:order.date_purchased,
								paidDate:order.paid_time,
								shipDate:order.os_date_add,
								cancelDate:order.cancel_time,
								shippingMethod:order.sm_title,
								order_shipping:order_shipping
							});
							//   console.log(data);
							const newOrder = data.save().then((data) => {
								
								data.orderDetails.forEach(async (val) => {
									// console.log(val.sku)
									let condition = {
										'code': val.sku,
									}
									let resultProducts = await Product.findOne(condition);
									
									let userData = await User.findOne({_id: mongoose.Types.ObjectId(data.merchantId)});
									
									let order_status = 0;
									if(order.os_tracking_no!=null || order.os_tracking_no!=''){
										order_status = 12
									}

									const winward = new WInward({
										spID: mongoose.Types.ObjectId(resultProducts.supplier_id),
										orderId: mongoose.Types.ObjectId(data._id),
										orderSerial:data.orderSerial,
										s_orderno:data.orderSerial,
										mkpOrderId:data.mkpOrderId,
										code:val.sku,
										qty:val.quantity,
										orderUnitPrice:resultProducts.sp,
										OrderTotalPrice:resultProducts.sp*val.quantity,
										order_status:order_status,
										created_date:new Date(),
										account_name:userData.fName+' '+userData.lName,
										sellerId: data.merchantId,
										ship_phone:data.shippingPhoneNumber,
										processBy:data.chinaProcess,
										orderDate:data.orderDate,
										courierName: order.sm_title,
										trackingId: order.os_tracking_no,
										shipDate:order.os_date_add
									})
									// console.log(winward)
									await winward.save();
									
									if(data.chinaProcess==0 || data.chinaProcess==2 ){
										
										let updatedInQty = 0;
										if(resultProducts.stock.in_qty){
											updatedInQty = resultProducts.stock.in_qty-val.quantity
										}else{
											updatedInQty = val.quantity
										}

										let obj = {
											'stock.in_qty': updatedInQty,
										}
										// console.log(resultProducts._id)
										let resultProducts1 = await Product.updateOne({"_id": mongoose.Types.ObjectId(resultProducts._id)}, { $set: obj }, { upsert: false });
										
									}

									if(data.chinaProcess==3){
										let updatedBlkQty = 0;
										if(resultProducts.stock.blk_qty){
											updatedBlkQty = resultProducts.stock.blk_qty-val.quantity
										}else{
											updatedBlkQty = val.quantity
										}

										let obj = {
											'stock.blk_qty': updatedBlkQty,
										}
										// console.log(resultProducts._id)
										let resultProducts1 = await Product.updateOne({"_id": mongoose.Types.ObjectId(resultProducts._id)}, { $set: obj }, { upsert: false });
										
									}

									if(data.chinaProcess==1){
										let updatedCnQty = 0;
										if(resultProducts.stock.cn_qty){
											updatedCnQty = resultProducts.stock.cn_qty-val.quantity
										}else{
											updatedCnQty = val.quantity
										}
 
										let obj = {
											'stock.cn_qty': updatedCnQty,
										}
										// console.log(resultProducts._id)
										let resultProducts1 = await Product.updateOne({"_id": mongoose.Types.ObjectId(resultProducts._id)}, { $set: obj }, { upsert: false });
										
									}

								})

							}).catch((e) => {
								// console.log(e);
								
							})


							
						}else{
							// console.log(userProductIdData)
							// console.log(order.istore_product_id)
							// console.log(order.orderSerial)
						}
					}else{
						// console.log(buyerEmail)
						// return false
					}
				}

				// return false;
				
				

				

			}
		});
		return true;
	} catch (error) {
		// console.log(error)
	}
};

exports.getCffWmsOrdersLegacy = async (req,res) => {
  try {
	    var dataWms = req.body.data;
	    Object.keys(dataWms).forEach(async function(key) {
		  var element = dataWms[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 = 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 = 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);

			// return false;

            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);
            }
        }
		  
		});
	   // console.log(dataWms.WSTK0124081039732);
		return false;
	} catch (error) {
		
	}	
};

exports.getCffWmsLegacy = async (req,res) => {
  try {
	    var dataOp = req.body.pickup;
	    var dataPickupMap = req.body.pickupMap;
	    let op_status = 0;
		let opm_status = 0;
		if(dataOp.op_orders_type==0){
			op_status = 4;
			opm_status = 0;
		}
		var productmap_data = [];
	    dataPickupMap.forEach(async function (item1) {
			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: dataOp.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,
			});
	   });
	   
	   
	    const orderPickup = new OrderPickup({
			op_code: dataOp.op_code,
			op_creater_id: dataOp.op_creater_id,
			op_order_cnt: dataOp.op_order_cnt,
			op_product_cnt: dataOp.op_product_cnt,
			op_sku_cnt: dataOp.op_sku_cnt,
			op_status: dataOp.op_status, 
			op_orders_type: dataOp.op_orders_type,
			op_note: dataOp.op_note,
			op_create_date: dataOp.op_create_date,
			op_last_update: convertToDateOrNull(dataOp.op_last_update),
			warehouse_id: dataOp.warehouse_id,
			op_is_import: dataOp.op_is_import,
			op_is_create_labels: dataOp.op_is_create_labels,
			back_id: dataOp.back_id,
			pickup_user_id: dataOp.pickup_user_id,
			op_start_time: convertToDateOrNull(dataOp.op_start_time),
			op_end_time: convertToDateOrNull(dataOp.op_end_time),
			pickup_finish_time: convertToDateOrNull(dataOp.pickup_finish_time),
			pick_type: dataOp.pick_type,
			op_ref_code: dataOp.op_ref_code,
			op_order_qty: dataOp.op_order_qty,
			op_dispatch_date: convertToDateOrNull(dataOp.op_dispatch_date),
			op_cancel_date: convertToDateOrNull(dataOp.op_cancel_date),
			op_rto_date: convertToDateOrNull(dataOp.op_rto_date),
			op_return_date: convertToDateOrNull(dataOp.op_return_date),
			op_ticketed_date: convertToDateOrNull(dataOp.op_ticketed_date),
			map: productmap_data,
			 
		});
		const orderPickData = await OrderPickup.find({op_code:dataOp.op_code});
	    if(orderPickData.length>0 ){
			console.log('exist');
			res.send('exist');
		}else{
			console.log('insert');
			const orderPickupSave = await orderPickup.save();
			res.send('insert');
		}
		
	} catch (error) {
		
	}	
};

exports.getCffWmsLegacyOrder = async (req,res) => {
  try {
	    var dataOp = req.body.orders;
	    var dataShip1 = req.body.orderShip;
	    var dataProduct = req.body.orderProduct;
	    
		const product_data = [];
	    dataProduct.forEach(async function (item) {
			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 ordership_data = [];
	    dataShip1.forEach(async function (dataShip) {
		ordership_data.push({
			orders_code: dataShip.orders_code,
			tracking_number: dataShip.tracking_number,
			ref_tracking_number: dataShip.ref_tracking_number,
			transfer_number: dataShip.transfer_number,
			combine_code: dataShip.combine_code,
			ae_tracking_number: dataShip.ae_tracking_number,
			warehouse_id: dataShip.warehouse_id,
			carrier_code: dataShip.carrier_code,
			os_status: dataShip.os_status,
			os_qty: dataShip.os_qty,
			os_estimate_weight: dataShip.os_estimate_weight,
			os_weight: dataShip.os_weight,
			os_vol_weight: dataShip.os_vol_weight,
			os_weight_rate: dataShip.os_weight_rate,
			os_length: dataShip.os_length,
			os_width: dataShip.os_width,
			os_height: dataShip.os_height,
			os_declared_value: dataShip.os_declared_value,
			os_guarantee_value: dataShip.os_guarantee_value,
			os_cost_fee: dataShip.os_cost_fee,
			os_deal_fee: dataShip.os_deal_fee,
			os_reg_fee: dataShip.os_reg_fee,
			os_addons_fee: dataShip.os_addons_fee,
			os_other_fee: dataShip.os_other_fee,
			os_shipping_fee: dataShip.os_shipping_fee,
			os_insurance_fee: dataShip.os_insurance_fee,
			os_vat_fee: dataShip.os_vat_fee,
			os_shipping_fee_estimate: dataShip.os_shipping_fee_estimate,
			os_fee_area: dataShip.os_fee_area,
			currency_code: dataShip.currency_code,
			currency_rate: dataShip.currency_rate,
			os_fee_deduction_date: dataShip.os_fee_deduction_date,
			os_fee_deduction_time: dataShip.os_fee_deduction_time,
			os_send_date: dataShip.os_send_date,
			exist_label: dataShip.exist_label,
			os_create_date: dataShip.os_create_date,
			os_last_update: dataShip.os_last_update,
			os_image: dataShip.os_image,
			delivered_date: dataShip.delivered_date,
			change_number: dataShip.change_number,
		});
		});
		
	    const wmsOrder = new Wmsorder({
			orders_code: dataOp.orders_code ? dataOp.orders_code : '',
			customer_id:  dataOp.customer_id ? dataOp.customer_id : '',
			warehouse_id:  dataOp.warehouse_id ? dataOp.warehouse_id : '',
			consignee_first_name:  dataOp.consignee_first_name ? dataOp.consignee_first_name : '',
			consignee_last_name:  dataOp.consignee_last_name ? dataOp.consignee_last_name : '',
			consignee_company: dataOp.consignee_company ? dataOp.consignee_company : '',
			consignee_country_id: dataOp.consignee_country_id ? dataOp.consignee_country_id : '',
			consignee_zip: dataOp.consignee_zip ? dataOp.consignee_zip : '',
			consignee_region: dataOp.consignee_region ? dataOp.consignee_region : '',
			consignee_city: dataOp.consignee_city ? dataOp.consignee_city : '',
			consignee_address1: dataOp.consignee_address1 ? dataOp.consignee_address1 : '',
			consignee_address2: dataOp.consignee_address2 ? dataOp.consignee_address2 : '',
			doorplate: dataOp.doorplate ? dataOp.doorplate : '',
			consignee_phone: dataOp.consignee_phone ? dataOp.consignee_phone : '',
			consignee_email: dataOp.consignee_email ? dataOp.consignee_email : '',
			shipping_method: dataOp.shipping_method ? dataOp.shipping_method : '',
			sub_shipping_method: dataOp.sub_shipping_method ? dataOp.sub_shipping_method : '',
			ship_area: dataOp.ship_area ? dataOp.ship_area : '',
			parcel_declared_value: dataOp.parcel_declared_value ? dataOp.parcel_declared_value : '',
			parcel_contents: dataOp.parcel_contents ? dataOp.parcel_contents : '',
			parcel_quantity: dataOp.parcel_quantity ? dataOp.parcel_quantity : '',
			order_attribute: dataOp.order_attribute ? dataOp.order_attribute : '',
			orders_status: dataOp.orders_status ? dataOp.orders_status : '',
			process_status: dataOp.process_status ? dataOp.process_status : '',
			problem_status: dataOp.problem_status ? dataOp.problem_status : '',
			import_status: dataOp.import_status ? dataOp.import_status : '',
			underreview_status: dataOp.underreview_status ? dataOp.underreview_status : '',
			shipping_fee_estimate: dataOp.shipping_fee_estimate ? dataOp.shipping_fee_estimate : '',
			shipping_fee: dataOp.shipping_fee ? dataOp.shipping_fee : '',
			currency: dataOp.currency ? dataOp.currency : '',
			add_time: dataOp.add_time ? dataOp.add_time : '',
			submit_time: dataOp.submit_time ? dataOp.submit_time : '',
			package_time: dataOp.package_time ? dataOp.package_time : '',
			ship_date: dataOp.ship_date ? dataOp.ship_date : '',
			send_date: convertToDateOrNull(dataOp.send_date),
			delivered_date: convertToDateOrNull(dataOp.delivered_date),
			last_modified_time: convertToDateOrNull(dataOp.last_modified_time),
			order_stop_date: convertToDateOrNull(dataOp.order_stop_date),
			import_time: convertToDateOrNull(dataOp.import_time),
			print_time: convertToDateOrNull(dataOp.print_time),
			order_print_id: dataOp.order_print_id ? dataOp.order_print_id : '',
			orders_print_type: dataOp.orders_print_type ? dataOp.orders_print_type : '',
			customer_order_code: dataOp.customer_order_code ? dataOp.customer_order_code : '',
			init_pickup_user_id: dataOp.init_pickup_user_id ? dataOp.init_pickup_user_id : '',
			pickup_user_id: dataOp.pickup_user_id ? dataOp.pickup_user_id : '',
			package_user_id: dataOp.package_user_id ? dataOp.package_user_id : '',
			outbound_user_id: dataOp.outbound_user_id ? dataOp.outbound_user_id : '',
			sorting_user_id: dataOp.sorting_user_id ? dataOp.sorting_user_id : '',
			remark: dataOp.remark ? dataOp.remark : '',
			is_special_order: dataOp.is_special_order ? dataOp.is_special_order : '',
			order_print_area: dataOp.order_print_area ? dataOp.order_print_area : '',
			order_type: dataOp.order_type ? dataOp.order_type : '',
			order_area_mixed: dataOp.order_area_mixed ? dataOp.order_area_mixed : '',
			evaluate: dataOp.evaluate ? dataOp.evaluate : '',
			cn_region_id: dataOp.cn_region_id ? dataOp.cn_region_id : '',
			package_type: dataOp.package_type ? dataOp.package_type : '',
			isreturn: dataOp.isreturn ? dataOp.isreturn : '',
			withbattery: dataOp.withbattery ? dataOp.withbattery : '',
			pay_by: dataOp.pay_by ? dataOp.pay_by : '',
			taxes_number: dataOp.taxes_number ? dataOp.taxes_number : '',
			is_remote: dataOp.is_remote ? dataOp.is_remote : '',
			is_pdapickup: dataOp.is_pdapickup ? dataOp.is_pdapickup : '',
			customer_label: dataOp.customer_label ? dataOp.customer_label : '',
			vat_fee: dataOp.vat_fee ? dataOp.vat_fee : '',
			duty_forward: dataOp.duty_forward ? dataOp.duty_forward : '',
			operation_mode: dataOp.operation_mode ? dataOp.operation_mode : '',
			signature: dataOp.signature ? dataOp.signature : '',
			order_item: dataOp.order_item ? dataOp.order_item : '',
			orders_from: dataOp.orders_from ? dataOp.orders_from : '',
			operator: dataOp.operator ? dataOp.operator : '',
			custom_alone: dataOp.custom_alone ? dataOp.custom_alone : '',
			cod_amount: dataOp.cod_amount ? dataOp.cod_amount : '',
			sub_process_status: dataOp.sub_process_status ? dataOp.sub_process_status : '',
			supplier: dataOp.supplier ? dataOp.supplier : '',
			posun_create_user: dataOp.posun_create_user ? dataOp.posun_create_user : '',
			is_labelling: dataOp.is_labelling ? dataOp.is_labelling : '',
			product:product_data,
			ordership:ordership_data
		});
		const orderData = await Wmsorder.find({orders_code:dataOp.orders_code});
	    if(orderData.length>0 ){
			console.log('exist');
			res.send('exist');
		}else{
			console.log('success');
			const saveProduct = await wmsOrder.save();
			res.send('success');
		}
		
	} catch (error) {
		
	}	
};

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