import React from "react";
import Head from "next/head";
import Image from "next/image";
import { connect } from "react-redux";
import { withRouter } from "next/router";
import moment from "moment";
import { SpinnerCircular } from "spinners-react";
import Link from "next/link";
import { reduxWrapper } from "../../../store";

import Header from "../../components/Header";
import Footer from "../../components/Footer";
import Company from "../../components/Company";
import DateInput from "../../components/DatePicker";

import InnerMenu from "./../components/InnerMenu";

import SignatoriesList from "./components/SignatoriesList";
import CalculationsList from "./components/CalculationsList";

import VariantsList from "./components/VariantsList";
import FinalMessage from "./components/FinalMessage";

import {
	getContractInfo, 
	getContractGraphicChange, 
	getContractGraphicChangeVariants, 
	getContractGraphicChangeGetCurrent, 
	getContractGraphicChangeGetCalculated, 
	getContractGraphicChangeSignatories, 
	getContractGraphicChangeCalculationsList,
	signContractGraphicChange, 
} from "../../../actions";
import Options from "./components/Options";
import Comparison from "./components/Comparison";
import AccountLayout from "../../components/Layout/Account";
import ContractHeader from "../components/ContractHeader";

class ChangeGraphicPage extends React.Component 
{
	constructor(props) 
	{
		super(props);
		this.state = {
			loading: false, 
			contracts_info: {}, 
			mode_options: false, 
			mode_comparison: false, 
			mode_calculation: false, 
			mode_final: false, 
			calculation_id: undefined, 
			signer: undefined, 
			signatories: null, 
			calculations: null, 
			variants: null, 
			variants_selected: [], 
			variants_unavailable: [], 
			variants_loading: false, 
			variants_types: [
				{ title: "Изменение даты платежей", type: "change_payment_date", help: "Это подсказка по Изменить дату платежа" }, 
				{ title: "Включение КАСКО в график", type: "insurance_change", help: "Это подсказка по Изменение параметров страхования" }, 
				//{ title: "Изменение выкупного платежа", type: "last_payment_change", help: "Это подсказка по Изменение формулировки выкупной платеж" }, 
				{ title: "Лизинговые каникулы", type: "date_offset_change", help: "Это подсказка по Лизинговые каникулы" }, 
				{ title: "Увеличение срока договора лизинга", type: "contract_term_change", help: "Это подсказка по Изменение кол-ва платежей" }, 
				{ title: "Изменение суммы платежей", type: "sum_pay_change", help: "Это подсказка по Изменение суммы платежей" }, 
				{ title: "Досрочный выкуп", type: "early_redemption_change", help: "Это подсказка по Досрочный выкуп" }, 
				//{ title: "Изменение Лизингополучателя", type: "", help: "Это подсказка по Изменение Лизингополучателя" }, 
			], 
			options: null, 
			current: null, 
			calculated: null, 
			comment: null, 
			editable: false, 
		};
	}

	static getDerivedStateFromProps(nextProps, prevState) 
	{
		console.log("getDerivedStateFromProps", nextProps);
		return {
			contracts_info: nextProps.contracts_info, 
			signatories: nextProps.signatories, 
			calculations: nextProps.calculations, 
			variants: nextProps.variants, 
			options: nextProps.options, 
			current: nextProps.current, 
			calculated: nextProps.calculated, 
		};
	}

	componentDidMount() 
	{
		const { dispatch, number } = this.props;

		if(document.location.hash !== undefined && document.location.hash !== null && document.location.hash !== "")
		{
			if (!this.state.loading && number !== undefined) 
			{
				this.setState({ loading: true }, () => 
				{
					if(this.state.contracts_info[ number ] === undefined)
					{
						getContractInfo({ dispatch, number });
					}

					Promise.all([
						getContractGraphicChangeCalculationsList({ dispatch, number }), 
						getContractGraphicChangeSignatories({ dispatch, number }), 
						getContractGraphicChangeGetCurrent({ dispatch, number }), 
						getContractGraphicChangeGetCalculated({ dispatch, calculation: document.location.hash.replace("#", "") }), 
					])
					.then(() => 
					{
						this.setState({ loading: false, mode_calculation: true });
					});
				});
			}
		}
		else
		{
			if (!this.state.loading && number !== undefined) 
			{
				this.setState({ loading: true }, () => 
				{
					if(this.state.contracts_info[ number ] === undefined)
					{
						getContractInfo({ dispatch, number });
					}

					getContractGraphicChange({ dispatch, number, })
					.then(() => 
					{
						this.setState({ loading: false });
					})
					.catch(() => {});
				});
			}
		}
	}

