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

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

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

import { getContractsList, getReconciliationFile } from '../../actions';

import { eachSeries } from "async";
import AccountLayout from "../components/Layout/Account";


class ReconciliationsPage extends React.Component 
{
	constructor(props)
	{
		super(props);
		this.state = {
			loading: false, 
			contracts: null, 
			checked: [], 
			checked_all: true, 
			valid_date_start: null, 
			valid_date_end: null, 
			period_date_start: null, 
			period_date_end: null, 
			reconciliation_requested: false, 
		}
	}

	static getDerivedStateFromProps(nextProps, prevState)
	{
		return {
			contracts: nextProps.contracts, 
		};
	}

	componentDidMount()
	{
		this.setState({ loading: true }, () => 
		{
			getContractsList({ dispatch: this.props.dispatch, all: true }).then(() => {
				this.setState({ loading: false });
			}).catch(() => {});
		});
	}

	componentDidUpdate(prevProps, prevState)
	{
		if(prevState.contracts === null && this.state.contracts !== null)
		{
			const ds = this.state.contracts.length > 0 ? moment(this.state.contracts[ this.state.contracts.length-1 ].date).toDate() : moment().toDate();
			const de = moment().toDate();

			this.setState({ 
				period_date_start: ds, 
				period_date_end: de, 
				valid_date_start: ds, 
				valid_date_end: de, 
			});
		}
	}

	_handle_onAllContracts = () => 
	{
		this.setState({ checked_all: this.state.checked_all ? false : true, checked: this.state.checked ? [] : this.state.checked });
	}

