import * as React from "react";
import { RecordService, CachingService } from "../../../../Services";
// import { FieldTypes } from "../../../../Enums"
import { IColumn } from "office-ui-fabric-react/lib/DetailsList";
import {
  Breadcrumb,
  Dialog,
  DialogType,
  DialogFooter,
  PrimaryButton,
  getId
} from "office-ui-fabric-react/lib";
// import { Panel, PanelType, PrimaryButton, DefaultButton } from 'office-ui-fabric-react/lib';
// import { Record, Command, ListRecordsCriteria, WorkflowAction, WorkflowHistory } from '../../../../Models';
import { RouteComponentProps } from "react-router";
import "./RecordsList.css";
import RecordWizardControl from "src/Controls/RecordWizardControl";
// import { DateUtils } from '../../../../Utils';
// import { RecordsListView } from '../../../../Controls/RecordsListView';
// import { Sorting } from "../../../../Models/Sorting";
// import { Pagination } from "../../../../Models/Pagination";
import { ToastContainer, toast } from "react-toastify";
import { Record } from "../../../../Models";

import "react-toastify/dist/ReactToastify.min.css";
import { LoadingService } from "src/Services/LoadingService";
import { FormattedMessage } from "react-intl";
import { WorkflowAction } from "src/Models";
import WorkflowActions from "src/Controls/WorkflowActions/WorkflowActions";

export interface IData {
  columns: IColumn[];
  items: any[];
}

export class RecordWizard extends React.Component<
  {} & RouteComponentProps<{ id: number }>,
  any
  > {
  notifySuccess = (msg: any) => {
    toast.success(msg, {
      position: toast.POSITION.TOP_RIGHT
    });
  };
  notifyError = (msg: any) => {
    toast.error(msg, {
      position: toast.POSITION.TOP_RIGHT
    });
  };
  private _recordService = new RecordService();
  private _loadingService = new LoadingService();
  private workflowActions: WorkflowActions;
  private _cachingService = new CachingService();
  private _notAuthenticated = true;
  private _labelId: string = getId("dialogLabel");
  private _subTextId: string = getId("subTextLabel");

  constructor(props: {} & RouteComponentProps<{ id: number }>) {
    super(props);

    this._notAuthenticated =
      !this._cachingService.read("Token") ||
      this._cachingService.read("Token") == "";
    if (this._notAuthenticated) return;

    let cachingService: CachingService = new CachingService();
    let params = cachingService.read("Params");

    this.state = {
      record: {},
      entityId: params.entityId,
      hideDialogTransferSuccess: true
    };

    this._getRecord(props.match.params.id);
  }

  _saveRecord(record: any) {
    // let _this = this;
    this._loadingService.show();
    let _this = this;
    //debugger;
    return this._recordService.saveRecord(record).then(
      result => {
        this.notifySuccess(this._cachingService.readPersistant("Language") == 0 ?"Saved Succesfully":"تم الحفظ");
        this._loadingService.hide();
        this._loadingService.hide();
        this._loadingService.hide();
        // this.props.history.push('/dashboard');
        this.setState({ hideDialogTransferSuccess: false });
        setTimeout(() => {
          _this._closeDialogDialogTransferSuccess();
        }, 3000);
        return result;
      },
      err => {
        // err.response.data
        this._loadingService.hide();
        this.notifyError(err.response.data);
      }
    );
  }

  _getRecord(recordId: number) {
    let _this = this;
    this._loadingService.show();
    let props: any = this.props;
    let templateId = props.createMeeting_TemplateId;

    if (recordId > 0) {
      this._recordService.getRecord(this.state.entityId, recordId)
        .then(result => {



          this.setState({ record: result });
          this._loadingService.hide();
        },
          error => {
            this._loadingService.hide();
          })
        .catch(err => {
          _this._loadingService.hide();
        });

    }
    else if (templateId)
      this._recordService
        .getEmptyRecordForMeeting(this.state.entityId, templateId)
        .then(
          result => {
            this.setState({ record: result });
            this._loadingService.hide();
          },
          err => {
            this._loadingService.hide();
          }
        )
        .catch(err => {
          _this._loadingService.hide();
        });
    else
      this._recordService
        .getEmptyRecord(this.state.entityId)
        .then(
          result => {
            this.setState({ record: result });
            this._loadingService.hide();
          },
          err => {
            this._loadingService.hide();
          }
        )
        .catch(err => {
          _this._loadingService.hide();
        });
  }
  private ExecuteAction(record: Record, action: WorkflowAction) {
    if (action.id == 7) {
      // show your modal
      this.workflowActions.showActionModal();
    } else {
      this._recordService
        .executeAction(action.id, record.entityId, record)
        .then(
          result => {
            this.notifySuccess("Done Succesfully");
            this._loadingService.hide();
            this.props.history.push("/dashboard");
          },
          error => {
            alert(error);
          }
        );
    }
  }

  public render(): JSX.Element {
    return (
      <div>
        {!this._notAuthenticated && (
          <div>
            <div className="breadcrumb-container">
              <i className="iconsmind-Mail-Add" />
              <Breadcrumb
                items={[{ text: "Create", key: "Create" }]}
                ariaLabel={"Website breadcrumb"}
                onRenderItem={this._onRenderItem}
              />
            </div>

            <div className="ms-Grid-row">
              <div className="ms-Grid-col ms-lg12">
                <div className="layout-card form-card">
                  <RecordWizardControl
                    history={this.props.history}
                    record={this.state.record}
                    saveRecord={this._saveRecord.bind(this)}
                    ExecuteAction={this.ExecuteAction.bind(this)}
                  />
                </div>
              </div>
            </div>
            <ToastContainer />
            <WorkflowActions
              onRef={(ref: any) => (this.workflowActions = ref)}
            />
          </div>
        )}
        <Dialog
          hidden={this.state.hideDialogTransferSuccess}
          onDismiss={this._closeDialogDialogTransferSuccess.bind(this)}
          dialogContentProps={{
            type: DialogType.normal,
            title:
              this._cachingService.readPersistant("Language") == 1
                ? "تم إرسال الرسالة بنجاح"
                : "Message was sent successfully"
          }}
          modalProps={{
            titleAriaId: this._labelId,
            subtitleAriaId: this._subTextId,
            isBlocking: false,
            containerClassName: "ms-dialogMainOverride"
          }}
        >
          <DialogFooter>
            <PrimaryButton
              onClick={this._closeDialogDialogTransferSuccess.bind(this)}
            >
              {" "}
              <FormattedMessage id="OK" />
            </PrimaryButton>
            {/* <DefaultButton onClick={this._closeDialog} text="Cancel" /> */}
          </DialogFooter>
        </Dialog>
      </div>
    );
  }
  private _closeDialogDialogTransferSuccess() {
    this.setState({ hideDialogTransferSuccess: true });
    this.props.history.push("/dashboard");
  }
  private _onRenderItem = (item: any): JSX.Element | null => {
    // debugger;
    return <FormattedMessage id={item.text} />;
  };
}