	componentWillUnmount() {}

	componentDidUpdate(prevProps, prevState)
	{
		if(document.location.hash)
		{
		}
	}

	_handle_onVariants = () => 
	{
		this.setState({ mode_options: false, mode_comparison: false });
	}

	_handle_onVariantSelect = (type) => 
	{
		const selected = [ ...this.state.variants_selected ];

		if(selected.indexOf(type) > -1)
		{
			selected.splice(selected.indexOf(type), 1)
		}
		else
		{
			selected.push(type);
		}

		this.setState({ variants_selected: selected, variants_loading: true }, () => 
		{
			const { variants_selected, variants_types } = this.state;
			const variants = {};

			for(let i in variants_types)
			{
				if(variants_selected.indexOf(variants_types[i].type) > -1)
				{
					variants[ variants_types[i].type ] = true;
				}
				else
				{
					variants[ variants_types[i].type ] = false;
				}
			}

			getContractGraphicChangeVariants({ dispatch: this.props.dispatch, number: this.props.number, variants })
			.then(() => 
			{
				this.setState({ variants_loading: false });
			});
		});
	}

	_handle_onBack = () => 
	{
		this.setState({ mode_options: false, mode_comparison: false });
	}

	_handle_onOptions = () => 
	{
		window.scrollTo(0, 0);
		this.setState({ mode_options: true, mode_comparison: false });
	}

	_handle_onSigner = (signer_id) => 
	{
		this.setState({ signer: signer_id });
	}

	_handle_onSign = (type) => 
	{
		const { calculation_id, signer, } = this.state;
		const { number, } = this.props;

		this.setState({ loading: true }, () => 
		{
			signContractGraphicChange({
				contract_number: number, 
				addcontract_number: calculation_id, 
				signatoryid: signer, 
				type
			})
			.then((comment) => 
			{
				this.setState({ loading: false, mode_final: true, mode_options: false, mode_comparison: false, comment });
			})
			.catch(() => 
			{	
				this.setState({ loading: false, }, () => 
				{
					alert("К сожалению, при расчёте возникла ошибка.\n\nДля расчёта вариантов изменения графика обратитесь, пожалуйста, в Службу клиентского сервиса по адресу электронной почты clint@evoleasing.ru или по телефону Горячей линии 8 800 333 75 75.");
				});
			});	
		});
	}

	_handle_onCalculate = (calculation_id) => 
	{
		const { dispatch, number } = this.props;

		getContractGraphicChangeCalculationsList({ dispatch, number })
		.then(() => 
		{
			setTimeout(() => 
			{
				this._handle_onCalculation(calculation_id, true);
			}, 100);
		})
		.catch(() => 
		{
		});	
	}

	_handle_onCalculation = (calculation_id, editable = false) => 
	{
		this.setState({ editable: editable, loading: true, mode_options: false, calculation_id: calculation_id }, () => 
		{
			const { dispatch, number } = this.props;

			Promise.all([
				getContractGraphicChangeGetCurrent({ dispatch, number }), 
				getContractGraphicChangeGetCalculated({ dispatch, calculation: calculation_id }), 
			])
			.then(() => 
			{
				this.setState({ loading: false, mode_comparison: true, });
			});
		});
	}

