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 { createEDOProject, signCheckCreatePrintForm, signCheckPowerAttorneyClient, signDownloadFile, signGetGUIDEntity, signGetPowerAttorneyClient, signGetWMDoc, docEDOSign, docEDOStatus, docEDOConnect, getFile, signGetFileContractProject, signCheckCancelDocument, signContractGraphicChange, signCancelDocument } from "../../../../../../../actions";
//import { getDeals, getDealOffers, getDealDocuments, getDealContracts } from "../../actions";

class SignEDO extends React.Component 
{
	constructor(props) 
	{
		super(props)
		this.state = {
			finished: false, 
			operators: null, 
			edo_message: null, 
			loading: false, 
			disabled: false, 
			documents: [], 
			operator_selected: {}, 
			statuses: {}, 
			error: false, 
			message: undefined, 
			ready: false, 
			attorney: false, 
			attorneys: [], 
			attorney_selected: undefined, 
			step: 0, 
			graphic_change_comment: undefined, 
			edoid: undefined, 
		}
	}

	static getDerivedStateFromProps(nextProps, prevState) 
	{
		console.log("SignEDO", "getDerivedStateFromProps", { nextProps });
		return {
			operators: nextProps.operators, 
			edo_message: nextProps.edo_message, 
		}
	}

	componentDidMount()
	{
		console.log("SignEDO", { props: this.props });
		/*
			const check_result = await signCheckCreatePrintForm({ addcontract_number: calculation_id, sign_type: "EDO" });
			if(check_result.status === "success")
			{
				const get_guid_entity_result = await signGetGUIDEntity({ addcontract_number: calculation_id });

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

		if(this.state.operator_selected.box_id === undefined)
		{
			this.setState({ operator_selected: this.state.operators !== null && this.state.operators[0] !== undefined ? this.state.operators[0] : {} });
		}

		/*
		setTimeout(() => 
		{
			this.setState({ loading: false })
		}, 5000);
		*/
	}

	_update = (update) => 
	{
		return new Promise((resolve) => 
		{
			this.setState(update, () => 
			{
				resolve();
			});
		});
	}

	_sign = async () => 
	{
		const { calculation_id, contract_number, signer, onFinished } = this.props;
		const { operator_selected, error, step, completed, signing, ready, attorney, attorney_selected, } = this.state;

		console.log("_handle_onFormSubmit");
		console.log({ operator_selected });

		await this._update({ loading: true, disabled: true, });

		if(!error)
		{
			if(attorney && attorney_selected !== undefined)
			{
				this._finalizeSign({
					power_attorney: attorney_selected.value, 
					power_attorney_number: attorney_selected.label, 
				});
			}
			else
			{
				const create_print_form_result = await signCheckCreatePrintForm({ addcontract_number: calculation_id, sign_type: "EDO" });
				console.log({ create_print_form_result });

				if(create_print_form_result.status === "success")
				{
					const get_guid_entity_result = await signGetGUIDEntity({
						addcontract_number: calculation_id, 
					});

					console.log("\n\nENTITY !!!!!!!!!!\n\n");
					console.log({ get_guid_entity_result });

					const graphic_change_comment = await signContractGraphicChange({
						contract_number: contract_number, 
						addcontract_number: calculation_id, 
						signatoryid: signer.signatoryid, 
						type: 1, 
					});

					await signCancelDocument({ addcontract_number: calculation_id, doc_type_id: "64" });

					await this._update({ graphic_change_comment, entity_id: get_guid_entity_result.entityid });

					const check_attorney_client_result = await signCheckPowerAttorneyClient({ addcontract_number: calculation_id, contactid: signer.signatoryid, })
					console.log({ check_attorney_client_result });

					await this._update({ attorney: check_attorney_client_result.power_attorney_required, });

					if(check_attorney_client_result.power_attorney_required)
					{
						const get_attorney_client_result = await signGetPowerAttorneyClient({ addcontract_number: calculation_id, contactid: signer.signatoryid, });
						console.log({ get_attorney_client_result });

						if(get_attorney_client_result === null)
						{
							await this._update({ loading: false, disabled: false, error: true, ready: false, message: "Возникла ошибка при создании документа для подписания." });
						}
						else
						{
							if(get_attorney_client_result.length === null)
							{
								await this._update({ loading: false, disabled: false, error: true, ready: false, message: "Не обнаружена доверенность на подписанта. Для продолжения подписания обратитесь к своему персональному менеджеру" });
							}
							else
							{
								const attorneys = [];
								for(let i in get_attorney_client_result)
								{
									attorneys.push({
										value: get_attorney_client_result[i].power_attorney, 
										label: get_attorney_client_result[i].power_attorney_number, 
									});
								}

								await this._update({ loading: false, disabled: true, error: false, attorneys, attorney_selected: undefined });
							}
						}
					}
					else
					{
						this._finalizeSign({});
					}
				}
				else
				{
					this.setState({ 
						loading: false, 
						error: true, 
						disabled: false, 
						message: create_print_form_result.message !== undefined && create_print_form_result.message !== null ? create_print_form_result.message : "Возникла ошибка при создании документа для подписания.", 
					});
				}
			}
		}
	}

