import * as React from "react";
import { DefaultButton, PanelType, Panel, IconButton } from 'office-ui-fabric-react';
import { WorkflowService, RecordService } from "../Services";
import { LoadingService } from "../Services/LoadingService";
import { PrimaryButton } from "../Customizations/Controls/PrimaryButton";
import { FormattedMessage } from "react-intl";
import { FieldsControl } from "./FieldsControl";
import { DynamicRecordService } from "../Services/DynamicRecordService";

export class ExecuteActionButton extends React.Component<any, any> {

    private _loadingService = new LoadingService();
    private _workflowService: WorkflowService = new WorkflowService();
    private _recordService: RecordService = new RecordService();
    private _dynamicRecordService: DynamicRecordService = new DynamicRecordService();

    constructor(props: any) {
        super(props);
        this.state = {
            disabled: false,
            showFillInputParametersPanel: false
        };
    }

    private executeWorkflowAction() {

        if (this.props.workflowAction.actionToExecute) {
            this.props.workflowAction.actionToExecute();
            return;
        }

        if (this.props.workflowAction.needsInputParameters == true) {
            this.showFillInputParametersPanel();
            return;
        }

        this._executeWorkflowAction();
    }

    private _executeWorkflowAction(inputParameters: any = null) {
        this._loadingService.show();

        this._workflowService.executeAction(
            {
                entityId: this.props.entityId.toString(),
                entityType: 0,
                recordId: this.props.recordId.toString(),
                actionId: this.props.workflowAction.id,
                inputParameters: inputParameters
            }).then(
                (result: any) => {

                    console.log(result);

                    if (this.props.onExecute)
                        this.props.onExecute();

                    this._loadingService.hide();
                },
                error => {
                    // alert(error.text());
                    // this.toastr.error('', error.text());
                    //this.displayAlertModal(error.text());
                    alert(error);
                    this._loadingService.hide();
                }
            );
    }

    private showFillInputParametersPanel() {
        this._recordService.getEmptyRecord(this.props.workflowAction.actionInputParametersCustomEntityId)
            .then(result => {
                // debugger;
                this.setState({ emptyInputParameters: result, showFillInputParametersPanel: true });
            }, error => {
                alert(error);
            });
    }

    private closeFillInputParametersPanel() {
        this.setState({ showFillInputParametersPanel: false });
    }

    private executeActionWithInputParameters(button: any) {
        if (button && button.block) button.block();

        this._loadingService.show();

        //debugger;
        this._recordService.saveRecord(this.state.emptyInputParameters)
            .then(result => {

                if (button && button.unblock) button.unblock();

                let recordId: any = result.data;

                this._dynamicRecordService.getRecord(this.props.workflowAction.actionInputParametersCustomEntityId, recordId)
                    .then(result => {

                        if (button && button.unblock) button.unblock();

                        this._loadingService.hide();

                        this.closeFillInputParametersPanel();
                        this._executeWorkflowAction(JSON.stringify(result));


                    }, error => {
                        if (button && button.unblock) button.unblock();
                        this._loadingService.hide();
                        alert(error);
                    });

            }, error => {
                if (button && button.unblock) button.unblock();
                this._loadingService.hide();
                alert(error);
            });

    };

    private renderFillInputParametersPanelFooterContent = (): JSX.Element => {
        return (
            <div className="sticky-footer-btns">
                <PrimaryButton
                    onClick={this.executeActionWithInputParameters.bind(this)}
                    className="panel-footer-btn">
                    <FormattedMessage id="Execute" />
                </PrimaryButton>
                <DefaultButton className="panel-footer-btn" onClick={() => { return this.closeFillInputParametersPanel() }}>
                    <FormattedMessage id="Cancel" />
                </DefaultButton>
            </div>
        );
    }

    private renderFillInputParametersPanelBody = (): JSX.Element => {
        return (
            <div>
                <FieldsControl
                    Record={this.state.emptyInputParameters}
                    fields={this.state.emptyInputParameters.fields}
                    // onSubmit={this.handleSubmit.bind(this)}
                    actions={this.state.emptyInputParameters.actions}
                    // onRef={(ref: any) => (this.fieldsControl = ref)} 
                    panelMode={true} />
            </div>)
    }

    private _onReadnderHader = (item: any): JSX.Element | null => {
        return (
            <div className="ms-Panel-commands" data-is-visible="true">
                <div className="ms-Panel-navigation navigation_1033a520">
                    <h2 className="panel-header-text ">
                        <FormattedMessage id={item.headerText} />
                    </h2>
                    <IconButton
                        className="ms-Panel-closeButton ms-PanelAction-close custom"
                        onClick={item.onDismissed.bind(this)}
                        iconProps={{ iconName: "ChromeClose", style: { fontSize: 12 } }}
                    />
                </div>
            </div>
            // <div className="panel-header-text "><FormattedMessage id={item.headerText} /></div>
        );
    };

    render() {
        //{this.pros}
        return (
            <div style={{ "float": "left" }}>
                {
                    this.props.buttonType == 'primary' ?
                        <PrimaryButton onClick={this.executeWorkflowAction.bind(this)}
                            {...this.props} />
                        :
                        <DefaultButton onClick={this.executeWorkflowAction.bind(this)}
                            {...this.props} />
                }

                {this.props.workflowAction.needsInputParameters == true &&
                    <Panel
                        className="panelStyle"
                        isOpen={this.state.showFillInputParametersPanel}
                        onDismissed={this.closeFillInputParametersPanel.bind(this)}
                        type={PanelType.medium}
                        onRenderFooter={this.renderFillInputParametersPanelFooterContent.bind(this)}
                        onRenderBody={this.renderFillInputParametersPanelBody.bind(this)}
                        headerText={this.props.workflowAction.displayName_En}
                        isFooterAtBottom={true}
                        //styles={{ IsFooterSticky: true }}
                        headerClassName="panelHeaderStyle"
                        hasCloseButton={false}
                        isBlocking={true}
                        onRenderHeader={this._onReadnderHader}
                    ></Panel>
                }
            </div>
        );
    }
}

// export default NewPrimaryButton;
