import React from "react";
import numeral from "numeral";
import { SpinnerCircular } from "spinners-react";

import { acceptDealOffers, downloadDealOffer, } from "../../../actions";
import Step from "./Step";

class OfferDownload extends React.Component
{
	constructor(props)
	{
		super(props);
		this.state = {
			loading: false, 
		}
	}

	_handle_onOffer = (quote_number) => 
	{
		this.setState({ loading: true }, () => 
		{
			downloadDealOffer({ quote_number, filename: `ЛК Эволюция КП №${ quote_number }.pdf` })
			.then(() => {
				this.setState({ loading: false });
			})
			.catch(() => {
				this.setState({ loading: false });
			});
		})
	}
	
	render()
	{
		const { offer } = this.props;
		const { loading } = this.state;

		return (
			<div className="docs_list" style={{ cursor: "pointer" }} onClick={ () => this._handle_onOffer(offer.quote_number) }>
				<div className="row">
					<div className="small-icon">
						{ loading ? (
							<div style={{ width: "105px", height: "30px", display: "flex", alignItems: "center", justifyContent: "center", }}>
								<SpinnerCircular size={ 22 } thickness={ 100 } speed={ 100 } color="rgba(236, 239, 244, 1)" secondaryColor="rgba(28, 1, 169, 1)" />
							</div>
						) : (
							<p className="doc_name i-pdf">
								КП
								<span>№{ offer.quote_number }</span>
							</p>
						) }
					</div>
				</div>
			</div>
		)
	}
}

export default class Offers extends Step
{
	constructor(props)
	{
		super(props);
		this.state = {
			open: false, 
			loading: false, 
			checked: [], 
		};
		this.status = 100;
	}

	_handle_onCheckOffer = (quote_number) => 
	{
		const checked = [ ...this.state.checked ];
		let is_new = true;

		if(checked.indexOf(quote_number) > -1)
		{
			checked.splice(checked.indexOf(quote_number), 1);
			is_new = false;
		}

		if(is_new)
		{
			checked.push(quote_number);
		}

		this.setState({ checked });
	}

	_handle_onSend = (event) => 
	{
		event.preventDefault();
		event.stopPropagation();

		this.setState({ loading: true }, () => 
		{
			const { checked } = this.state;
			const { dealSelected, onDealsUpdate } = this.props;
			const offers = [];

			for(let i in checked)
			{
				offers.push({
					quote_number: checked[i], 
					agreed: true, 
				});
			}

			acceptDealOffers({ deal_id: dealSelected, offers })
			.then(() => 
			{
				onDealsUpdate()
				.then(() => 
				{
					this.setState({ loading: false });	
				})
				.catch(() => 
				{
					this.setState({ loading: false });	
				});
			})
		});
	}

	/*
	_renderHeaderButtons = () => 
	{
		const { open, checked, loading } = this.state;
		const { statuscode_id } = this.props;

		if(statuscode_id === this.status)
		{
			if(!loading && open && checked.length > 0)
			{
				return (
					<div className="buttons">
						<button className="button button button-blue" onClick={ this._handle_onSend }>Согласовать</button>
					</div>
				)
			}
		}

		return null;
	}
	*/

	render()
	{
		const { index, statuscode_id, dealSelected, offers } = this.props;
		const { checked, open, loading } = this.state;

		return (
			<div className={`${ this.status === statuscode_id ? "current" : statuscode_id > this.status ? "done" : "" }`}>
				<p>№ { dealSelected }</p>
				<span></span>
				<div className="status_body with_footer">
					{ this._renderHeader("Выбор КП ") }
					<div className="wrap" style={{ display: open ? "block" : "none" }}>
						{ offers === undefined || loading ? (
							<div style={{ minHeight: 100, display: "flex", justifyContent: "center", alignItems: "center", }}>
								<SpinnerCircular size={ 50 } thickness={ 51 } speed={ 100 } color="rgba(28, 1, 169, 1)" secondaryColor="rgba(236, 239, 244, 1)" />
							</div>
						) : (
							<>
								{ offers.length > 0 ? (
									<table className="deal_offers_table">
										<thead>
											<tr>
												<th></th>
												<th>№</th>
												<th>Стоимость</th>
												<th>Первый платеж, ₽</th>
												<th>Первый платеж, %</th>
												<th>Марка</th>
												<th>Модель</th>
												<th>Объектов лизинга</th>
												<th></th>
											</tr>
										</thead>
										<tbody>
											{ offers.map((offer, offer_index) => 
											{ 
												return (
													<tr key={ offer_index }>
														{ statuscode_id === this.status && offer.quote_status ? (
															<td>
																<div className="form_field checkbox offer_selection">
																	<input type="checkbox" name="row" id={`offer_${ offer.quote_number }`} checked={ checked.indexOf(offer.quote_number) > -1 } onChange={ () => { this._handle_onCheckOffer(offer.quote_number) } }/>
																	<label htmlFor={`offer_${ offer.quote_number }`} data-text={`Выбрать коммерческое предложение`}></label>
																</div>
															</td>
														) : (
															<td>
																<div className="form_field checkbox checkbox_disabled">
																	<input type="checkbox" name="row" id={`offer_${ offer.quote_number }`} checked={ true } onChange={ () => { } } style={{ filter: "grayscale", opacity: 0.5 }}/>
																	<label htmlFor={`offer_${ offer.quote_number }`} data-text={`Принято`}></label>
																</div>
															</td>
														) }
														<td data-title="№">{ offer_index + 1 }</td>
														<td data-title="Стоимость">{ numeral(offer.price).format(' ., ') } ₽</td>
														<td data-title="Первый платеж, ₽">{ numeral(offer.first_payment_rub).format(' ., ') } ₽</td>
														<td data-title="Первый платеж, %">{ offer.first_payment_perc }%</td>
														<td data-title="Марка">{ offer.brand_name }</td>
														<td data-title="Модель">{ offer.model_name }</td>
														<td data-title="Объектов лизинга">{ offer.object_count }</td>
														<td>
															<OfferDownload offer={ offer }/>
														</td>
													</tr>
												)
											} ) }
										</tbody>
									</table>
								) : (
									<p>Нет предложений</p>
								) }
							</>
						) }
					</div>
					{ open && !loading && (
						<div className="status_footer">
							{ checked.length > 0 &&  statuscode_id === this.status && (
								<div className="buttons">
									<button className="button button button-blue" onClick={ this._handle_onSend }>Согласовать</button>
								</div>
							) }
						</div>
					) }
				</div>
			</div>
		)
	}
}