import React from "react";
import Head from "next/head";
import Image from "next/image";
import Link from "next/link";
import cookie from "cookie";
import numeral from "numeral";
import pluralize from "pluralize-ru";
import { SpinnerCircular } from "spinners-react";
import { connect } from "react-redux";
import { withRouter } from 'next/router';
import moment from "moment";
import NoSSR from "@mpth/react-no-ssr";

import QuestionnaireForm from "../QuestionnaireForm";
import { MatchMedia } from '../../../../utils/mediaqueries';
import { reduxWrapper } from '../../../../store';
import { downloadQuestionnaire, saveQuestionnaire } from "../../../../actions";
import DigitalCertificates from "../DigitalCertificates";
import FormMessage from "../FormMessage";

class Form_8_Signing extends QuestionnaireForm 
{
	constructor(props) 
	{
		super(props);
		this.state = {
			loading: true, 
			main: {}, 
			head_person: {}, 
			signatory_person: {}, 
			sign_digital: true, 
			address: "", 
			filename: null, 
			mobile: MatchMedia() === "mobile" ? true : false, 
			company: {}, 
			downloading: false, 
			error: false, 
			digital_disabled: false, 
			sign: {}, 
		};
	}

	static getDerivedStateFromProps(nextProps, prevState) 
	{
		return {
			main: nextProps.questionnaire.main, 
			signatory_person: nextProps.questionnaire.signatory_person, 
			sign: nextProps.questionnaire.sign, 
			head_person: nextProps.questionnaire.head_person, 
			company: nextProps.company, 
		};
	}

	componentDidMount() 
	{
		//console.log("Form_8_Signing", "CDM");


		//setTimeout(() => 
		//{
			//console.log("Form_8_Signing", "CDM", { state: this.state });


			const { main, head_person, signatory_person } = this.state;

			const update = { filename: `${ main.inn }_questionnaire_${ moment().format("DDMMYYYY_HHmmss") }.pdf` };
			let digital = true;

			if(signatory_person.not_head_person)
			{
				update.digital_disabled = true;
				digital = false;
			}

			this.setState({ ...this.state, ...update, ...{ loading: false } }, () => 
			{
				this._handle_onBranchChange([
					{ name: `sign.digital`, value: digital }, 
				]);
			});	

		//}, 50);
	}

	_handle_onFormSubmit = (event) => 
	{
		event.preventDefault();
		//console.log("FormAddress", "_handle_onFormSubmit");

	};

	_check_fields_disabled = (values) => 
	{
		for (let i in values) 
		{
			if (values[i] === "") 
			{
				return true;
			}
		}

		return false;
	};

	_handle_onDownload = () => 
	{
		const { filename, downloading } = this.state;
		if(!downloading)
		{
			this.setState({ downloading: true }, () => 
			{
				saveQuestionnaire()
				.then(() => 
				{
					downloadQuestionnaire({ filename, download: true })
					.then(() => 
					{
						this._handle_onCheckboxFieldChange("step", 9);
						setTimeout(() => 
						{
							this.props.onNextStep("status");
						}, 10);	
					})
					.catch(() => 
					{
						this.setState({ downloading: false, error: true, })
					});
				})
				.catch(() => 
				{
					this.setState({ downloading: false, error: true, })
				});
			});
		}
	}

	_handle_onChangeSignMethod = () => 
	{
		const { sign } = this.state;
		this._handle_onBranchChange([
			{ name: `sign.digital`, value: sign.digital ? false : true }, 
		]);
		window.scrollTo(0, 0);
	}

