import React from "react";
import moment from "moment";
import { SpinnerCircular } from "spinners-react";
import Link from "next/link";

//import EDOSign from "../../../components/EDOSign";

import Step from "./Step";
import DealContractsSignEDO from "./DealContractsSignEDO";
import DealContractsSignPaper from "./DealContractsSignPaper";
import SignPlannedContract from "./SignPlannedContract";
import SignedContract from "./SignedContract";

export default class LeasingRegistration extends Step
{
	constructor(props)
	{
		super(props);
		this.state = {
			open: false, 
			/*
			checked: {
				prepared_contracts: [], 
				signing_plan_contracts: [], 
				signing_fact_contracts: [], 
				issued_contracts: [], 
				annulled_contracts: [], 
			}, 
			*/
			checked: [], 
			edo: false, 
			paper: false, 
		};
		this.status = 107;
		this.types = [
			{
				title: "Подготовлено", 
				key: "prepared_contracts", 
			}, 
			{
				title: "К подписанию", 
				key: "signing_plan_contracts", 
			}, 
			{
				title: "Подписано", 
				key: "signing_fact_contracts", 
			}, 
			{
				title: "Выдано", 
				key: "issued_contracts", 
			}, 
			{
				title: "Аннулировано", 
				key: "annulled_contracts", 
			}, 
		];
		this.container_ref = React.createRef();
	}

	_handle_onScrollToContainer = () => 
	{
		const element = this.container_ref.current;
		const y = (element.getBoundingClientRect().top + window.scrollY - 160);
		window.scrollTo({top: y, behavior: 'smooth'});
	}

	_handle_onPreparedContract = (contract) => 
	{
		const checked = [ ...this.state.checked ];

		if(checked.indexOf(contract) > -1)
		{
			checked.splice(checked.indexOf(contract), 1);
		}
		else
		{
			checked.push(contract);
		}

		this.setState({ checked });
	}

	_handle_onSignEDO = () => 
	{
		this.setState({ edo: true, paper: false }, () => 
		{
			this._handle_onScrollToContainer();
		});
	}

	_handle_onSignPaper = (contract) => 
	{
		this.setState({ edo: false, paper: true }, () => 
		{
			this._handle_onScrollToContainer();
		});
	}

	_onEDOCancel = (clean = false) => 
	{
		if(clean)
		{
			this.setState({ edo: false, checked: [] });
		}
		else
		{
			this.setState({ edo: false });
		}
	}

	_handle_onCancelEDO = () => 
	{
		const { onDealContractsUpdate } = this.props;

		this.setState({ edo: false, checked: [] }, () => 
		{
			onDealContractsUpdate();
		});
	}

	_handle_onFinishEDO = () => 
	{
		const { onDealContractsUpdate } = this.props;

		this.setState({ edo: false, checked: [] }, () => 
		{
			onDealContractsUpdate();
		});
	}

	_handle_onCancelPaper = () => 
	{
		const { onDealContractsUpdate } = this.props;

		this.setState({ paper: false, checked: [] }, () => 
		{
			onDealContractsUpdate();
		});
	}

	_handle_onFinishPaper = () => 
	{
		const { onDealContractsUpdate } = this.props;

		this.setState({ paper: false, checked: [] }, () => 
		{
			onDealContractsUpdate();
		});
	}

	_handle_onGoToEDOInvites = () => 
	{
		console.log("_handle_onGoToEDOInvites", { props: this.props });

		this.props.router.push("/settings/digital");
	}

	_getDocuments = () => 
	{
		const contracts = this.props.contracts['prepared_contracts'];
		const { checked } = this.state;
		const documents = [];

		for(let i in contracts)
		{
			if(checked.indexOf(contracts[i].name) > -1)
			{
				documents.push({
					id: contracts[i].name, 
					name: `Договор № ${ contracts[i].name }`, 
					date: contracts[i].date,
					type: `${ contracts[i].brand_name } ${ contracts[i].model_name }`, 
					extension: 'pdf', 
				})
			}
		}

		return documents;
	}

	_render_preparedContracts = (type) => 
	{
		const { dealSelected } = this.props;
		const { edo, paper, checked } = this.state;
		//const checked = this.state.checked.prepared_contracts;

		const contracts = this.props.contracts['prepared_contracts'];
		console.log("_render_preparedContracts", { contracts });

		if(edo)
		{
			return (
				<DealContractsSignEDO 
					documents={ this._getDocuments() } 
					onCancel={ this._handle_onCancelEDO } 
					onFinish={ this._handle_onFinishEDO } 
					onGoToEDOInvites={ this._handle_onGoToEDOInvites } 
				/>
			)
		}

		if(paper)
		{
			return (
				<DealContractsSignPaper 
					deal_id={ dealSelected } 
					documents={ this._getDocuments() } 
					onCancel={ this._handle_onCancelPaper } 
					onFinish={ this._handle_onFinishPaper } 
				/>
			)
		}

		return (
			<div className="block deal_contracts_group_item" key={ type.key }>
				{ !edo && ( <div className="left"><p><b>{ type.title }</b></p></div> )}
				<div className="right" style={ edo ? { width: "100%" } : {} }>
					<div className="block-column">
						<div className={ `${ contracts.length === 0 ? "documents" : ""} docs_list acts_list-checkbox medium-icon` }>
							{ contracts.length > 0 ? 
								contracts.map((contract, index) => (
									<div className="row" key={ index }>
										<div className="doc_name i-doc i-medium blue deals_contracts" style={{ alignItems: "flex-start" }}>
											<input type="checkbox" name="" id={ `contract_${ index }` } checked={ checked.indexOf(contract.name) > -1 ? true : false } onChange={ () => { this._handle_onPreparedContract(contract.name) } }/>
											<label htmlFor={ `contract_${ index }` }>№{ contract.name }</label>
											<div className="info">
												<span>{ moment(contract.date).format('MM.DD.YYYY') }</span>
												<span>{ contract.brand_name }</span>
												<span>{ contract.model_name }</span>
											</div>
										</div>
									</div>
							)) : (
								<p className="empty">Нет договоров</p>
							) }
						</div>
						{ contracts.length > 0 && 
						(
							<div className="block_footer_btn">
								<button className="button button-blue" onClick={ this._handle_onSignEDO } disabled={ checked.length > 0 ? false : true }>Подписать в ЭДО</button>
								<button className="button button-blue" onClick={ this._handle_onSignPaper } disabled={ checked.length > 0 ? false : true }>Подписать в бумажном виде</button>
							</div>
						) }
					</div>
				</div>
			</div>
		)
	}

