// const axios = require("axios");
// const { splitSite } = require("../middlewares");
// const db = require("../models");
// const ExcelTemplate = db.exceltemplate;
// var XlsxTemplate = require('xlsx-template');
// var fs = require('fs');
// var multer = require('multer');
// const path = require('path');
// var libre = require('libreoffice-convert');

// exports.createPDFFromSheetTemplateName = (req, res) => {
// 	console.log('what', __dirname.replace('/controllers', ''));
// 	var inputData = req.query.inputData;
// 	var excelTemplateName = req.query.excelTemplateName;
// 	// var transportationId = req.body.transportationId;d
// 	// var transportationName = req.body.transportationName;
// 	ExcelTemplate.find({name: excelTemplateName}).then((data) => {
// 		try {
// 			if (data && data.length > 0) {
// 				var excelTemplate = data[0] || {};
// 				var templateExcel = `${__dirname.replace('/controllers', '')}${excelTemplate?.file[0]?.url}`;
// 				var outputFileRandom = Math.ceil(Math.random() * 100000000);
// 				var outputFile = `/tmp/${excelTemplate.name}_${outputFileRandom}.xlsx`;
// 				var data = fs.readFileSync(templateExcel, 'binary');
// 				var template = new XlsxTemplate(data);
//       	        var events = JSON.parse(inputData)?.events;
// 				for (var i = 0; i < events.length; i++) {
// 					var pageNumber = i + 2;
// 					var event = events[i];
// 					// template.copySheet(1, pageNumber);
// 					template.copySheet(1, event.client_name);
// 					// console.log('>>> template substitute:', pageNumber, event);
// 					template.substitute(pageNumber, event);
// 				}
// 				template.deleteSheet(1);
// 				var newData = template.generate();
//       	fs.writeFileSync(outputFile, newData, 'binary');
// 				var outputFilename = outputFile || {};
// 				var outputPdfPath = outputFilename.substr(0, outputFilename.length - 5) + '.pdf';
// 				console.log('outputPDF:', outputPdfPath);
// 				var extend = 'pdf';
				
// 				var infile = fs.readFileSync(outputFile);
// 				// Convert it to pdf format with undefined filter (see Libreoffice doc about filter)
// 				try {
// 					libre.convert(infile, extend, undefined, (err, done) => {
// 						if (err) {
// 							console.log('Error converting file:', err);
// 						}
// 						// Here in done you have pdf file which you can save or transfer in another stream
// 						fs.writeFileSync(outputPdfPath, done);
// 						console.log('Conver xlsx to pdf, Done.');
// 						res.download(outputPdfPath, function(error) {
// 							if (error) {
// 								console.log('Error in sending download file ${outputPdfPath}');
// 							}
// 						});
// 					});
// 				} catch (e) {
// 					console.log(e);
// 				}
				
// 			} else {
// 				res.status(404).send({
// 					success: false,
// 					message: "Sheet Template doesn't exist"
// 				})
// 			}
// 		} catch(e) {
// 			console.log(e);
// 		}
// 	}).catch(err => {
// 		res.status(500).send({
// 			success: false,
// 			message: "Error Geting docs"
// 		});
// 	});
// }

// exports.createSheetFromTemplateName = (req, res) => {
//   console.log('what', __dirname.replace('/controllers', ''));
// 	var inputData = req.query.inputData;
// 	console.log('inputData', inputData);
// 	var excelTemplateName = req.query.excelTemplateName;
// 	// var transportationId = req.body.transportationId;
// 	// var transportationName = req.body.transportationName;
// 	ExcelTemplate.find({name: excelTemplateName}).then((data) => {
// 		try {
// 			if (data && data.length > 0) {
// 				var excelTemplate = data[0] || {};
// 				console.log('template', excelTemplate);
// 				var templateExcel = `${__dirname.replace('/controllers', '')}${excelTemplate?.file[0]?.url}`;
// 				var outputFileRandom = Math.ceil(Math.random() * 100000000);
// 				var outputFile = `/tmp/${excelTemplate.name}_${outputFileRandom}.xlsx`;
// 				var data = fs.readFileSync(templateExcel, 'binary');
// 				var template = new XlsxTemplate(data);
//       	        var events = JSON.parse(inputData)?.events;
// 				console.log('events',events)
// 				for (var i = 0; i < events.length; i++) {
// 					var pageNumber = i + 2;
// 					var event = events[i];
// 					// template.copySheet(1, pageNumber);
// 					template.copySheet(1, event.client_name);
// 					// console.log('>>> template substitute:', pageNumber, event);
// 					template.substitute(pageNumber, event);
// 				}
// 				template.deleteSheet(1);
// 				var newData = template.generate();
//       	fs.writeFileSync(outputFile, newData, 'binary');
// 				console.log('test');
// 				res.download(outputFile, (error) => {
// 					if (error) {
// 						console.log('Error in downloading excel')
// 					}
// 				})
// 				console.log('Download finish');
// 			} else {
// 				res.status(404).send({
// 					success: false,
// 					message: "excel Template doesn't exist"
// 				})
// 			}
// 		} catch(e) {
// 			console.log(e);
// 		}
// 	}).catch(err => {
// 		res.status(500).send({
// 			success: false,
// 			message: "Error Geting excels"
// 		});
// 	});
// 	// ids.forEach(id => {
// 	// 	CalendarEvent.findByIdAndUpdate(id, {link_event_uuid: transportationId,
// 	// 		link_event_name: transportationName}, { useFindAndModify: false })
//   //   .then(data => {
//   //     if (!data) {
//   //       res.status(404).send({
//   //         message: `Cannot update Event with id=${id}. Maybe Event was not found!`
//   //       });
//   //     } else res.send({ success: true, message: "Event was updated successfully." });
//   //   })
//   //   .catch(err => {
//   //     res.status(500).send({
//   //       success: false,
//   //       message: "Error updating Event with id=" + id
//   //     });
//   //   });
// 	// }) 
// }



