import React from "react";
import Head from "next/head";
import Image from "next/image";
import moment from "moment";
import 'moment/locale/ru';
import numeral from "numeral";
import { SpinnerCircular } from "spinners-react";
import Link from "next/link";

export default class Comparison extends React.Component 
{
	constructor(props) 
	{
		super(props);
		this.state = {
			date: null, 
			loading: false, 
			calculation: null, 
			today: moment(), 
			show_previous: false, 
			mixed_index: 0, 
			signatories_show_all: false, 
			opened: [], 
		};
	}

	componentDidMount() 
	{
		const { signer, signatories, calculations, calculation_id, current } = this.props;
		const { today } = this.state;
		if(signer === undefined)
		{
			if(signatories !== undefined && signatories !== null)
			{
				this._handle_onSigner(signatories[0].signatoryid);
			}
		}

		let calculation = null;

		for(let i in calculations)
		{
			if(calculations[i].addcontract_number === calculation_id)
			{
				calculation = calculations[i];
				break;
			}
		}

		const opened = [];
		for(let i in current.payments)
		{
			if(moment(current.payments[i].plandate) >= today)
			{
				opened.push(current.payments[i].name);
				break;
			}
		}

		this.setState({ calculation, opened });
	}

	componentDidUpdate(prevProps, prevState)
	{
		if(prevProps.signatories === undefined || prevProps.signatories === null)
		{
			if(this.props.signer === undefined && this.props.signatories !== undefined && this.props.signatories !== null)
			{
				this._handle_onSigner(this.props.signatories[0].signatoryid);
			}
		}
	}

	_handle_onSigner = (signer_id) => 
	{
		this.props.onSigner(signer_id);
	}

	_handle_onOptions = () => 
	{
		if(this.props.editable)
		{
			this.props.onOptions();
		}
		else
		{
			this.props.onBack();
		}
	}

	_handle_onSignPaper = () => 
	{
		this.props.onSign(0);
	}

	_handle_onSignEDO = () => 
	{
		this.props.onSign(1);
	}

	_handle_onMixedPayment = (index) => 
	{
		const opened = [ ...this.state.opened ];

		if(opened.indexOf(index) > -1)
		{
			opened.splice(opened.indexOf(index));
		}
		else
		{
			opened.push(index);
		}

		this.setState({ opened });
	}

	_handle_onShowPrevious = () => 
	{
		this.setState({ show_previous: true });
	}

	_handle_onDownloadPDF = () => 
	{
		console.log("this.props");
		console.log(this.props);
		console.log("this.state");
		console.log(this.state);
	}

	_renderMixedPayments = () => 
	{
		const { calculation, mixed_index, opened, today, show_previous, } = this.state;
		const { current, calculated } = this.props;

		if(current !== undefined && current !== null && calculated !== undefined && calculated !== null) 
		{
			if(current.payments.length > calculated.payments.length)
			{
				return (
					<>
						{ current.payments.map((payment, index) => 
						{
							if(!show_previous && moment(payment.plandate) < today) { return null; }
							else
							{
								return (
									<div key={ `mixed_${ index }` } className={ `table_row ${ opened.indexOf(payment.name) > -1 && "opened" }` } onClick={ () => this._handle_onMixedPayment(payment.name) }>
										<p className="row_title">Платеж №{ payment.name }</p>
										<div className="table_group">
											<div className="table_cell">
												<div><span>Текущий график</span> { moment(payment.plandate, "YYYY.MM.DD").format("DD.MM.YYYY") }</div>
												<div><span>На сумму</span> { numeral(payment.sum).format(' ., ') }&nbsp;₽</div>
												<div><span>Сумма досрочного выкупа</span> { numeral(payment.early_repayment_sum).format(' ., ') }&nbsp;₽</div>
											</div>
											<div className="table_cell">
												<div><span>Новый график</span> { calculated.payments[index] !== undefined ? moment(calculated.payments[index].plandate, "YYYY.MM.DD").format("DD.MM.YYYY") : (`-`) }</div>
												<div><span>На сумму</span> { calculated.payments[index] !== undefined ? (<>{ numeral(calculated.payments[index].sum).format(' ., ') }&nbsp;₽</>) : (`-`) }</div>
												<div><span>Сумма досрочного выкупа</span> { calculated.payments[index] !== undefined ? (<>{ numeral(calculated.payments[index].early_repayment_sum).format(' ., ') }&nbsp;₽</>) : (`-`) }</div>
											</div>
										</div>
									</div>
								)
							}
						}) }
						<div key={ `mixed_total` } className={ `table_row ${ opened.indexOf("mixed_total") > -1 && "opened" }` } onClick={ () => this._handle_onMixedPayment("mixed_total") }>
							<p className="row_title">Итого</p>
							<div className="table_group">
							<div className="table_cell">
									<div><span>Текущий график</span> { numeral(current.total).format(' ., ') }&nbsp;₽</div>
								</div>
								<div className="table_cell">
									<div><span>Новый график</span> { numeral(calculated.total).format(' ., ') }&nbsp;₽</div>
								</div>
							</div>
						</div>
					</>
				)
			}
			else
			{
				return (
					<>
						{ calculated.payments.map((payment, index) => 
						{
							if(!show_previous && moment(payment.plandate) < today) { return null; }
							else
							{
								return (
									<div key={ `mixed_${ index }` } className={ `table_row ${ opened.indexOf(payment.name) > -1 && "opened" }` } onClick={ () => this._handle_onMixedPayment(payment.name) }>
										<p className="row_title">Платеж №{ payment.name }</p>
										<div className="table_group">
											<div className="table_cell">
												<div><span>Текущий график</span> { current.payments[index] !== undefined ? moment(current.payments[index].plandate, "YYYY.MM.DD").format("DD.MM.YYYY") : (`-`) }</div>
												<div><span>На сумму</span> { current.payments[index] !== undefined ? (<>{ numeral(current.payments[index].sum).format(' ., ') }&nbsp;₽</>) : (`-`) }</div>
												<div><span>Сумма досрочного выкупа</span> { current.payments[index] !== undefined ? (<>{ numeral(current.payments[index].early_repayment_sum).format(' ., ') }&nbsp;₽</>) : (`-`) }</div>
											</div>
											<div className="table_cell">
												<div><span>Новый график</span> { moment(payment.plandate, "YYYY.MM.DD").format("DD.MM.YYYY") }</div>
												<div><span>На сумму</span> { numeral(payment.sum).format(' ., ') }&nbsp;₽</div>
												<div><span>Сумма досрочного выкупа</span> { numeral(payment.early_repayment_sum).format(' ., ') }&nbsp;₽</div>
											</div>
										</div>
									</div>
								)
							}
						}) }
						<div key={ `mixed_total` } className={ `table_row ${ opened.indexOf("mixed_total") > -1 && "opened" }` } onClick={ () => this._handle_onMixedPayment("mixed_total") }>
							<p className="row_title">Итого</p>
							<div className="table_group">
								<div className="table_cell">
									<div><span>Текущий график</span> { numeral(current.total).format(' ., ') }&nbsp;₽</div>
								</div>
								<div className="table_cell">
									<div><span>Новый график</span> { numeral(calculated.total).format(' ., ') }&nbsp;₽</div>
								</div>
							</div>
						</div>
					</>
				)
			}
		}

		return null;
	}