	_finalizeSign = async (attorney) => 
	{
		await this._update({ ready: true, });

		const { calculation_id, onFinished } = this.props;
		const { operator_selected, } = this.state;

		const create_edo_project_result = await createEDOProject({ ...{
			addcontract_number: calculation_id, 
			edo_box: operator_selected.edo_box, 
		}, ...attorney });

		if(create_edo_project_result.edoid !== undefined)
		{
			await this._update({ edoid: create_edo_project_result.edoid, });

			const get_guid_entity_result = await signGetGUIDEntity({
				addcontract_number: calculation_id, 
			});

			const wmdoc_result = await signGetWMDoc({ 
				entity_name: "evo_addcontract", 
				entity_id: get_guid_entity_result.entityid, 
				sign_type: "EDO", 
				evo_id: "156", 
				code: "AddcontractSale", 
			});

			const connect_result = await docEDOConnect({ addcontract_number: calculation_id });
			const sign_result = await docEDOSign({ edoid: this.state.edoid, });

			onFinished(this.state.graphic_change_comment);
		}
		else
		{
			this.setState({ 
				loading: false, 
				error: true, 
				disabled: false, 
				message: create_edo_project_result.message !== undefined && create_edo_project_result.message !== null ? create_edo_project_result.message : "Возникла ошибка при создании документа для подписания.", 
			});		
		}
	}

	_handle_onGoToEDOInvites = () => 
	{
		const eventLogin = new CustomEvent("_move", { detail: { path: "/settings/digital" } });
		window.dispatchEvent(eventLogin);
	}

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

		const { onFinish, onCancel } = this.props;
		const { operators, operator_selected, step, finished, error } = this.state;

		console.log("_handle_onFormSubmit");
		console.log({ operator_selected });

