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 numeral from "numeral";
import moment from "moment";
import { SpinnerCircular } from 'spinners-react';

import { reduxWrapper } from '../../store';

import Header from '../components/Header';
import Footer from '../components/Footer';
import Company from "../components/Company";
import InnerMenu from "./components/InnerMenu";

import { getContractInfo, getContractHelpCard, getContractInsurance, getContractRegistration, getContractTelematic, } from './../../actions';
import DownloadPdfButton from "../components/DownloadPdfButton";
import AccountLayout from "../components/Layout/Account";
import ContractHeader from "./components/ContractHeader";
import DownloadFileById from "../components/DownloadFileById";

class ContractServicesPage extends React.Component 
{
	constructor(props)
	{
		super(props);
		this.state = { 
			loading: false, 
			contracts_info: {}, 
			opened: [], 
			date: null, 
			car: null, 
			helpcard: null, 
			insurance: null, 
			registration: null, 
			telematic: null, 
			insurance_location_checked: false, 
		};
	}

	static getDerivedStateFromProps(nextProps, prevState)
	{
		return {
			contracts_info: nextProps.contracts_info, 
			date: nextProps.date, 
			car: nextProps.car, 
			helpcard: nextProps.helpcard, 
			insurance: nextProps.insurance, 
			registration: nextProps.registration, 
			telematic: nextProps.telematic, 
		};
	}

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

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