const axios = require("axios");
const { splitSite } = require("../middlewares");
const db = require("../models");
const ExcelTemplate = db.exceltemplate;
const Event = db.calendar_event;
const Customer = db.customer;
const Client = db.client;
const Resource = db.resource;
var XlsxTemplate = require('xlsx-template');
var fs = require('fs');
var multer = require('multer');
const path = require('path');
var libre = require('libreoffice-convert');
const moment = require('moment-timezone');
const BASE_UPLOAD_DIR = "/www/wwwroot/upload/";

const resolveTemplateFilePath = (fileUrl = "") => {
  if (!fileUrl) return "";
  if (fileUrl.startsWith("/files/")) {
    return fileUrl.replace("/files/", BASE_UPLOAD_DIR);
  }
  return `${__dirname.replace("/controllers", "")}${fileUrl}`;
};

exports.createPDFFromSheetTemplateName = (req, res) => {
	console.log('what', __dirname.replace('/controllers', ''));
	var inputData = JSON.parse(req.query.inputData);
	const eventIds = inputData?.eventIds;
	console.log('eventIds',eventIds);
	var excelTemplateName = req.query.excelTemplateName;
  const site = splitSite.findSiteNumber(req);
	console.log('template', excelTemplateName);

	Event.find({ '_id': { $in: eventIds } }).then((events) => {

		Resource.find({}).then((resources) => {
			Customer.find({}).then((customers) => {
				Client.find({}).then((clients) => {
					const docData = {events: []};
					for (const event of events) {
						const customerModels = event?.data?.customer ? customers: clients;
					  const customerId = event?.data?.customer ? event?.data?.customer : event?.target_uuid;
						const customer = customerModels.find((customerModel) => customerModel?.id === customerId || customerModel?._id === customerId || customerModel?.name === event?.data?.client_name );
						let pharmacyInfo = 'This patient has no contracted pharmacy.\n' + 	'Please give the prescription directly to the patient';
						const pharmacy = resources.find(r => (r.id === customer?.pharmacy_id)) || resources.find(r => (r.name?.toLowerCase() === event?.data?.client_pharmacy?.toLowerCase()));
					
						if (pharmacy) {
							pharmacyInfo = `${pharmacy?.name} @ ${pharmacy?.address} \n` + 
							`phone:${pharmacy?.phone} fax:${pharmacy?.fax}`;
						} else {
							if (event?.data?.client_pharmacy) {
								pharmacyInfo = 'Pharmacy: ' + event?.data?.client_pharmacy;
							}
						}
						
						const nameShow = event?.data?.customer ? `${event?.data?.client_name} ${customer?.name_cn}` : `${customer?.name_cn}`
						
						const clientName = (!!customer?.name_cn && !!event?.data?.client_name && nameShow)  || customer?.name_cn || (customer?.lastname && customer?.firstname && `${customer?.lastname}, ${customer?.firstname}`) || event?.data?.client_name;
						
						docData.events.push({
							event_time: moment(event?.start_time).format('MM/DD/YYYY hh:mm A'),
							client_name: event?.data?.client_name, // event.data.client_name,
							client_status: '会员',
							client_dob: event.data.client_birth_date,
							// client_pcp: event.data.client_pcp,
							// client_pharmacy: event.data.client_pharmacy,
							client_seating: event.data.client_seating,
							doctor_name: event.data.resource_name,
							doctor_phone: event.data.resource_phone,
							//doctor_contact: event.data.resource_contact,
							doctor_address: event.data.resource_address?.replaceAll('\n', ' '),
							//title: event.title,
							// description: event.description,
							interpreter: event.data.interpreter,
							fasting: event.data.fasting,
							confirmed: event.data.confirmed,
							new_patient: event.data.new_patient,
							doc_order: event.data.doc_order,
							need_id: event.data.need_id,
							need_med_list: event.data.need_med_list,
							reason: event.data.reason,
							// notes: event.data.notes,
							other: event.data.other,
							pharmacy_info: pharmacyInfo,
							client_preferred_name: customer?.name_cn,
							member_type: customer?.type,
							disability: (customer?.disability === true) ? 'Yes' : (event?.data?.disability || 'No')
						});
						
					}

					// var transportationId = req.body.transportationId;d
					// var transportationName = req.body.transportationName;
					ExcelTemplate.findOne({
            name: excelTemplateName,
            site,
            "file.0": { $exists: true }
          }).sort({ edit_date: -1, updatedAt: -1, createdAt: -1 }).then((excelTemplate) => {
						try {
							if (excelTemplate) {
								var templateExcel = resolveTemplateFilePath(excelTemplate?.file?.[0]?.url);
								if (!templateExcel || !fs.existsSync(templateExcel)) {
									return res.status(404).send({
										success: false,
										message: "Sheet template file not found on server"
									});
								}
								var outputFileRandom = Math.ceil(Math.random() * 100000000);
								var outputFile = `/tmp/${excelTemplate.name}_${outputFileRandom}.xlsx`;
								var data = fs.readFileSync(templateExcel, 'binary');
								var template = new XlsxTemplate(data);
								var eventDatas = docData.events;
								for (var i = 0; i < eventDatas.length; i++) {
									var pageNumber = i + 2;
									var eventData = eventDatas[i];
									// template.copySheet(1, pageNumber);
									template.copySheet(1, eventData.client_name);
									// console.log('>>> template substitute:', pageNumber, event);
									template.substitute(pageNumber, eventData);
								}
								template.deleteSheet(1);
								var newData = template.generate();
								fs.writeFileSync(outputFile, newData, 'binary');
								var outputFilename = outputFile || {};
								var outputPdfPath = outputFilename.substr(0, outputFilename.length - 5) + '.pdf';
								console.log('outputPDF:', outputPdfPath);
								var extend = 'pdf';
								
								var infile = fs.readFileSync(outputFile);
								// Convert it to pdf format with undefined filter (see Libreoffice doc about filter)
								try {
									libre.convert(infile, extend, undefined, (err, done) => {
										if (err) {
											console.log('Error converting file:', err);
											return res.status(500).send({
												success: false,
												message: "Error converting sheet file to PDF"
											});
										}
										// Here in done you have pdf file which you can save or transfer in another stream
										fs.writeFileSync(outputPdfPath, done);
										console.log('Conver xlsx to pdf, Done.');
										res.download(outputPdfPath, function(error) {
											if (error) {
												console.log('Error in sending download file ${outputPdfPath}');
												return res.status(500).send({
													success: false,
													message: "Error downloading generated PDF"
												});
											}
										});
									});
								} catch (e) {
									console.log(e);
									return res.status(500).send({
										success: false,
										message: "Error generating PDF from sheet template"
									});
								}
								
							} else {
								res.status(404).send({
									success: false,
									message: "Sheet Template doesn't exist for this site, or file not uploaded yet"
								})
							}
						} catch(e) {
							console.log(e);
							return res.status(500).send({
								success: false,
								message: "Error processing sheet template"
							});
						}
					}).catch(err => {
						res.status(500).send({
							success: false,
							message: "Error Geting docs"
						});
					});

				})
			})
		});
	})
}

