import React from "react";
import { connect } from "react-redux";
import moment from "moment";
import { SpinnerCircular } from "spinners-react";
import { concatSeries } from "async";
import { eachSeries } from 'async';
import Select from 'react-select';
import Dropzone from 'react-dropzone';

import { signCheckCreatePrintForm, signGetGUIDEntity, signGetWMDoc, docEDOStatus, getFile, signGetFileContractProject, signUploadPaperDocument, signCheckCancelDocument, signCancelDocument } from "../../../actions";

export default class DealContractsSignPaper extends React.Component 
{
	constructor(props) 
	{
		super(props)
		this.state = {
			finished: false, 
			loading: false, 
			disabled: false, 
			documents: [], 
			operator_selected: {}, 
			statuses: {}, 
			step: 0, 
		}
	}

	componentDidMount()
	{
		const docs = [];
		for(let i in this.props.documents)
		{
			docs.push({ ...this.props.documents[i], ...{ index: i, loading: true, ready: false, upload: false, } });
		}

		this.setState({ documents: docs, loading: true }, () => 
		{
			this._sign();
		});
	}

	_updateDocs = (id, update) => 
	{
		return new Promise((resolve) => 
		{
			const docs = [ ...this.state.documents ];
			docs[ id ] = { ...docs[id], ...update };

			this.setState({ documents: docs }, () => 
			{
				resolve();
			});
		});
	}

	_checkDocumentsCompleted = () => 
	{
		const { documents } = this.state;
		let completed = true;

		for(let i in documents)
		{
			if(documents[i].error)
			{
				continue;
			}
			else
			{
				if(!documents[i].completed)
				{
					completed = false;
					break;
				}
			}
		}

		return completed;
	}

	_sign = () => 
	{
		const documents = [ ...this.state.documents ];

		this.setState({ loading: true }, () => 
		{
			eachSeries(documents, async (document, callback) => 
			{
				if(document.completed)
				{
					callback();
				}
				if(document.uploading)
				{
					callback();
				}
				else if(document.ready)
				{
					callback();
				}
				else
				{
					const create_print_form_result = await signCheckCreatePrintForm({ contract_number: document.id, sign_type: "Paper" });
					const docs = { status: create_print_form_result.status };

					if(create_print_form_result.status !== "success")
					{
						docs.loading = false;
						docs.error = true;
						docs.ready = true;
						docs.message = create_print_form_result.message;
					}

					await this._updateDocs(document.index, docs);

					if(create_print_form_result.status === "success")
					{
						const get_guid_entity_result = await signGetGUIDEntity({
							contract_number: document.id, 
						});

						const wmdoc_result = await signGetWMDoc({ 
							entity_name: "evo_contract", 
							entity_id: get_guid_entity_result.entityid, 
							sign_type: "Paper", 
							evo_id: "60", 
							code: "Leas_Contract", 
						});

						await this._updateDocs(document.index, {
							entity_id: get_guid_entity_result.entityid, 
							ready: true, 
							loading: false, 
						});

						callback();
					}
					else
					{
						await this._updateDocs(document.index, { 
							loading: false, 
							error: true, 
							ready: true, 
							message: create_print_form_result.message !== undefined && create_print_form_result.message !== null ? create_print_form_result.message : "Возникла ошибка при создании документа для подписания.", 
						});
						callback();
					}
				}
			}, () => 
			{
				if(this._checkDocumentsCompleted())
				{
					this.setState({ loading: false, finished: true, });
				}
				else
				{
					this.setState({ loading: false, finished: false, });
				}
			});
		});
	}

	_handle_onFormSubmit = (event) => 
	{
		event.preventDefault();

		const { onFinish } = this.props;
		const { finished } = this.state;

		if(finished)
		{
			onFinish();
		}
		else
		{
			this._sign();
		}
	}

	_handle_onDownloadFile = (index) => 
	{
		const { documents } = this.state;

		this.setState({ loading: true, disabled: true, }, async () => 
		{
			await this._updateDocs(index, { loading: true });

			const link_result = await signGetFileContractProject({
				contract_number: documents[index].id, 
			});

			await getFile({ id: link_result.url, filename: `ЛК ЭВОЛЮЦИЯ ${ documents[index].id }.${ link_result.extension }` });

			await this._updateDocs(index, { loading: false, disabled: false, ready: false, uploading: true, });
			this.setState({ loading: false, disabled: false, });
		});
	}

	_handle_onCancelFile = async (index) => 
	{
		const { onCancel } = this.props;
		const { documents } = this.state;
		await this._updateDocs(index, { loading: true });

		this.setState({ loading: true, disabled: true }, async () => 
		{
			const check_result = await signCheckCancelDocument({ contract_number: documents[index].id, doc_type_id: "60" });
			if(check_result.status === "success")
			{
				await signCancelDocument({ contract_number: documents[index].id, doc_type_id: "60" });
				const docs = [ ...this.state.documents ];
				docs.splice(index, 1);

				if(docs.length > 0)
				{
					this.setState({ documents: docs, loading: false, disabled: false, });
				}
				else
				{
					onCancel(true);
				}
			}
			else
			{
				await this._updateDocs(index, { 
					loading: false, 
					error: true, 
					message: check_result.message !== undefined && check_result.message !== null ? check_result.message : "Возникла ошибка при отмене подписания", 
				});
			}
		});
	}