	_render_signingPlanContracts = (type) => 
	{
		const contracts = this.props.contracts['signing_plan_contracts'];
		const { onDealContractsUpdate, dealSelected } = this.props;
		console.log("_render_signingPlanContracts", { contracts });

		return (
			<div className="block deal_contracts_group_item" key={ type.key }>
				<div className="left"><p><b>{ type.title }</b></p></div>
				<div className="right">
					<div className="documents deal_contract_sign_list">
						{ contracts.length > 0 ? 
							contracts.map((contract, index) => (
								<SignPlannedContract 
									key={ `SignPlannedContract_${ contract.name }` } 
									index={ index } 
									contract={ contract } 
									deal_id={ dealSelected } 
									onDealContractsUpdate={ onDealContractsUpdate } 
								/>
							)
						) : (
							<p className="empty">Нет договоров</p>
						) }
					</div>
				</div>
			</div>
		)
	}

	_render_signingFactContracts = (type) => 
	{
		const contracts = this.props.contracts['signing_fact_contracts'];
		console.log("_render_signingFactContracts", { contracts });

		return (
			<div className="block deal_contracts_group_item" key={ type.key }>
				<div className="left"><p><b>{ type.title }</b></p></div>
				<div className="right">
					<div className="documents">
						{ contracts.length > 0 ? 
							contracts.map((contract, index) => (
								<SignedContract 
									key={ `SignedContract_${ contract.name }` } 
									index={ index } 
									contract={ contract } 
								/>
							)
						) : (
							<p className="empty">Нет договоров</p>
						) }
					</div>
				</div>
			</div>
		)
	}

	_render_issuedContracts = (type) => 
	{
		const contracts = this.props.contracts['issued_contracts'];
		console.log("_render_issuedContracts", { contracts });

		return (
			<div className="block deal_contracts_group_item" key={ type.key }>
				<div className="left"><p><b>{ type.title }</b></p></div>
				<div className="right">
					<div className="documents">
						{ contracts.length > 0 ? 
							contracts.map((contract, index) => (
								<div className="document" key={ index }>
									<div className="icon formal"></div>
									<div className="title">
										<p><Link href={`/contract/${ contract.name }/payments`}><a>{ contract.name }</a></Link></p>
										<div className="description">
											<span>{ moment(contract.date).format("DD.MM.YYYY") }</span>
											<span>{ contract.brand_name }</span>
											<span>{ contract.model_name }</span>
										</div>
									</div>
								</div>
						)) : (
							<p className="empty">Нет договоров</p>
						) }
					</div>
				</div>
			</div>
		)
	}

	_render_annuledContracts = (type) => 
	{
		const contracts = this.props.contracts['annulled_contracts'];
		console.log("_render_annuledContracts", { contracts });

		if(contracts.length > 0)
		{
			return (
				<div className="block deal_contracts_group_item" key={ type.key }>
					<div className="left"><p><b>{ type.title }</b></p></div>
					<div className="right">
						<div className="documents">
							{ contracts.map((contract, index) => (
									<div className="document" key={ index }>
										<div className="icon formal"></div>
										<div className="title">
											<p>{ contract.name }</p>
											<div className="description">
												<span>{ moment(contract.date).format("DD.MM.YYYY") }</span>
												<span>{ contract.brand_name }</span>
												<span>{ contract.model_name }</span>
											</div>
										</div>
									</div>
							)) }
						</div>
					</div>
				</div>
			)
		} else {
			return null;
		}
	}

	_render_contracts = (type) => 
	{
		const { contracts } = this.props;

		if(contracts !== undefined)
		{
			switch (type.key)
			{
				case "prepared_contracts":
				{
					return this._render_preparedContracts(type);
				}

				case "signing_plan_contracts":
				{
					return this._render_signingPlanContracts(type);
				}

				case "signing_fact_contracts":
				{
					return this._render_signingFactContracts(type);
				}

				case "issued_contracts":
				{
					return this._render_issuedContracts(type);
				}

				case "annulled_contracts":
				{
					return this._render_annuledContracts(type);
				}
			}
		}
		else
		{
			return null;
		}
	}

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

		return (
			<div className={`${ this.status === statuscode_id ? "current" : statuscode_id > this.status ? "done" : "" }`} ref={ this.container_ref }>
				<p>№ { dealSelected }</p>
				<span></span>
				<div className="status_body">
					{ this._renderHeader("Оформление лизинга") }
					<div className="wrap form contracts" style={{ display: open ? "block" : "none" }}>
						{ this.props.contracts === undefined ? (
							<div style={{ minHeight: 200, 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>
						) : 
							this.types.map((type, index) => this._render_contracts(type) ) 
						}
					</div>
				</div>
			</div>
		)
	}
}