import React from "react";
import moment from "moment";
import { SpinnerCircular } from "spinners-react";
import Dropzone from 'react-dropzone';

import { docEDOSign, docEDOStatus, getFile, signCancelDocument, signCheckCancelDocument, signCheckDownloadContractProject, signGetFileContractProject, signUploadPaperDocument } from "../../../actions";

export default class SignPlannedContract extends React.Component
{
	constructor(props)
	{
		super(props);
		this.state = {
			loading: true, 
			uploading: false, 
			finished: false, 
			loading_download_file: false, 
			loading_cancel_sign: false, 
			loading_signing: false, 
			loading_uploading_file: false, 
			disabled: false, 
			status: undefined, 
			contract_entity_id: undefined, 
			url: undefined, 
			error: false, 
			message: undefined, 
		};
	}

	async componentDidMount()
	{
		const { contract } = this.props;

		if(contract.sign_type === "EDO")
		{
			const status_result = await docEDOStatus({ contract_number: contract.name });
			this.setState({ contract_entity_id: status_result.edoid, status: status_result.status, loading: false, url: status_result.url_edo });
		}
		else
		{
			this.setState({ loading: false });
		}
	}

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

		this.setState({ loading: true, disabled: true, uploading: true, loading_uploading_file: true, finished: false, }, async () => 
		{
			await signUploadPaperDocument(contract.name, deal_id, files);
			this.setState({ loading: false, disabled: false, uploading: false, loading_uploading_file: false, finished: true, });
		});
	}

	_handle_downloadFile = () => 
	{
		const { contract } = this.props;

		this.setState({ disabled: true, loading_download_file: true, error: false, }, async () => 
		{
			const check_result = await signCheckDownloadContractProject({ contract_number: contract.name });
			if(check_result.status === "success")
			{
				const link_result = await signGetFileContractProject({
					contract_number: contract.name
				});

				await getFile({ id: link_result.url, filename: `ЛК ЭВОЛЮЦИЯ ${ contract.name }.${ link_result.extension }` });
				this.setState({ disabled: false, loading_download_file: false, error: false, uploading: contract.sign_type === "EDO" ? false : true, });	
			}
			else
			{
				this.setState({ disabled: false, loading_download_file: false, error: true, uploading: false, message: check_result.message !== undefined && check_result.message !== null ? check_result.message : "Возникла ошибка обработки документа" })
			}
		});
	}

	_handle_cancelSign = () => 
	{
		const { contract, onDealContractsUpdate } = this.props;

		this.setState({ disabled: true, loading_cancel_sign: true }, async () => 
		{
			const check_result = await signCheckCancelDocument({ contract_number: contract.name, doc_type_id: contract.sign_type === "EDO" ? "144" : "60" });
			if(check_result.status === "success")
			{
				const cancel_result = await signCancelDocument({ contract_number: contract.name, doc_type_id: contract.sign_type === "EDO" ? "144" : "60" });
				setTimeout(() => {
					onDealContractsUpdate();
				}, 1000);
			}
			else
			{
				this.setState({ 
					loading: false, 
					loading_cancel_sign: false, 
					error: true, 
					message: check_result.message !== undefined && check_result.message !== null ? check_result.message : `Возникла ошибка при отмене подписания${ contract.sign_type === "EDO" ? " через ЭДО" : "" }`, 
				});
			}
		});
	}

	_handle_sendToEDO = () => 
	{
		const { contract, onDealContractsUpdate } = this.props;

		this.setState({ disabled: true, loading_signing: true }, async () => 
		{
			const check_result = await signCheckDownloadContractProject({ contract_number: contract.name });
			if(check_result.status === "success")
			{
				const status_result = await docEDOStatus({ contract_number: contract.name });

				if(status_result.status > 0)
				{
					const sign_result = await docEDOSign({ edoid: status_result.edoid });

					const new_status_result = await docEDOStatus({ contract_number: contract.name });
					this.setState({ status: new_status_result.status, loading: false, disabled: false, loading_signing: false });
				}
				else
				{
					this.setState({ 
						loading: false, 
						loading_signing: false, 
						error: true, 
						message: status_result.message !== undefined && status_result.message !== null ? status_result.message : `Возникла ошибка при отправке в ЭДО`, 
					});	
				}
			}
			else
			{
				this.setState({ 
					loading: false, 
					loading_signing: false, 
					error: true, 
					message: check_result.message !== undefined && check_result.message !== null ? check_result.message : `Возникла ошибка при отправке в ЭДО`, 
				});
			}
		});
	}

	_handle_onGoToEDO = () => 
	{
		const { url } = this.state;

		if(url !== undefined && url !== null)
		{
			window.open(url, "_blank");
		}
	}

	render()
	{
		const { index, contract, } = this.props;
		const { loading, status, uploading, disabled, finished, error, message, loading_download_file, loading_uploading_file, loading_cancel_sign, loading_signing } = this.state;

		return (
			<div className="document deal_contract_sign_item">
				<div className="icon">
					<span className="extension">PDF</span>
				</div>
				<div className="title">
					<p>{ contract.name }</p>
					<div className="description">
						<span>{ moment(contract.date).format("DD.MM.YYYY") }</span>
						<span>{ contract.brand_name }</span>
						<span>{ contract.model_name }</span>
					</div>
				</div>
				{ loading ? (
					<div className="actions actions_with_status">
						<SpinnerCircular size={ 22 } thickness={ 100 } speed={ 100 } color="rgba(236, 239, 244, 1)" secondaryColor="rgba(28, 1, 169, 1)" />
					</div>
				) : (
					<>
						{ error ? (
							<div className="actions actions_with_status">
								<div className="status_icon error"></div>
								<div className="status_title">
									<i>{ message }</i>
								</div>
							</div>
						) : (
							<>
								{ contract.sign_type === "PAPER" && (
									<>
										{ finished ? (
											<div className="actions actions_with_status">
												<div className="status_icon success"></div>
												<div className="status_title">
													<i>Договор отправлен вашему менеджеру "ЛК Эволюция"</i>
												</div>
											</div>
										) : (
											<div className="actions" style={{ justifyContent: "flex-end" }}>
												{ uploading ? (
													<Dropzone onDrop={ (acceptedFiles) => this._handle_onUploadFile(acceptedFiles, index) } maxFiles={ 10 }>
														{ ({getRootProps, getInputProps}) => (
															<div { ...getRootProps() }>
																<button className="button" style={{ minWidth: "294px", }} disabled={ disabled }>
																{ loading_uploading_file ? (
																	<SpinnerCircular size={ 22 } thickness={ 100 } speed={ 100 } color="rgba(236, 239, 244, 1)" secondaryColor="rgba(28, 1, 169, 1)" />
																) : (
																	"Загрузить скан подписанного документа" 
																) }
																</button>
																<input { ...getInputProps() } />
															</div>
														) }
													</Dropzone>
												) : (
													<>
														<button className="button blue" style={{ minWidth: "230px", }} disabled={ disabled } onClick={ () => this._handle_downloadFile() }>
															{ loading_download_file ? (
																<SpinnerCircular size={ 22 } thickness={ 100 } speed={ 100 } color="rgba(236, 239, 244, 1)" secondaryColor="rgba(28, 1, 169, 1)" />
															) : (
																"Скачать файл для подписания"
															) }
														</button>
														<button className="button blue" style={{ minWidth: "175px", }} disabled={ disabled } onClick={ () => this._handle_cancelSign() }>
															{ loading_cancel_sign ? (
																<SpinnerCircular size={ 22 } thickness={ 100 } speed={ 100 } color="rgba(236, 239, 244, 1)" secondaryColor="rgba(28, 1, 169, 1)" />
															) : (
																"Отменить подписание"
															) }
														</button>
													</>
												) }
											</div>
										) }
									</>
								) }
								{ contract.sign_type === "EDO" && (
									<>
										{ status === 3 ? (
											<div className="actions actions_with_status">
												<div className="status_icon success"></div>
												<div className="status_title">
													<i>Подписанный договор будет доступен для скачивания в течение 1-2 минут.</i>
												</div>
											</div>
										) : (
											<div className="actions">
												{ status === 1 && (									
													<button className="button blue" style={{ minWidth: "130px", }} disabled={ disabled } onClick={ () => this._handle_downloadFile() }>
														{ loading_download_file ? (
															<SpinnerCircular size={ 22 } thickness={ 100 } speed={ 100 } color="rgba(236, 239, 244, 1)" secondaryColor="rgba(28, 1, 169, 1)" />
														) : (
															"Скачать проект"
														) }
													</button>
												) }
												{ status === 1 && (
													<button className="button blue" style={{ minWidth: "175px", }} disabled={ disabled } onClick={ () => this._handle_cancelSign() }>
														{ loading_cancel_sign ? (
															<SpinnerCircular size={ 22 } thickness={ 100 } speed={ 100 } color="rgba(236, 239, 244, 1)" secondaryColor="rgba(28, 1, 169, 1)" />
														) : (
															"Отменить подписание"
														) }
													</button>
												)}
												{ status === 1 && (
													<button className="button blue" style={{ minWidth: "144px", }} disabled={ disabled } onClick={ () => this._handle_sendToEDO() }>
														{ loading_signing ? (
															<SpinnerCircular size={ 22 } thickness={ 100 } speed={ 100 } color="rgba(236, 239, 244, 1)" secondaryColor="rgba(28, 1, 169, 1)" />
														) : (
															"Отправить в ЭДО" 
														) }
													</button>
												) }
												{ status === 2 && (
													<button className="button blue" onClick={ () => this._handle_onGoToEDO() }>Перейти в ЭДО</button>
												) }
											</div>
										) }
									</>
								) }
							</>
						) }
					</>
				) }
			</div>
		)
	}
}