	_handle_onContract = (number) => 
	{
		const { checked_all, contracts } = this.state;
		const checked = [ ...this.state.checked ];

		if(checked_all)
		{
			for(let i in contracts)
			{
				if(contracts[i].number !== number)
				{ 
					checked.push(contracts[i].number); 
				}
			}

			this.setState({ checked_all: false, checked: checked });
		}
		else
		{
			if(checked.indexOf(number) < 0)
			{ checked.push(number); }
			else
			{ checked.splice(checked.indexOf(number), 1); }

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

	_handle_onPeriodDate_start = (date) => 
	{
		const { valid_date_start, valid_date_end, period_date_start, period_date_end } = this.state;
		const md = moment(date, "DD.MM.YYYY");

		if(md.isValid())
		{
			if(date >= valid_date_start && date <= valid_date_end)
			{
				if(date < period_date_end)
				{
					this.setState({ period_date_start: date, reconciliation_disabled: false });
				}
				else
				{
					this.setState({ period_date_start: date, reconciliation_disabled: true });	
				}
			}
			else
			{
				this.setState({ period_date_start: date, reconciliation_disabled: true });	
			}
		}
		else
		{
			console.log("invalid date", md);
			this.setState({ reconciliation_disabled: true });
		}
	}

	_handle_onPeriodDate_end = (date) => 
	{
		const { valid_date_start, valid_date_end, period_date_start, period_date_end } = this.state;

		if(moment(date).isValid())
		{
			if(date >= valid_date_start && date <= valid_date_end)
			{
				if(date > period_date_start)
				{
					this.setState({ period_date_end: date, reconciliation_disabled: false });
				}
				else
				{
					this.setState({ period_date_end: date, reconciliation_disabled: true });	
				}
			}
			else
			{
				this.setState({ period_date_end: date, reconciliation_disabled: true });	
			}
		}
		else
		{
			this.setState({ reconciliation_disabled: true });
		}
	}

	_handle_onReconciliationFiles = () => 
	{
		const { checked, checked_all, contracts, reconciliation_requested, period_date_start, period_date_end, } = this.state;

		let list = [];
		if(!reconciliation_requested)
		{
			if(checked_all)
			{
				for(let i in contracts)
				{
					list.push(contracts[i].number);
				}
			}
			else
			{
				list = checked;
			}

			console.log(list);

			const date_from = moment(period_date_start).format("YYYY-MM-DD");
			const date_to = moment(period_date_end).format("YYYY-MM-DD");

			this.setState({ reconciliation_requested: true }, () => 
			{
				eachSeries(list, (number, callback) =>
				{
					getReconciliationFile({ 
						contract: number, 
						date_from: date_from, 
						date_to: date_to, 
						filename: `${ number }_reconciliation_${ date_from }_${ date_to }.pdf`, 
					})
					.then(() => 
					{
						callback();
					})
					.catch(() => 
					{
						callback();
					});
	
				}, () => 
				{
					this.setState({ reconciliation_requested: false });
				});
			});
		}
	}

	render()
	{
		const { loading, contracts, checked, checked_all, valid_date_start, valid_date_end, period_date_start, period_date_end, reconciliation_disabled, reconciliation_requested } = this.state;

		return (
			<React.Fragment>
				<Head>
					<title>ЛК Эволюция автолизинга</title>
					<meta
						name="description"
						content="ЛК Эволюция автолизинга"
					/>
				</Head>
				<Header { ...this.props }/>
				<AccountLayout>
					<div className="title_wrapper">
						<div className="left">
							<h1 className="section_title">Акты сверок</h1>
						</div>
						<Company { ...this.props }/>
					</div>
					<div className="aside_container about">
						<InnerMenu { ...this.props }/>
						<article>
							<div className="acts_wrapper" style={{ flex: 1, justifyContent: "center" }}>
								{ 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>
								) : (
									<>
										{ contracts !== undefined && contracts !== null && contracts.length > 0 ? (
											<>
												<div className="dosc_list acts_list-checkbox">
													<div className="row">
														<p className="doc_name">
															<input type="checkbox" name="all" id="all" checked={ checked_all } onChange={ this._handle_onAllContracts } />
															<label htmlFor="all">Все договоры</label>
														</p>
													</div>
													{ contracts !== undefined && contracts !== null && contracts.map((contract, index) => (
														<div className="row" key={ index }>
															<p className="doc_name i-pdf">
																<input type="checkbox" checked={ checked_all || checked.indexOf(contract.number) > -1 } name={ `contract_${ contract.number }` } id={ `contract_${ contract.number }` } onChange={ () => this._handle_onContract(contract.number) }/>
																<label htmlFor={ `contract_${ contract.number }` }>№{ contract.number } от { moment(contract.date).format("DD.MM.YYYY") }</label>
															</p>
														</div>
													)) }
												</div>
												<div className="reconciliation_form small" style={{ alignContent: "flex-start" }}>
													<div className="form_field">
														<DateInput placeholder="Дата начала периода" value={ period_date_start } min={ valid_date_start } max={ valid_date_end } onChange={ this._handle_onPeriodDate_start }/>
													</div>
													<div className="form_field">
														<DateInput placeholder="Дата окончания периода" value={ period_date_end } min={ valid_date_start } max={ valid_date_end } onChange={ this._handle_onPeriodDate_end }/>
													</div>
													<button className="button button-blue" disabled={ reconciliation_disabled } onClick={ () => { this._handle_onReconciliationFiles() }}>
														<>
															{ reconciliation_requested ? (
																<SpinnerCircular size={24} thickness={100} speed={100} color="rgba(255, 255, 255, 1)" secondaryColor="rgba(255, 255, 255, 0.5)" />
															) : "Скачать" }
														</>
													</button>
													{/*<button className="button button-blue">Отправить в ЭДО</button>*/}
												</div>
											</>
										) : (
											<p>Нет договоров для запроса актов сверок</p>
										) }
									</>
								) }
							</div>
						</article>
					</div>
				</AccountLayout>
				<Footer/>
			</React.Fragment>
		)
	}
}

function mapStateToProps(state, ownProps)
{
	return {
		contracts: state.contracts.list, 
	}
}

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

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