import axios from 'axios';
import { Cookies } from 'react-cookie';
import Router from 'next/router';
import moment from 'moment';
import { nSQL } from "@nano-sql/core";
import fileDownload from 'js-file-download';
import { eachSeries, each } from "async";

import * as actionTypes from '../constants/actionTypes';
import { getCitizenshipTitleByCode } from '../utils/citizenship';
import { questionnaire_template } from '../reducers/initialState';

if(process.browser)
{
	FormData.prototype.appendObject = function(obj, namespace) 
	{
		let keyName;
		for (var key in obj) 
		{
			if (obj.hasOwnProperty(key)) 
			{
				keyName = [namespace, '[', key, ']'].join('');
				this.append(keyName, obj[key]);
			}
		}
	};	
}

export const getQuestionnaire = ({ dispatch, id }) => 
{
	console.log("ACTION", "support", "getAppeals()", `${ process.env.NEXT_PUBLIC_SELF_API_HOST }/api/questionnaire/get`);

	return new Promise((resolve, reject) => 
	{
		axios.get(`${ process.env.NEXT_PUBLIC_SELF_API_HOST }/api/questionnaire/read`, {})
		.then((response_read) => 
		{
			console.log("ACTION", "getQuestionnaire", "/api/questionnaire/read", response_read.data);
			if(response_read.data !== "")
			{
				updateQuestionnaire({ dispatch, questionnaire: response_read.data });
				resolve();
			}
			else
			{
				axios.get(`${ process.env.NEXT_PUBLIC_SELF_API_HOST }/api/questionnaire/get`, {
					params: {
						id
					}
				})
				.then((response) => 
				{
					console.log("ACTION", "questionnaire", "getQuestionnaire()", "response", response.data);

					const founder_persons_template = {
						signatory_id: null, 
						lastname: "", 
						firstname: "", 
						middlename: "", 
						no_middle_name: false, 
						jobtitle: "", 
						telephone: "", 
						email: "", 
						founder_from_list: true, 
						founder_number: 0, 
						founder_part: "", 
						is_beneficial: false, 
						identity_document: 
						{
							doctype: "", 
							seria: "", 
							docnumber: "", 
							issuedate: "", 
							icode: "", 
							issueby: "", 
							issueby_search_dadata: "", 
							placebirth: "", 
							citizenship: {
								title: "", 
								code: "", 
							}, 
							registration_address: {
								title: "", 
								fias_id: "", 
							}
						}
					};

					const questionnaire = JSON.parse(JSON.stringify(global.store.getState().questionnaire));
					if(questionnaire.status === "empty")
					{
						questionnaire.main.title = response.data.title;
						questionnaire.main.inn = response.data.inn;
						questionnaire.main.kpp = response.data.kpp;
						questionnaire.main.telephone = response.data.telephone;
						questionnaire.main.email = response.data.email;
						questionnaire.main.websiteurl = response.data.websiteurl !== null ? response.data.websiteurl : "";
						questionnaire.main.financial_loan = response.data.financial_loan !== null ? response.data.financial_loan : "";
						questionnaire.main.mail_delivery_address_type = response.data.mail_delivery_address_type !== null ? response.data.mail_delivery_address_type : response.data.inn.length > 10 ? 100000001 : 100000000;

						questionnaire.contacts.fact_address = response.data.fact_address !== null ? response.data.fact_address : { name: null, fias_id: null };
						questionnaire.contacts.postal_address = response.data.postal_address !== null ? response.data.postal_address : { name: null, fias_id: null };
						questionnaire.contacts.legal_address = response.data.legal_address !== null ? response.data.legal_address : { name: null, fias_id: null };

						const head_person_identity_document = questionnaire.head_person.identity_document;
						questionnaire.head_person = { ...questionnaire.head_person, ...response.data.head_person };
						if(questionnaire.head_person.identity_document === null)
						{
							questionnaire.head_person.identity_document = head_person_identity_document;
						}
						questionnaire.head_person.identity_document.citizenship = {
							title: response.data.head_person !== null && response.data.head_person.identity_document !== null ? getCitizenshipTitleByCode(response.data.head_person.identity_document.citizenship_code) : null, 
							code: response.data.head_person !== null && response.data.head_person.identity_document !== null ? response.data.head_person.identity_document.citizenship_code : 643, 
						};

						const signatory_person_identity_document = questionnaire.signatory_person.identity_document;
						questionnaire.signatory_person = { ...questionnaire.signatory_person, ...response.data.signatory_person };
						questionnaire.signatory_person.identity_document.citizenship = {
							title: response.data.signatory_person !== null && response.data.signatory_person.identity_document !== null ? getCitizenshipTitleByCode(response.data.signatory_person.identity_document.citizenship_code) : null, 
							code: response.data.signatory_person !== null && response.data.signatory_person.identity_document !== null ? response.data.signatory_person.identity_document.citizenship_code : 643, 
						};
						if(questionnaire.signatory_person.identity_document === null)
						{
							questionnaire.signatory_person.identity_document = signatory_person_identity_document;
						}

						for(let i in response.data.founder_persons)
						{
							questionnaire.founder_persons[i] = response.data.founder_persons[i];
							if(questionnaire.founder_persons[i] !== null)
							{
								if(questionnaire.founder_persons[i].identity_document !== null)
								{
									questionnaire.founder_persons[i].identity_document.citizenship = {
										title: getCitizenshipTitleByCode(response.data.founder_persons[i].identity_document.citizenship_code), 
										code: response.data.founder_persons[i].identity_document.citizenship_code, 
									};
								}
								else
								{
									questionnaire.founder_persons[i].identity_document = { ...founder_persons_template.identity_document };
								}
							}
						}

						for(let i in response.data.client_contacts)
						{
							questionnaire.client_contacts[i] = response.data.client_contacts[i];
							if(questionnaire.client_contacts[i] !== null)
							{
								if(questionnaire.client_contacts[i].identity_document !== null)
								{
									questionnaire.client_contacts[i].identity_document.citizenship = {
										title: getCitizenshipTitleByCode(response.data.client_contacts[i].identity_document.citizenship_code), 
										code: response.data.client_contacts[i].identity_document.citizenship_code, 
									};	
								}
								else
								{
									questionnaire.client_contacts[i].identity_document = { ...founder_persons_template.identity_document };
								}
							}
						}

						const main_params = [
							"board_of_directors", 
							"collective_executive", 
							"high_level", 
							"individual_executive", 
							"other_control", 
							"individual_executive_docdate", 
							"individual_executive_docnum", 
							"individual_executive_inn", 
							"individual_executive_kpp", 
							"individual_executive_oop", 	
						];

						for(let i in main_params)
						{
							if(response.data[main_params[i]] !== null)
							{
								questionnaire.main[main_params[i]] = response.data[main_params[i]];
							}
						}

						if(response.data.is_individual_executive)
						{
							questionnaire.main.is_individual_executive = true;
						}

						//questionnaire.founder_persons = { ...questionnaire.head_person, ...response.data.head_person };

						console.log("questionnairequestionnairequestionnaire FROM JSON", questionnaire);
						updateQuestionnaire({ dispatch, questionnaire })
						.then(() => {})
						.catch(() => {});
						//dispatch({ type: actionTypes.SUPPORT_APPEALS, data: { appeals: { list: response.data.appeals, new: response.data.new, } } });
						resolve();
					}
					else
					{
						resolve();
					}
				})
				.catch((error) => 
				{
					console.log("error");
					console.error(error);

					reject();
				});
			}
		})
		.catch(() => 
		{

		});
	});
}