exports.createSheetFromTemplateName = (req, res) => {
	console.log('what', __dirname.replace('/controllers', ''));
	var inputData = JSON.parse(req.query.inputData);
	const eventIds = inputData?.eventIds;
	var excelTemplateName = req.query.excelTemplateName;
  const site = splitSite.findSiteNumber(req);

	Event.find({ '_id': { $in: eventIds } }).then((events) => {
		Resource.find({}).then((resources) => {
			Customer.find({}).then((customers) => {
				Client.find({}).then((clients) => {
					const docData = {events: []};
					for (const event of events) {
						const customerModels = event?.data?.customer ? customers: clients;
					  const customerId = event?.data?.customer ? event?.data?.customer : event?.target_uuid;
						const customer = customerModels.find((customerModel) => customerModel?.id === customerId || customerModel?._id === customerId || customerModel?.name === event?.data?.client_name );
						let pharmacyInfo = 'This patient has no contracted pharmacy.\n' + 	'Please give the prescription directly to the patient';
						const pharmacy = resources.find(r => (r.id === customer?.pharmacy_id)) || resources.find(r => (r.name?.toLowerCase() === event?.data?.client_pharmacy?.toLowerCase()));
			
						if (pharmacy) {
							pharmacyInfo = `${pharmacy?.name} @ ${pharmacy?.address} \n` + 
							`phone:${pharmacy?.phone} fax:${pharmacy?.fax}`;
						} else {
							if (event?.data?.client_pharmacy) {
								pharmacyInfo = 'Pharmacy: ' + event?.data?.client_pharmacy;
							}
						}
						
						const clientName = (customer?.name_cn && event?.data?.client_name && `${event?.data?.client_name} ${customer?.name_cn}`)  || customer?.name_cn || (customer?.lastname && customer?.firstname && `${customer?.lastname}, ${customer?.firstname}`) || event?.data?.client_name;
						
						docData.events.push({
							event_time: moment(event?.start_time).format('MM/DD/YYYY hh:mm A'),
							client_name: event?.data?.client_name, // event.data.client_name,
							client_status: '会员',
							client_dob: event.data.client_birth_date,
							// client_pcp: event.data.client_pcp,
							// client_pharmacy: event.data.client_pharmacy,
							client_seating: event.data.client_seating,
							doctor_name: event.data.resource_name,
							doctor_phone: event.data.resource_phone,
							//doctor_contact: event.data.resource_contact,
							doctor_address: event.data.resource_address?.replaceAll('\n', ' '),
							//title: event.title,
							// description: event.description,
							interpreter: event.data.interpreter,
							fasting: event.data.fasting,
							confirmed: event.data.confirmed,
							new_patient: event.data.new_patient,
							doc_order: event.data.doc_order,
							need_id: event.data.need_id,
							need_med_list: event.data.need_med_list,
							reason: event.data.reason,
							// notes: event.data.notes,
							other: event.data.other,
							pharmacy_info: pharmacyInfo,
							client_preferred_name: customer?.name_cn,
							member_type: customer?.type,
							disability: (customer?.disability === true) ? 'Yes' : (event?.data?.disability || 'No')
						});
					}
					// var transportationId = req.body.transportationId;d
					// var transportationName = req.body.transportationName;
					ExcelTemplate.findOne({
            name: excelTemplateName,
            site,
            "file.0": { $exists: true }
          }).sort({ edit_date: -1, updatedAt: -1, createdAt: -1 }).then((excelTemplate) => {
						try {
							if (excelTemplate) {
								var templateExcel = resolveTemplateFilePath(excelTemplate?.file?.[0]?.url);
								if (!templateExcel || !fs.existsSync(templateExcel)) {
									return res.status(404).send({
										success: false,
										message: "Sheet template file not found on server"
									});
								}
								var outputFileRandom = Math.ceil(Math.random() * 100000000);
								var outputFile = `/tmp/${excelTemplate.name}_${outputFileRandom}.xlsx`;
								var data = fs.readFileSync(templateExcel, 'binary');
								var template = new XlsxTemplate(data);
								var eventDatas = docData.events;
								for (var i = 0; i < eventDatas.length; i++) {
									var pageNumber = i + 2;
									var eventData = eventDatas[i];
									// template.copySheet(1, pageNumber);
									template.copySheet(1, eventData.client_name);
									// console.log('>>> template substitute:', pageNumber, event);
									template.substitute(pageNumber, eventData);
								}
								template.deleteSheet(1);
								var newData = template.generate();
								fs.writeFileSync(outputFile, newData, 'binary');
								console.log('test');
								res.download(outputFile, (error) => {
									if (error) {
										console.log('Error in downloading excel')
										return res.status(500).send({
											success: false,
											message: "Error downloading generated sheet file"
										});
									}
								})
								console.log('Download finish');
							} else {
								res.status(404).send({
									success: false,
									message: "Sheet Template doesn't exist for this site, or file not uploaded yet"
								})
							}
						} catch(e) {
							console.log(e);
							return res.status(500).send({
								success: false,
								message: "Error processing sheet template"
							});
						}
					}).catch(err => {
						res.status(500).send({
							success: false,
							message: "Error Geting docs"
						});
					});

				})
			})
		});
	})
}
