import React from "react";
import { eachSeries } from "async";
import { SpinnerCircular } from "spinners-react";

import FileDropzoneDeals from "../../FileDropzoneDeals";

import { attachDealDocument, createQuestionnaire, removeDealDocument, sendDealDocuments, } from "../../../actions";

import Step from "./Step";
import md5 from "md5";

class QuestionnaireForm extends React.Component
{
	constructor(props)
	{
		super(props);
		this.state = {
			loading: false
		}
	}

	_handle_onQuestionnaire = (event) => 
	{
		event.preventDefault();
		const { onQuestionnaire } = this.props;

		onQuestionnaire();
	}

	_handle_onCreateQuestionnaire = (event) => 
	{
		event.preventDefault();
		const { onQuestionnaire, deal_id, last_deal_id } = this.props;

		this.setState({ loading: true, }, () => 
		{
			createQuestionnaire(last_deal_id)
			.then(() => 
			{
				onQuestionnaire();
			});
		});
	}

	render()
	{
		const { loading } = this.state;
		const { questionnaire_status } = this.props;

		switch(questionnaire_status)
		{
			case "need_to_fill":
			{
				return (
					<div className="message alert">
						<p>Требуется обновить данные в анкете</p>
						<button className="button button-blue" onClick={ this._handle_onQuestionnaire }>Актуализировать данные</button>
					</div>
				)
			}

			case "need_to_create":
			{
				return (
					<div className="message alert">
						<p>Требуется предоставить данные в анкете клиента</p>
						<button className="button button-blue" style={{ minWidth: "130px" }} onClick={ this._handle_onCreateQuestionnaire }>
							{ loading ? (
								<SpinnerCircular size={24} thickness={100} speed={100} color="rgba(255, 255, 255, 1)" secondaryColor="rgba(255, 255, 255, 0.5)" style={{ marginTop: "0px" }}/>
							) : 
								"Создать анкету"
							}
						</button>
					</div>
				)
			}

			case "up_to_date":
			{
				return (
					<div className="message ok">
						<p>Вам не требуется актуализация данных анкеты Клиента</p>
					</div>
				)
			}

			default:
			{
				return (
					<div className="message wait">
						<p>Проводится проверка анкеты Вашей организации</p>
					</div>
				)
			}
		}
	}
}

export default class DocumentsForm extends Step
{
	constructor(props)
	{
		super(props);
		this.state = {
			open: false, 
			uploaded: {}, 
			uploading: false, 
			completed: false, 
			loading: true, 
			questionnaire_loading: false, 
		};
		this.status = 102;
	}

	componentDidMount()
	{
		if(this.status === this.props.statuscode_id)
		{
			this.setState({ open: true, });
		}
	}

	componentDidUpdate(prevProps, prevState)
	{
		if(this.props.statuscode_id !== prevProps.statuscode_id)
		{
			if(this.status === this.props.statuscode_id)
			{
				this.setState({ open: true });
			}
			else
			{
				this.setState({ open: false });	
			}
		}

		if(prevProps.uploaded !== this.props.uploaded)
		{
			this.setState({ uploaded: this.props.uploaded, loading: false }, () => 
			{
				const completed = this._checkFilesCompleted();
				this.setState({ completed });
			});
		}
	}

	_handle_onSendFiles = (event) => 
	{
		event.stopPropagation();
		const { dealSelected, onDealsUpdate } = this.props;

		this.props.onFocusDeal();
		setTimeout(() => 
		{
			this.setState({ loading: true }, () => 
			{
				sendDealDocuments({ deal_id: dealSelected })
				.then(() => 
				{
					onDealsUpdate();
				})
				.catch(() => 
				{
	
				});
			});
		}, 100);
	}

	_onSendFileStats = (group, index) => 
	{
		return new Promise((resolve) => 
		{
			const uploaded = { ...this.state.uploaded };
			uploaded[group].files[index].uploaded = true;

			this.setState({ uploaded }, () => 
			{
				resolve();
			});
		})
	}

	_handle_onAddFile = ({ document_id, document_name, files, update }) => 
	{
		const existed_files = { ...this.state.uploaded };

		const group = md5(`${ document_id }_${ document_name }`);
		const document_files = existed_files[ group ] === undefined ? [] : existed_files[ group ].files;

		if(existed_files[ group ] === undefined)
		{
			existed_files[ group ] = {
				files: [], 
			};
		}

		let index = parseInt(existed_files[ group ].files.length, 10);

		for(let nf in files)
		{
			files[nf].document_id = document_id;
			files[nf].group = group;
			files[nf].group_name = document_name;
			files[nf].uploaded = false;
			files[nf].update = update;

			document_files.push(files[nf]);

			existed_files[ group ].files = document_files;
		}

		this.setState({ uploaded: existed_files, uploading: true }, () => 
		{
			const { opp_number } = this.props;

			eachSeries(files, (file, callback) => 
			{
				const payload = {
					deal_id: opp_number, 
					document_id: file.document_id, 
					group: file.group, 
					document_name: file.group_name, 
					filename: file.name, 
					lastModified: file.lastModified, 
					type: file.type, 
					file, 
					update, 
					index, 
				};

				attachDealDocument(payload)
				.then(async () => 
				{
					await this._onSendFileStats(group, index);
					index++;
					callback();
				}, 1000)
			}, () => 
			{
				const completed = this._checkFilesCompleted();
				this.setState({ uploading: false, completed });
			});
		});
	}