	render() 
	{
		const { loading, filename, sign_digital, sign, head_person, mobile, company, main, downloading, error, digital_disabled } = this.state;

		//console.log({ sign });


		if(loading)
		{ 
			return (
				<div style={{ minHeight: 200, display: "flex", justifyContent: "center", alignItems: "center", }}>
					<SpinnerCircular size={ 90 } thickness={ 51 } speed={ 100 } color="rgba(28, 1, 169, 1)" secondaryColor="rgba(236, 239, 244, 1)" />
				</div>
			); 
		}
		else
		{
			return (
				<React.Fragment>
					<form onSubmit={ this._handle_onFormSubmit } className="questionnaire questionnaire_8">
						<p className="title">8. Выбор метода подписания</p>

						<div className="form_field">
							<div style={{ width: "100%" }}>
								<div className="form_field checkbox">
									<input type="radio" hidden="" 
										id="sign_digital" 
										name="sign_digital" 
										checked={ sign.digital } 
										onChange={ this._handle_onChangeSignMethod } 
									/>
									<label htmlFor="sign_digital">
										<b>Подписать онлайн используя ЭЦП</b>
									</label>
								</div>
							</div>
						</div>

						{ sign.digital && (
							<>
								{ digital_disabled ? (
									<div className="questionnaire message moderate">
										<svg width="44" height="45" viewBox="0 0 44 45" fill="none" xmlns="http://www.w3.org/2000/svg">
											<path d="M40.5425 31.1863L25.7969 8.08116C24.9653 6.77804 23.5459 6 22 6C20.4539 6 19.0345 6.77804 18.2032 8.08116L3.45741 31.1862C2.57234 32.5732 2.51363 34.3313 3.30467 35.7746C4.09572 37.2173 5.60918 38.1137 7.25444 38.1137H36.7456C38.3909 38.1137 39.9044 37.2175 40.6956 35.7742C41.4863 34.3313 41.4276 32.5733 40.5425 31.1863ZM22 34.2245C20.644 34.2245 19.5448 33.1252 19.5448 31.7694C19.5448 30.4133 20.6441 29.3141 22 29.3141C23.356 29.3141 24.4551 30.4133 24.4551 31.7694C24.4551 33.1252 23.3559 34.2245 22 34.2245ZM25.403 17.1635L24.1937 25.3052C24.0157 26.5037 22.8999 27.3309 21.7016 27.1529C20.7334 27.0091 20.0075 26.25 19.8582 25.333L18.5451 17.2074C18.2394 15.3155 19.5251 13.534 21.417 13.2283C23.3089 12.9226 25.0904 14.2083 25.3962 16.1002C25.4536 16.4565 25.4517 16.8243 25.403 17.1635Z" fill="white"/>
										</svg>
										<p><b>Внимание</b>
											Подписант отличается от Единоличного исполнительного органа. Подписание посредством ЭЦП недоступно.
										</p>
									</div>
								) : (
									<>
										{ mobile ? (
											<div className="questionnaire message moderate">
												<svg width="44" height="45" viewBox="0 0 44 45" fill="none" xmlns="http://www.w3.org/2000/svg">
													<path d="M40.5425 31.1863L25.7969 8.08116C24.9653 6.77804 23.5459 6 22 6C20.4539 6 19.0345 6.77804 18.2032 8.08116L3.45741 31.1862C2.57234 32.5732 2.51363 34.3313 3.30467 35.7746C4.09572 37.2173 5.60918 38.1137 7.25444 38.1137H36.7456C38.3909 38.1137 39.9044 37.2175 40.6956 35.7742C41.4863 34.3313 41.4276 32.5733 40.5425 31.1863ZM22 34.2245C20.644 34.2245 19.5448 33.1252 19.5448 31.7694C19.5448 30.4133 20.6441 29.3141 22 29.3141C23.356 29.3141 24.4551 30.4133 24.4551 31.7694C24.4551 33.1252 23.3559 34.2245 22 34.2245ZM25.403 17.1635L24.1937 25.3052C24.0157 26.5037 22.8999 27.3309 21.7016 27.1529C20.7334 27.0091 20.0075 26.25 19.8582 25.333L18.5451 17.2074C18.2394 15.3155 19.5251 13.534 21.417 13.2283C23.3089 12.9226 25.0904 14.2083 25.3962 16.1002C25.4536 16.4565 25.4517 16.8243 25.403 17.1635Z" fill="white"/>
												</svg>
												<p><b>Внимание</b>
													Для подписания анкеты посредством ЭЦП пожалуйста воспользуйтесь стационарным компьютером или ноутбуком с установленной программой КриптоПро CSP.
												</p>
											</div>
										) : (
											<NoSSR>
												<DigitalCertificates main={ main } company={ company } head_person={ head_person } onSignDigital={ this._handle_onSignDigital }/>
											</NoSSR>
										) }
									</>
								)}
							</>
						) }

						<div className="form_field">
							<div style={{ width: "100%" }}>
								<div className="form_field checkbox">
									<input type="radio" hidden="" 
										id="sign_print" 
										name="sign_print" 
										checked={ !sign.digital } 
										onChange={ this._handle_onChangeSignMethod } 
									/>
									<label htmlFor="sign_print">
										<b>Подписать в бумажном виде</b>
									</label>
								</div>
							</div>
						</div>

						{ error && (
							<FormMessage type="error" title="Ошибка" message="К сожалению в процессе создания документа возникла ошибка. Пожалуйста, обратитесь к сотруднику Отдела по работе с клиентами или попробуйте еще раз."/>
						)}
						{ !sign.digital && (
							<div className="docs_list medium-icon">
								<div className="row">
									<p className="doc_name i-pdf extension">
										{ filename }
										<span style={{ width: "100%" }}>Анкета клиента</span>
									</p>
									<a className="button button-blue " onClick={ this._handle_onDownload }>
										{ downloading ? (
											<SpinnerCircular size={ 24 } thickness={ 50 } speed={ 100 } color="rgba(28, 1, 169, 1)" secondaryColor="rgba(236, 239, 244, 1)" />
										) : "Скачать" }
									</a>
								</div>
							</div>
						) }
					</form>
				</React.Fragment>
			);
		}
	}
}

function mapStateToProps(state, ownProps)
{
	return {
		questionnaire: state.questionnaire, 
		company: state.company, 
	}
}

export const getServerSideProps = reduxWrapper.getServerSideProps(store => 
	async ({ req, res, query }) => 
	{
    }
);

export default connect(mapStateToProps)(Form_8_Signing);