	render() 
	{
		const { calculation, mixed_index, today, show_previous, signatories_show_all } = this.state;
		const { number, signer, signatories, current, calculated } = this.props;

		return (
			<article className="compare">
				<div className="compare_top">
					<p>Выбранный(ые) варианты изменения графика</p>
					<a className="interactive" onClick={ this._handle_onOptions }>Вернуться к параметрам изменения графика</a>
					{/*}
					<button className="button button-blue" onClick={ this._handle_onDownloadPDF }>Скачать PDF</button>
					{*/}
				</div>
				<div className="compare_data">
					{ calculation !== undefined && calculation !== null && calculation.fix_last_payment_available_comment !== null && (
						<div className="form_field">
							<p><span>{ calculation.fix_last_payment_available_comment.label }:</span> { calculation.fix_last_payment_available_comment.value ? "Да" : "Нет" }</p>
						</div>
					) }
					{ calculation !== undefined && calculation !== null && calculation.date_offset_type_comment !== null && (
						<div className="form_field">
							<input type="checkbox" hidden id="" name="" checked={ calculation.date_offset_type_comment.value ? true : false } disabled={ true } style={ calculation.date_offset_type_comment.value ? {} : { background: "unset"} } />
							<label htmlFor="">{ calculation.date_offset_type_comment.label }</label>
						</div>
					) }
					{ calculation !== undefined && calculation !== null && calculation.insurance_price_result_comment !== null && (
						<div className="form_field">
							<p><span>{ calculation.insurance_price_result_comment.label }:</span> { calculation.insurance_price_result_comment.value }</p>
						</div>
					) }
					{ calculation !== undefined && calculation !== null && calculation.number_paydate_comment !== null && (
						<div className="form_field">
							<p><span>{ calculation.number_paydate_comment.label }:</span> { calculation.number_paydate_comment.value }</p>
						</div>
					) }
					{ calculation !== undefined && calculation !== null && calculation.period_new_comment !== null && (
						<div className="form_field">
							<p><span>{ calculation.period_new_comment.label }:</span> { calculation.period_new_comment.value }</p>
						</div>
					) }
					{ calculation !== undefined && calculation !== null && calculation.sum_comment !== null && (
						<div className="form_field">
							<p><span>{ calculation.sum_comment.label }</span> { calculation.sum_comment.value }</p>
						</div>
					) }
					{/*}
					<div className="form_field">
						<input type="checkbox" hidden id="" name="" checked disabled />
						<label htmlFor="">Изменить дату платежа</label>
					</div>
					<div className="form_field">
						<input type="checkbox" hidden id="" name="" checked disabled />
						<label htmlFor="">Изменение кол-ва платежей</label>
					</div>
					<div className="form_field">
						<p>
							<span>Дата платежа:</span> 1 месяц (37 платежей)
						</p>
					</div>
					<div className="form_field">
						<p>
							<span>Тип каникул:</span> С увеличением срока
						</p>
					</div>
					{*/}
				</div>
				<div className="compare_tables">
					<div className="compare_table">
						<p className="table_title">Текущий график</p>
						<div className="table_body">
							<div className="table_row table_header">
								<div>№</div>
								<div>Дата лизингового платежа</div>{/* className="sortable" */}
								<div>Лизинговый платеж с НДС ₽</div>{/* className="sortable" */}
								<div>Сумма досрочного выкупа</div>{/* className="sortable" */}
							</div>
							{ !show_previous && (
								<div className="table_row row-button" >
									<button className="button button-gray" onClick={ this._handle_onShowPrevious }>
										Показать прошедшие платежи
									</button>
								</div>
							) }
							{ current !== undefined && current !== null && current.payments.map((payment, index) => 
							{ 
								if(!show_previous && moment(payment.plandate) < today) { return null; }

								return (
									<div key={ `current_${ index }` } className="table_row" >
										<div>{ payment.name }</div>
										<div>{ moment(payment.plandate, "YYYY.MM.DD").format("DD.MM.YYYY") }</div>
										<div>{ numeral(payment.sum).format(' ., ') }&nbsp;₽</div>
										<div>{ numeral(payment.early_repayment_sum).format(' ., ') }&nbsp;₽</div>
									</div>
								)
							}) }
							{ current !== undefined && current !== null && (
								<div key={ `current_total` } className="table_row" >
									<div></div>
									<div><b>Итого</b></div>
									<div><b>{ numeral(current.total).format(' ., ') }&nbsp;₽</b></div>
									<div></div>
								</div>
							) }
						</div>
					</div>
					<div className="compare_table">
						{ calculation !== undefined && calculation !== null && (
							<p className="table_title">
								Изменения с платежа №{ calculation.label }
							</p>
						) }
						<div className="table_body" >
							<div className="table_row table_header">
								<div>№</div>
								<div>Дата лизингового платежа</div>{/* className="sortable" */}
								<div>Лизинговый платеж с НДС ₽</div>{/* className="sortable" */}
								<div>Сумма досрочного выкупа</div>{/* className="sortable" */}
							</div>
							{ !show_previous && (
								<div className="table_row row-button">
									<button className="button button-gray" onClick={ this._handle_onShowPrevious }>
										Показать прошедшие платежи
									</button>
								</div>
							) }
							{ calculated !== undefined && calculated !== null && calculated.payments.map((payment, index) => 
							{
								if(!show_previous && moment(payment.plandate) < today) { return null; }

								return (
									<div key={ `current_${ index }` } className="table_row">
										<div>{ payment.name }</div>
										<div>{ moment(payment.plandate, "YYYY.MM.DD").format("DD.MM.YYYY") }</div>
										<div>{ numeral(payment.sum).format(' ., ') }&nbsp;₽</div>
										<div>{ numeral(payment.early_repayment_sum).format(' ., ') } &nbsp;₽</div>
									</div>
								)
							}) }
							{ calculated !== undefined && calculated !== null && (
								<div key={ `calculated_total` } className="table_row" >
									<div></div>
									<div><b>Итого</b></div>
									<div><b>{ numeral(calculated.total).format(' ., ') }&nbsp;₽</b></div>
									<div></div>
								</div>
							) }
						</div>
					</div>
					<div className="compare_table touchable">
						<div className="table_body">
							{ !show_previous && (
								<button className="button button-gray" style={{ position: "relative" }} onClick={ this._handle_onShowPrevious }>
									Показать прошедшие платежи
								</button>
							) }
							{ this._renderMixedPayments() }
						</div>
					</div>
				</div>
				<div className="compare_suscr">
					<p className="block_title">
						Подписанты
						{ signatories !== undefined && signatories !== null && signatories.length > 3 && (
							<a className="interactive" onClick={() => { this.setState({ signatories_show_all: true })}}>Все</a>
						)}
					</p>
					<div className="feed static">
						{ signatories !== undefined && signatories !== null && signatories.slice(0, signatories_show_all ? signatories.length : 3).map((person, index) => (
							<div className="feed_item user" key={ person.signatoryid }>
								<input type="radio" hidden id={ `user_${ person.signatoryid }` } name={ `user_${ person.signatoryid }` } checked={ person.signatoryid === signer } onChange={ () => this._handle_onSigner(person.signatoryid) }/>
								<label htmlFor={ `user_${ person.signatoryid }` }></label>
								<img src="/assets/images/icons/avatar.svg" alt="" />
								<div>
									<p className="item_title">{ `${ person.lastname } ${ person.firstname } ${ person.middlename }` }</p>
									<p className="item_desc">{ person.jobtitle }</p>
								</div>
							</div>
						)) }
					</div>
				</div>
				<div className="btn_group">
					<button className="button button-blue" onClick={ this._handle_onSignPaper }>
						Согласовать и подписать в бумажном виде
					</button>
					{/*}
					<button className="button button-blue" onClick={ this._handle_onSignEDO }>
						Согласовать и подписать по ЭДО
					</button>
					{*/}
				</div>
			</article>
		);
	}
}