export const saveQuestionnaire = () => 
{
	return new Promise((resolve, reject) => 
	{
		const questionnaire = JSON.parse(JSON.stringify(global.store.getState().questionnaire));

		axios.post(`${ process.env.NEXT_PUBLIC_SELF_API_HOST }/api/questionnaire/save`, { questionnaire }, {
			withCredentials: true, 
		})
		.then((response) => 
		{
			resolve();
		})
		.catch(() => 
		{
			reject();
		});
	});
}

export const eraseQuestionnaire = () => 
{
	return new Promise((resolve, reject) => 
	{
		axios.post(`${ process.env.NEXT_PUBLIC_SELF_API_HOST }/api/questionnaire/erase`, {}, {
			withCredentials: true, 
		})
		.then((response) => 
		{
			resolve();
		})
		.catch(() => 
		{
			reject();
		});
	});
}

export const updateQuestionnaire = ({ dispatch, questionnaire }) => 
{
	console.log("ACTION", "questionnaireActions", "updateQuestionnaire()", { questionnaire });

	return new Promise((resolve, reject) => 
	{
		dispatch({ type: actionTypes.QUESTIONNAIRE_UPDATE, data: { questionnaire, } });
		/*
			setTimeout(() => {
				console.log("ACTION", "questionnaireActions", "updateQuestionnaire", global.store.getState(), { dispatch: dispatch });
				resolve();
			}, 500);
		*/
	});
}

export const resetQuestionnaire = ({ dispatch, id }) => 
{
	const template = JSON.parse(JSON.stringify(questionnaire_template));
	dispatch({ type: actionTypes.QUESTIONNAIRE_UPDATE, data: { questionnaire: template, } });
	eraseQuestionnaire()
	.then(() => 
	{
		getQuestionnaire({ dispatch, id });
	});
}