	_handle_onDeleteFile = (group, index) => 
	{
		const uploaded = { ...this.state.uploaded };
		const { opp_number } = this.props;

		const list = [ ...uploaded[group].files ];
		list.splice(index, 1);

		uploaded[group].files = list;

		this.setState({ uploaded }, () => 
		{
			const completed = this._checkFilesCompleted();
			this.setState({ completed }, () => 
			{
				removeDealDocument({ deal_id: opp_number, group, index });
			});
		});
	}

	_checkFilesCompleted = () => 
	{
		const { uploaded } = this.state;
		const { documents, questionnaire_status, } = this.props;

		let c = true;
		if(questionnaire_status !== "need_to_fill" && questionnaire_status !== "need_to_create")
		{
			if(documents !== undefined)
			{
				for(let g in documents)
				{
					if(!documents[g].add)
					{
						continue;
					}

					const group = md5(`${ documents[g].doc_id }_${ documents[g].name }`);

					if(uploaded[group] === undefined || uploaded[group].files.length === 0)
					{
						c = false;
						break;
					}
					else
					{
						for(let f in uploaded[group].files)
						{
							if(!uploaded[group].files[f].uploaded)
							{
								c = false;
								break;
							}
						}
					}
				}
			}
		}
		else
		{
			c = false;
		}

		return c;
	}

	render()
	{
		const { index, statuscode_id, dealSelected, documents, questionnaire_status, onQuestionnaire, } = this.props;
		const { open, uploaded, uploading, loading, completed } = this.state;

		console.log("DocumentsForm", "render", { props: this.props });

		return (
			<div className={`${ this.status === statuscode_id ? "current" : statuscode_id > this.status ? "done" : "" }`}>
				<p>№ { dealSelected }</p>
				<span></span>
				<div className="status_body with_footer">
					{ this._renderHeader("Сборка пакета документов") }
					<div className="wrap form" style={{ display: open ? "block" : "none", }}>
						{ loading ? (
							<div style={{ minHeight: 100, display: "flex", justifyContent: "center", alignItems: "center", }}>
								<SpinnerCircular size={ 50 } thickness={ 51 } speed={ 100 } color="rgba(28, 1, 169, 1)" secondaryColor="rgba(236, 239, 244, 1)" />
							</div>
						) : (
							<>
								<div className="block">
									<div className="left">
										<p><b>Анкета клиента:</b></p>
									</div>
									<div className="right">
										<QuestionnaireForm 
											questionnaire_status={ questionnaire_status } 
											onQuestionnaire={ onQuestionnaire } 
											deal_id={ dealSelected } 
											last_deal_id={ this.props.deals.last } 
										/>
									</div>
								</div>
								{ documents === undefined ? (
									<></>
								) : (
									<>
										{ documents.map((document, index) => {
											const group = md5(`${ document.doc_id }_${ document.name }`);
											return (
												<div className="block deal_documents_form_group" key={ index }>
													<div className="left">
														<p><b><span>{ document.name }</span>:</b></p>
													</div>
													<div className="right">
														{ document.add ? (
															<FileDropzoneDeals 
																statuscode_id={ statuscode_id } 
																uploading={ uploading } 
																uploaded={ uploaded[ group ] !== undefined ? uploaded[ group ] : { files: [] } } 
																onAddFile={ (files, update) => { this._handle_onAddFile({ document_id: document.doc_id, document_name: document.name, files, update }) } } 
																onDeleteFile={ this._handle_onDeleteFile } 
																document={ document } 
															/>
														) : (
															<>
															{ document.check === "Документ принят" ? (
																<div className="message ok">
																	<p>{ document.check }</p>
																</div>
															) : (
																<div className="message wait">
																	<p>{ document.check }</p>
																</div>
															) }
															</>
														) }
													</div>
												</div>
											)
										} ) }
									</>
								) }
								{/*}
								<div className="message documents">
									<div className="doc_list">
									</div>
									<p>Документы, отправленные Вами принадлежат другой организации бла бла коммент от менеджера</p>
								</div>
								{*/}
							</>
						) }
					</div>
					{ open && !loading && (
						<div className="status_footer">
							{ this.status === statuscode_id && (
								<div className="buttons">
									<button className="button button button-blue" onClick={ this._handle_onSendFiles } disabled={ completed ? false : true }>Отправить документы</button>
								</div>
							) }
						</div>
					) }
				</div>
			</div>
		)
	}
}