	_handle_onCancel = () => 
	{
		const { onCancel } = this.props;
		const { documents } = this.state;

		var clean = false;
		if(documents.length === 0)
		{
			clean = true;
		}

		onCancel(clean);
	}

	_handle_onUploadFile = async (files, index) => 
	{
		const { documents } = this.state;
		const { deal_id } = this.props;

		await this._updateDocs(index, { loading: true });

		this.setState({ loading: true, disabled: true }, async () => 
		{
			await signUploadPaperDocument(documents[index].id, deal_id, files);
			await this._updateDocs(index, { loading: false, uploading: false, completed: true, });

			if(this._checkDocumentsCompleted())
			{
				this.setState({ loading: false, disabled: false, finished: true, });
			}
			else
			{
				this.setState({ loading: false, disabled: false, finished: false, });
			}
		});
	}

	_handle_onCancelUpload = async (index) => 
	{
		await this._updateDocs(index, { ready: true, uploading: false, });
	}

	render()
	{
		const { documents, loading, disabled, finished, } = this.state;

		return (
			<div className="edo_detail">
				<div className="docs_list medium-icon">
					<p className="list_title">Подписание в бумажном виде</p>
				</div>
				<div className="docs_list medium-icon edo_sign_documents_list">
					{ documents.map((document, index) => 
					{
						return (
							<div className="edo_sign_documents_document" key={ index }>
								<div className="edo_sign_documents_document_left">
									<p className="doc_name i-pdf extension edo_sign_document" data-format={ document.extension }>
										{ document.name } от { moment(document.date).format("DD.MM.YYYY") }
										{ document.type !== undefined && (<span>{ document.type }</span>) }
									</p>
								</div>
								<div className="edo_sign_documents_document_right">
									{ document.loading ? (
										<>
											{ loading && (
												<SpinnerCircular size={ 22 } thickness={ 100 } speed={ 100 } color="rgba(236, 239, 244, 1)" secondaryColor="rgba(28, 1, 169, 1)" />
											) }
										</>
									) : (
										<>
											{ document.error ? (
												<>
													<div className="status_icon error"></div>
													<i>{ document.message !== undefined && document.message !== null ? document.message : "" }</i>
												</>
											) : (
												<>
													{ document.ready && (
														<>
															<div className="status_icon success"></div>
															{ document.entity_id !== undefined && (
																<>	
																	<button className="button" disabled={ disabled } onClick={ () => this._handle_onDownloadFile(index) }>Посмотреть проект договора</button>	
																	<button className="button" disabled={ disabled } onClick={ () => this._handle_onCancelFile(index) }>Отменить подписание</button>
																</>
															) }
														</>
													) }
													{ document.uploading && (
														<>
															<div className="status_icon await"></div>
															{ document.entity_id !== undefined && (
																<>
																	<Dropzone onDrop={ (acceptedFiles) => this._handle_onUploadFile(acceptedFiles, index) } maxFiles={ 10 }>
																	{ ({getRootProps, getInputProps}) => (
																		<div { ...getRootProps() }>
																			<button className="button" disabled={ disabled }>Загрузить скан подписанного документа</button>
																			<input { ...getInputProps() } />
																		</div>
																	) }
																	</Dropzone>
																	<button className="button" disabled={ disabled } onClick={ () => this._handle_onCancelUpload(index) }>Отменить загрузку</button>
																</>
															) }
														</>
													) }
													{ document.completed && (
														<>
															<div className="status_icon success"></div>
															<div className="status_title">
																<i>Договор отправлен вашему менеджеру "ЛК Эволюция"</i>
															</div>
														</>
													) }
												</>
											) }
										</>
									) }
								</div>
							</div>
						) 
					} ) }
				</div>
				<form ref={ this.ref_form } onSubmit={ this._handle_onFormSubmit } onKeyDown={(e) => {if (e.key === 'Enter') e.preventDefault() }}>
					<div className="form_field" style={{ display: "flex", justifyContent: "space-between" }}>
						<button className="button button-blue" onClick={ this._handle_onCancel }>Отменить</button>
						<button type="submit" className="button button-blue" disabled={ finished ? false : true }>
							{ loading ? (
								<SpinnerCircular size={24} thickness={100} speed={100} color="rgba(255, 255, 255, 1)" secondaryColor="rgba(255, 255, 255, 0.5)" style={{ marginTop: "4px" }}/>
							) : "Продолжить" }
						</button>
					</div>
				</form>
			</div>
		)
	}
}