export const defaultQuestionnaire = ({ dispatch }) => 
{
	console.log("defaultQuestionnaire");

	const template = JSON.parse(JSON.stringify(questionnaire_template));
	dispatch({ type: actionTypes.QUESTIONNAIRE_UPDATE, data: { questionnaire: template, } });
}


export const uploadAttachmentFile = (file) => 
{
	console.log("ACTION", "questionnaireActions", "uploadAttachmentFile()", { file });

	return new Promise((resolve, reject) => 
	{
		let data = new FormData();
		data.append('file', file);

		axios.post(`${ process.env.NEXT_PUBLIC_SELF_API_HOST }/api/questionnaire/file/upload`, data, 
		{
			headers: {
				"Content-Type": "multipart/form-data; charset=utf-8", 
			}, 
			withCredentials: true, 
		})
		.then(async (response) => 
		{
			console.log("questionnaireActions", "uploadAttachmentFile()", "response.data", response.data);
			resolve(response.data);
		})
		.catch((error) => 
		{
			console.error(error);
			reject();
		});
	});
}

export const uploadSignedFile = (file, id, digital = false) => 
{
	console.log("uploadSignedFile", { file, id, digital });
	return new Promise((resolve, reject) => 
	{
		let data = new FormData();
		data.append('file', file);
		data.append('id', id);
		data.append('digital', digital);

		axios.post(`${ process.env.NEXT_PUBLIC_SELF_API_HOST }/api/questionnaire/send`, data, 
		{
			headers: {
				"Content-Type": "multipart/form-data; charset=utf-8", 
			}, 
			withCredentials: true, 
		})
		.then(async (response) => 
		{
			resolve(response.data);
		})
		.catch((error) => 
		{
			console.error(error);
			reject();
		});
	});
}

export const removeAttachmentFiles = (files) => 
{
	for(let i in files)
	{
		removeAttachmentFile(files[i].id);
	}
}

export const removeAttachmentFile = (id) => 
{
	console.log("ACTION", "questionnaireActions", "removeAttachmentFile()", { id });

	return new Promise((resolve, reject) => 
	{
		axios.delete(`${ process.env.NEXT_PUBLIC_SELF_API_HOST }/api/questionnaire/file/remove`, 
		{
			params: {
				id
			}, 
			withCredentials: true, 
		})
		.then(async (response) => 
		{
			console.log("questionnaireActions", "removeAttachmentFile()", "complete");
			resolve();
		})
		.catch((error) => 
		{
			console.error(error);
			reject();
		});
	});
}

export const downloadQuestionnaire = ({ filename, download = true, base64 = false }) => 
{
	console.log("ACTION", "questionnaireActions", "downloadQuestionnaire()", );

	//{ questionnaire }
	//questionnaire
	return new Promise((resolve, reject) => 
	{
		let cookies = new Cookies();
		let cookies_list = cookies.getAll();
		const { questionnaire } = global.store.getState();

		console.log("questionnaire", questionnaire);
		const { main, contacts, signatory_person, founder_persons, head_person, non_profit, } = questionnaire;
		const payload = { main, contacts, signatory_person, founder_persons, head_person, non_profit, };
		console.log({ payload });

/*		axios.post(`${ process.env.NEXT_PUBLIC_INT_API_HOST }/questionnaire/download`, { questionnaire: payload }, {
			headers: {
				"Authorization": `Bearer ${ cookies_list.jwt }`, 
			}, 
		})
*/

		const options = {
			headers: {
				'Content-Type': 'application/json', 
				'Accept': 'application/pdf'
			}, 
		};

		if(!base64)
		{
			options.responseType = "arraybuffer"; 
		}

		axios.post(`${ process.env.NEXT_PUBLIC_SELF_API_HOST }/api/questionnaire/download`, { questionnaire: payload, filename, base64: download ? false : true }, options)
		.then((response) => 
		{
			if(download)
			{
				console.log("downloadQuestionnaire", "response.data");
				fileDownload(response.data, filename);

				resolve();
			}
			else
			{
				resolve({ file: response.data, filename });
			}

			//dispatch({ type: actionTypes.SUPPORT_APPEALS, data: { appeals: { list: response.data.appeals, new: response.data.new, } } });
		})
		.catch((error) => 
		{
			console.log("error");
			console.error(error);

			reject();
		});

	});
}

export const questionnaireSetSign = ({ dispatch, sign }) => 
{
	dispatch({ type: actionTypes.QUESTIONNAIRE_SET_SIGN, data: { sign } });
}  