	render() 
	{
		const { number } = this.props;
		const { loading, contracts_info, mode_options, mode_comparison, mode_calculation, mode_final, signer, signatories, calculations, calculation_id, editable, variants, variants_loading, variants_selected, variants_types, variants_unavailable, options, current, calculated, comment } = this.state;

		let { date, car, status } = contracts_info[ number ] !== undefined ? contracts_info[ number ] : {};

		console.log("contracts_info", contracts_info);

		return (
			<React.Fragment>
				<Head>
					<title>ЛК Эволюция автолизинга</title>
					<meta name="description" content="ЛК Эволюция автолизинга" />
				</Head>
				<Header { ...this.props } />
				<AccountLayout>
					<div className="title_wrapper">
						<div className="left" style={{ flexDirection: "column" }}>
							<ContractHeader number={ number } date={ date } car={ car }/>
						</div>
						<Company { ...this.props }/>
					</div>
					{ loading ? (
						<div className="aside_container about">
							<InnerMenu number={ number } status={ status } { ...this.props } />
							<article className="changes">
								<div className="container" style={{ display: "flex", alignItems: "center", justifyContent: "center", }}>
									<SpinnerCircular size={ 90 } thickness={ 51 } speed={ 100 } color="rgba(28, 1, 169, 1)" secondaryColor="rgba(236, 239, 244, 1)" />
								</div>
							</article>
						</div>
					) : (
						<>
							{ mode_comparison || mode_calculation || mode_final ? (
								<>
									{ mode_final ? (
										<div className="aside_container about">
											<FinalMessage number={ number } comment={ comment }/>
										</div>
									) : (
										<div className="aside_container about">
											<Comparison 
												signer={ signer } 
												signatories={ signatories } 
												calculations={ calculations } 
												calculation_id={ calculation_id } 
												editable={ editable } 
												current={ current } 
												calculated={ calculated } 
												onBack={ this._handle_onBack } 
												onOptions={ this._handle_onOptions } 
												onSigner={ this._handle_onSigner } 
												onSign={ this._handle_onSign } 
											/>
										</div>
									) }
								</>
							) : (
								<div className="aside_container about">
									<InnerMenu number={ number } status={ status } { ...this.props } />
									<article className="changes">
										{ mode_options ? (
											<Options 
												dispatch={ this.props.dispatch } 
												number={ number } 
												variants={ variants } 
												variants_selected={ variants_selected } 
												options={ options } 
												onVariants={ this._handle_onVariants } 
												onCalculate={ this._handle_onCalculate } 
											/>
										) : (
											<>
												{ variants !== null && (
													<>
														{ variants.enable_addcontract === false ? (
															<div className="block alert">
																<p>{ variants.comment !== null ? variants.comment : "Внимание! Существует активное неподписанное дополнительное соглашение. Расчёт новых изменений невозможен." }</p>
																{ variants.comment === null && (<Link href={`/contract/${ number }/agreement`}><a>Подробнее</a></Link>) }
															</div>
														) : (
															<></>
														) }
														{ calculations !== undefined && calculations !== null && calculations.length > 0 && (
															<div className="block">
																<p className="title">Предварительные расчеты</p>
																<CalculationsList number={ number } calculations={ calculations } onCalculation={ this._handle_onCalculation }/>
															</div>
														) }
														<div className="block">
															<p className="title">
																Подписанты
																<Link href="/support/request#0b6b0460b862ea69764f3e9d5dca187e"><a>Добавить подписанта</a></Link>
															</p>
															<SignatoriesList signatories={ signatories }/>
														</div>
														<VariantsList 
															onOptions={ this._handle_onOptions } 
															onVariant={ this._handle_onVariantSelect } 
															variants={ variants } 
															variants_types={ variants_types } 
															selected={ variants_selected } 
															loading={ variants_loading } 
															blocked={ variants.enable_addcontract === false ? true : false } 
														/>
														{/*}
														{ variants.enable_addcontract !== false && (
														) }
														{*/}
													</>
												) }
											</>
										) }
									</article>
								</div>
							) }
						</>
					) }
				</AccountLayout>
				<Footer/>
			</React.Fragment>
		);
	}
}

function mapStateToProps(state, ownProps) 
{
	return {
		contracts_info: state.contracts_info, 
		signatories: state.contract.change.signatories, 
		calculations: state.contract.change.calculations, 
		variants: state.contract.change.variants, 
		options: state.contract.change.options, 
		current: state.contract.change.current, 
		calculated: state.contract.change.calculated, 
	};
}

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

export default withRouter(connect(mapStateToProps)(ChangeGraphicPage));