				Promise.all([
					new Promise((resolve) => { getContractHelpCard({ dispatch, number }).then(resolve())}), 
					new Promise((resolve) => { getContractInsurance({ dispatch, number }).then(resolve())}), 
					new Promise((resolve) => { getContractRegistration({ dispatch, number }).then(resolve())}), 
					new Promise((resolve) => { getContractTelematic({ dispatch, number }).then(resolve())}), 
				])
				.then(() => {
					this.setState({ loading: false });
				});
			});	
		}
	}

	componentDidUpdate(prevProps, prevState)
	{
		if(prevState.insurance === null && this.state.insurance !== null)
		{
			if(!this.state.insurance_location_checked)
			{
				this.setState({ insurance_location_checked: true }, () => 
				{
					if(document.location.hash.indexOf("insurance") > -1)
					{
						const o = [ ...this.state.opened ];
						o.push("insurance");
						this.setState({ opened: o });
					}

					if(document.location.hash.indexOf("ratcard") > -1)
					{
						const o = [ ...this.state.opened ];
						o.push("ratcard");
						this.setState({ opened: o });
					}

					if(document.location.hash.indexOf("telematic") > -1)
					{
						const o = [ ...this.state.opened ];
						o.push("telematic");
						this.setState({ opened: o });
					}

					if(document.location.hash.indexOf("registration") > -1)
					{
						const o = [ ...this.state.opened ];
						o.push("registration");
						this.setState({ opened: o });
					}
				});
			}
		}
	}

	_handle_onCard = (card) => 
	{
		const opened = [ ...this.state.opened ];
		if(opened.indexOf(card) === -1)
		{
			opened.push(card);
		}
		else
		{
			opened.splice(opened.indexOf(card), 1);
		}

		this.setState({ opened: opened });
	}

	_handle_onContract = (url) => 
	{

	}

	_handle_onInvoice = (url) => 
	{

	}

	_checkInsuranceAvailable = () => 
	{
		const { insurance, } = this.state;

		if(insurance !== undefined && insurance !== null)
		{
			for(let i in insurance)
			{
				if(insurance[i] !== undefined && insurance[i] !== null)
				{
					if(insurance[i].length > 0)
					{
						return true;
					}
				}
			}
		}
		return false;
	}

	render()
	{
		const { loading, contracts_info, opened, helpcard, insurance, registration, telematic, } = this.state;
		const { number } = this.props;

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

		console.log("insurance", insurance);

		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>
					<div className="aside_container about">
						<InnerMenu number={ number } status={ status } { ...this.props }/>
						<article>
							{ loading ? (
								<div className="table_row table_header" style={{ minHeight: 300, 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>
							) : (									
								<div className="dropdown_blocks_list zero-margin">
									
									<div className={`dropdown_block ${ opened.indexOf("ratcard") > -1 ? 'open' : '' }`}>
										<div className="block_header" onClick={ () => this._handle_onCard('ratcard') }>
											<p className="with-icon">
												<img src="/assets/images/lk/additional-1.svg" alt="Карта РАТ" width="32px" height="32px"  />
												Карта РАТ
											</p>
											<button className="block_toggle"></button>
										</div>
										{ helpcard !== undefined && helpcard !== null && helpcard.length > 0 ? (
											helpcard.map((entry, index) => (
												<React.Fragment key={ index }>
													{ entry.card_number !== null ? (
														<div className="block_body">
															<div className="company">
																<p className="title">РАТ</p>
																<ul>
																<li>Номер карты: <b>{ entry.card_number }</b></li>
																<li>Тип карты: <b>{ entry.card_type }</b></li>
																<li>Действует до: <b>{ moment(entry.date).format("DD.MM.YYYY") }</b></li>
																</ul>
															</div>
															<>
																{ entry && entry.description && (
																	<p dangerouslySetInnerHTML={{ __html: entry.description.replace(/;/g, ";<br/>") }}/>
																) }
															</>
														</div>
													) : (
														<div className="block_body"><p>Нет данных</p></div>
													) }
												</React.Fragment>
											))
										) : (
											<div className="block_body"><p>Нет данных</p></div>
										) }
									</div>

									<div className={`dropdown_block ${ opened.indexOf("insurance") > -1 ? 'open' : '' }`}>
										<div className="block_header" onClick={ () => this._handle_onCard('insurance') }>
											<p className="with-icon">
												<img src="/assets/images/lk/additional-2.svg" alt="Страхование" width="32px" height="32px"  />
												Страхование
											</p>
											<button className="block_toggle"></button>
										</div>
										{ this._checkInsuranceAvailable() ? (
											<div className="block_body full">
												{ insurance.kasko !== undefined && insurance.kasko !== null && insurance.kasko !== "" && insurance.kasko.map !== undefined && insurance.kasko.map((entry, index) => (
													<React.Fragment key={ index }>
														<div className={ `company ${ entry.period_type === "prolong" && "filled" }` }>
															<p className="title">КАСКО</p>
															<ul>
																{ entry.company && (<li>Страховая компания: <b>{ entry.company }</b></li>) }
																{ entry.site && (<li>Сайт: <b>{ entry.site }</b></li>) }
																{ entry.phone && (<li>Телефон: <b>{ entry.phone }</b></li>) }
																{ entry.number && (
																	<li>Номер полиса: { entry.url !== null ? (<DownloadFileById id={ entry.url } filename={ `${ entry.number }.${ entry.extension}` }>
																			<b style={{ color: "#1C01A9", cursor: "pointer", }}>{ entry.number }</b>
																		</DownloadFileById>
																	) : (<b>{ entry.number }</b>) }
																	</li>
																) }
																{ entry.period && (<li>Период действия: <b>{ entry.period }</b></li>) }
																{ entry.amount && (<li>Страховая сумма: <b style={{ whiteSpace: "nowrap" }}>{ numeral(entry.amount).format(' ., ') }&nbsp;₽</b></li>) }
															</ul>
															{ entry.period_type === "prolong" && entry.invoice_url !== null && (
																<div className="action">
																	<DownloadPdfButton id={ entry.invoice_url } filename={ `${ entry.number }.${ entry.invoice_extension}` } title="Скачать счет на оплату" class={ "services_invoice_button" }/>
																</div>
															) }
														</div>
														{ entry.description && (<p>{ entry.description }</p>) }
													</React.Fragment>
												)) }
												{ insurance.osago !== undefined && insurance.osago !== null && insurance.osago !== "" && insurance.osago.map !== undefined && insurance.osago.map((entry, index) => (
													<React.Fragment key={ index }>
														<div className={ `company ${ entry.period_type === "prolong" && "filled" }` }>
															<p className="title">ОСАГО</p>
															<ul>
																{ entry.company && (<li>Страховая компания: <b>{ entry.company }</b></li>) }
																{ entry.site && (<li>Сайт: <b>{ entry.site }</b></li>) }
																{ entry.phone && (<li>Телефон: <b>{ entry.phone }</b></li>) }
																{ entry.number && (
																	<li>Номер полиса: { entry.url !== null ? (<DownloadFileById id={ entry.url } filename={ `${ entry.number }.${ entry.extension}` }>
																			<b style={{ color: "#1C01A9", cursor: "pointer", }}>{ entry.number }</b>
																		</DownloadFileById>
																	) : (<b>{ entry.number }</b>) }
																	</li>
																) }
																{ entry.period && (<li>Период действия: <b>{ entry.period }</b></li>) }
																{ entry.amount && (<li>Страховая сумма: <b style={{ whiteSpace: "nowrap" }}>{ numeral(entry.amount).format(' ., ') }&nbsp;₽</b></li>) }
																{ entry.period_type === "prolong" && (
																	<li className="alert">Обращаем Ваше внимание, что пролонгация полиса ОСАГО на второй и последующие периоды осуществляется Лизингополучателем самостоятельно</li>
																) }
															</ul>
															{ entry.period_type === "prolong" && entry.invoice_url !== null && (
																<div className="action">
																	<DownloadPdfButton id={ entry.invoice_url } filename={ `${ entry.number }.${ entry.invoice_extension}` } title="Скачать счет на оплату" class={ "services_invoice_button" }/>
																</div>
															) }
														</div>
														{ entry.description && (<p>{ entry.description }</p>) }
													</React.Fragment>
												)) }
												{ insurance.nsib !== undefined && insurance.nsib !== null && insurance.nsib !== "" && insurance.nsib.map !== undefined && insurance.nsib.map((entry, index) => (
													<React.Fragment key={ index }>
														<div className={ `company ${ entry.period_type === "prolong" && "filled" }` }>
															<p className="title">НСИБ</p>
															<ul>
																{ entry.company && (<li>Страховая компания: <b>{ entry.company }</b></li>) }
																{ entry.site && (<li>Сайт: <b>{ entry.site }</b></li>) }
																{ entry.phone && (<li>Телефон: <b>{ entry.phone }</b></li>) }
																{ entry.number && (
																	<li>Номер полиса: { entry.url !== null ? (<DownloadFileById id={ entry.url } filename={ `${ entry.number }.${ entry.extension}` }>
																			<b style={{ color: "#1C01A9", cursor: "pointer", }}>{ entry.number }</b>
																		</DownloadFileById>
																	) : (<b>{ entry.number }</b>) }
																	</li>															
																) }
																{ entry.period && (<li>Период действия: <b>{ entry.period }</b></li>) }
																{ entry.amount && (<li>Страховая сумма: <b style={{ whiteSpace: "nowrap" }}>{ numeral(entry.amount).format(' ., ') }&nbsp;₽</b></li>) }
															</ul>
															{ entry.period_type === "prolong" && entry.invoice_url !== null && (
																<div className="action">
																	<DownloadPdfButton id={ entry.invoice_url } filename={ `${ entry.number }.${ entry.invoice_extension}` } title="Скачать счет на оплату" class={ "services_invoice_button" }/>
																</div>
															) }
														</div>
														{ entry.description && (<p>{ entry.description }</p>) }
													</React.Fragment>
												)) }
												{ insurance.fingap !== undefined && insurance.fingap !== null && insurance.fingap !== "" && insurance.fingap.map !== undefined && insurance.fingap.map((entry, index) => (
													<React.Fragment key={ index }>
														<div className= { `company ${ entry.period_type === "prolong" && "filled" }` }>
															<p className="title">Safe Finance</p>
															<ul>
																{ entry.company && (<li>Страховая компания: <b>{ entry.company }</b></li>) }
																{ entry.site && (<li>Сайт: <b>{ entry.site }</b></li>) }
																{ entry.phone && (<li>Телефон: <b>{ entry.phone }</b></li>) }
																{ entry.number && (
																	<li>Номер полиса: { entry.url !== null ? (<DownloadFileById id={ entry.url } filename={ `${ entry.number }.${ entry.extension}` }>
																			<b style={{ color: "#1C01A9", cursor: "pointer", }}>{ entry.number }</b>
																		</DownloadFileById>
																	) : (<b>{ entry.number }</b>) }
																	</li>
																) }
																{ entry.period && (<li>Период действия: <b>{ entry.period }</b></li>) }
																{ entry.amount && (<li>Страховая сумма: <b style={{ whiteSpace: "nowrap" }}>{ numeral(entry.amount).format(' ., ') }&nbsp;₽</b></li>) }
															</ul>
															{ entry.period_type === "prolong" && entry.invoice_url !== null && (
																<div className="action">
																	<DownloadPdfButton id={ entry.invoice_url } filename={ `${ entry.number }.${ entry.invoice_extension}` } title="Скачать счет на оплату" class={ "services_invoice_button" }/>
																</div>
															) }
														</div>
														{ entry.description && (<p>{ entry.description }</p>) }
													</React.Fragment>
												)) }
											</div>
										) : (
											<div className="block_body"><p>Нет данных</p></div>
										) }
									</div>
									<div className={`dropdown_block ${ opened.indexOf("registration") > -1 ? 'open' : '' }`}>
										<div className="block_header" onClick={ () => this._handle_onCard('registration') }>
											<p className="with-icon">
												<img src="/assets/images/lk/additional-3.svg" alt="Регистрация" width="32px" height="32px" />
												Регистрация
											</p>
											<button className="block_toggle"></button>
										</div>
										{ registration !== undefined && registration !== null && registration.length > 0 ? registration.map((entry, index) => 
										(
											<div className="block_body" key={ index }>
												<div className="company">
													<p className="title">ГИБДД</p>
													<ul>
													{ entry.package && (
														<li>Пакет услуг: <b>{ entry.package }</b></li>
													) }
													{ entry.amount && (
														<li>Стоимость: <b style={{ whiteSpace: "nowrap" }}>{ numeral(entry.amount).format(' ., ') } ₽</b></li>
													) }
													</ul>
												</div>
											</div>
										)) : (
											<div className="block_body"><p>Нет данных</p></div>
										) }
									</div>
									<div className={`dropdown_block ${ opened.indexOf("telematic") > -1 ? 'open' : '' }`}>
										<div className="block_header" onClick={ () => this._handle_onCard('telematic') }>
											<p className="with-icon">
												<img src="/assets/images/lk/additional-4.svg" alt="Телематика" width="32px" height="32px"  />
												Телематика
											</p>
											<button className="block_toggle"></button>
										</div>
										{ telematic !== undefined && telematic !== null && telematic.length > 0 ? telematic.map((entry, index) => 
										(
											<div className="block_body" key={ index }>
												<div className="company">
													<ul style={{ marginLeft: "0px" }}>
													{ entry.provider && (
													<li>Поставщик: <b>{ entry.provider }</b></li>
													) }
													{ entry.equipment && (
														<li>Оборудование: <b>{ entry.equipment }</b></li>
													) }
													{ entry.amount && (
														<li>Стоимость: <b style={{ whiteSpace: "nowrap" }}>{ numeral(entry.amount).format(' ., ') } ₽</b></li>
													) }
													</ul>
												</div>
											</div>
										)) : (
											<div className="block_body"><p>Нет данных</p></div>
										)}
									</div>

								</div>
							) }
						</article>
					</div>
				</AccountLayout>
				<Footer/>
			</React.Fragment>
		);
	}
}

function mapStateToProps(state, ownProps)
{
	return {
		contracts_info: state.contracts_info, 
		date: state.contract.date, 
		car: state.contract.car, 
		helpcard: state.contract.helpcard, 
		insurance: state.contract.insurance, 
		registration: state.contract.registration, 
		telematic: state.contract.telematic, 
	}
}

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

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