		if(operators !== null && operators.length === 0)
		{
			this._handle_onGoToEDOInvites();
		}
		else
		{
			if(error)
			{
				onCancel();
			}
			else
			{
				if(finished)
				{
					onFinish();
				}
				else
				{
					switch(step)
					{
						case 0:
						{
							this.setState({ step: 1 }, () => 
							{
								this._sign();
							});
						}
						break;

						case 1:
						{
							this._sign();
						}
						break;
					}
				}
			}
		}
	}

	_handle_onSelectOperator = (operator) => 
	{
		this.setState({ operator_selected: operator });
	}

	_handle_onAttorneyChange = (attorney) => 
	{
		console.log("_handle_onAttorneyChange", { attorney });
		this.setState({ attorney_selected: attorney, disabled: false, });
	}

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

	render()
	{
		const { step, operators, edo_message, loading, disabled, operator_selected } = this.state;
		const { error, message, ready, attorney, attorneys, attorney_selected, } = this.state;

		const { onCancel, calculation_id, } = this.props;
		console.log({ operators, props: this.props });

		return (
			<div className="edo_detail">
				<div className="docs_list medium-icon">
					<p className="list_title">Подписание через ЭДО</p>
				</div>
				<>
					{ step === 0 && (
						<div className="form_field edo_list_field">
							<label className="wide">Выберите оператора ЭДО для отправки дополнительного соглашения [{ this.props.contract_number }]</label>
							<div className="edo_list_selection edo_sign_documents_document" style={{ flexDirection: "column", border: "none", padding: "0px 0px 0px 15px", }}>
								{ operators !== undefined && operators !== null && (
									<>
										{ operators.length === 0 ? (
											<div className="edo_sign_documents_document_right" style={{ border: "none", }}>
												<div className="status_icon await"></div>
												<div className="status_title">
													<i>{ edo_message }</i>
												</div>
											</div>
										) : (
											operators.map((operator, index) => (
												<div className="form_field checkbox item" key={ index }>
													<input type="radio" 
														checked={ operator.box_id === operator_selected.box_id } 
														hidden="" 
														id={ `operator_${ index }` } 
														name={ `operator_${ index }` } 
														onChange={ (event) => this._handle_onSelectOperator(operator) } 
														disabled={ false } 
													/>
													<label htmlFor={ `operator_${ index }` } className="unselectable">{ operator.provider_edo }</label>
												</div>
											) )	
										)}
									</>
								) }
							</div>
						</div>
					) }
					{ step === 1 && (
						<div className="docs_list medium-icon edo_sign_documents_list">
							<div className="edo_sign_documents_document">
								<div className="edo_sign_documents_document_left">
									<p className="doc_name i-pdf extension edo_sign_document" data-format={ "pdf" }>
										Дополнительное соглашение №{ calculation_id } от { moment().format("DD.MM.YYYY") }
									</p>
								</div>
								<div className="edo_sign_documents_document_right">
									{ loading ? (
										<>
											<SpinnerCircular size={ 22 } thickness={ 100 } speed={ 100 } color="rgba(236, 239, 244, 1)" secondaryColor="rgba(28, 1, 169, 1)" />
											{ !error && (
												<i>{ ready ? "Подписание дополнительного соглашения" : "Подготовка подписания" }</i>
											) }
										</>
									) : (
										<>
											{ error ? (
												<>
													<div className="status_icon error"></div>
													<i>{ message !== undefined && message !== null ? message : "" }</i>
												</>
											) : (
												<>
													{ attorney && (
														<>
															<div className="status_icon await"></div>
															<div className="edo_sign_status_attorney_select">
																<Select 
																	id="edo_attorneys_list" 
																	name="edo_attorneys_list" 
																	options={ attorneys } 
																	placeholder="Выберите доверенность" 
																	noOptionsMessage={ ({ inputValue }) => !inputValue ? "" :"Ничего не найдено" } 
																	isSearchable={ true } 
																	className="autocomlete autocomlete_with_indicators" 
																	classNamePrefix="react-select" 
																	value={ attorney_selected } 
																	onChange={ (element) => { this._handle_onAttorneyChange(element) } } 
																	required={ true } 
																/>
															</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: step === 0 ? "space-between" : "flex-end" }}>
							{ step === 0 && (
								<button className="button button-blue" onClick={ this._handle_onCancel }>Отменить</button>
							) }
							<button type="submit" className="button button-blue" disabled={ disabled }>
								{ 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>
		)
	}
}

function mapStateToProps(state, ownProps) 
{
	console.log("SignEDO", "mapStateToProps", { state: state });
	return {
		operators: state.edo.operators, 
		edo_message: state.edo.message, 
	}
}

export default connect(mapStateToProps)(SignEDO)