import * as React from "react";
import { TextField } from "office-ui-fabric-react/lib/components/TextField";
import { Label } from "office-ui-fabric-react/lib/components/Label";
import { Dropdown } from "office-ui-fabric-react/lib/components/Dropdown";
import { Checkbox } from "office-ui-fabric-react/lib/components/Checkbox";
import { Image } from "office-ui-fabric-react/lib/Image";
import {
  Record,
  RecordField,
  WorkflowAction,
  Command,
  ListRecordsCriteria
} from "../Models";
import { FileService, RecordService, CachingService } from "../Services";
import { FieldTypes } from "../Enums";
import { DatePicker } from "office-ui-fabric-react/lib/components/DatePicker/DatePicker";
import { ChoiceGroup } from "office-ui-fabric-react/lib/components/ChoiceGroup/ChoiceGroup";
import "./FormDisplay.css";
import {
  Link,
  Callout,
  IconButton,
  createRef,
  ComboBox,
  PrimaryButton,
  Panel,
  PanelType,
  IDatePickerStrings
} from "office-ui-fabric-react";
import { RecordsListView} from "./RecordsListView";
import { CommandsBar } from "./CommandsBar";
import {  MultipleFileUpload } from "./MultipleFileUpload";
// import ReactQuill from "react-quill";
// import 'react-quill/dist/quill.snow.css';
import { Editor } from "react-draft-wysiwyg";
import {
  convertToRaw,
  EditorState,
  convertFromHTML,
  ContentState
} from "draft-js";
import draftToHtml from "draftjs-to-html";
import "react-draft-wysiwyg/dist/react-draft-wysiwyg.css";
import { CorrespondenceTransfer } from "../Models/CorrespondenceTransfer";
import { FormattedMessage } from "react-intl";
import { OrganizationalUnitsTreeComboBox } from "./OrganizationalUnitsTreeComboBox";
import { PrimaryButton as NewPrimaryButton } from "../Customizations/Controls/PrimaryButton";

export class FormDisplay extends React.Component<any, any> {
  [x: string]: any;

  private _fileService: FileService = new FileService();
  private _recordService: RecordService = new RecordService();
  private _menuButtonElement = createRef<HTMLElement>();
  private _cachingService: CachingService = new CachingService();
  private _loggedInUser: any;
  private datepickerStrings: IDatePickerStrings;

  constructor(props: any) {
    super(props);

    this._loggedInUser = this._cachingService.read("LoggedInUser");

    this.state = {
      isCalloutVisible: false,
      commands: new Array<Command>(),
      selectedCorrespondenceTransfer: new CorrespondenceTransfer(),
      reasonLookups: [
        { id: 0, value: "option 1" },
        { id: 1, value: "option 2" },
        { id: 2, value: "option 3" }
      ]
    };
    if (this._cachingService.readPersistant("Language") != 1) {
      this.datepickerStrings = {
        days: [
          "Sunday",
          "Monday",
          "Tuesday",
          "Wednsday",
          "Thursday",
          "Friday",
          "Saturday"
        ],
        goToToday: "Go to today",
        months: [
          "January",
          "February",
          "March",
          "April",
          "May",
          "June",
          "July",
          "August",
          "September",
          "October",
          "November",
          "December"
        ],
        shortDays: ["S", "M", "T", "W", "T", "F", "S"],
        shortMonths: [
          "Jan",
          "Feb",
          "Mar",
          "Apr",
          "May",
          "June",
          "July",
          "Aug",
          "Sept",
          "Oct",
          "Nov",
          "Dec"
        ]
      };
    } else {
      this.datepickerStrings = {
        days: [
          "الاحد",
          "الاثنين",
          "الثلاثاء",
          "الاربعاء",
          "الخميس",
          "الجمعة",
          "السبت"
        ],
        goToToday: "اذهب الي اليوم",
        months: [
          "يناير",
          "فبراير",
          "مارس",
          "ابريل",
          "مايو",
          "يونيو",
          "يوليو",
          "اغسطس",
          "سبتمبر",
          "اكتوبر",
          "نوفمبر",
          "ديسمبر"
        ],
        shortDays: ["ح", "ن", "ث", "ع", "خ", "ج", "س"],
        shortMonths: [
          "يناير",
          "فبراير",
          "مارس",
          "ابريل",
          "مايو",
          "يونيو",
          "يوليو",
          "اغسطس",
          "سبتمبر",
          "اكتوبر",
          "نوفمبر",
          "ديسمبر"
        ]
      };
    }
  }

  private _showTransferFormButtons = (): JSX.Element => {
    return (
      <div className="ms-modalExample-footer modalFooter">
        <NewPrimaryButton
          onClick={this.transferCorrespondence.bind(this)}
          style={{ marginRight: "8px" }}
        >
          Transfer222
        </NewPrimaryButton>
      </div>
    );
  };

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

    if (this.state.selectedCorrespondenceTransfer) {
      //debugger;
      this._recordService
        .transferCorrespondence(this.state.selectedCorrespondenceTransfer)
        .then(
          () => {
            this.setState({ showTransferPanel: false });
            if (button && button.block) button.block();
            if (button && button.unblock) button.unblock();

            //this.loadRecorders();
          },
          (error: any) => {
            alert(error);
            if (button && button.unblock) button.unblock();
          }
        );
    }
  }

  private closeTransferPanel() {
    return (): void => {
      this.setState({ showTransferPanel: false });
    };
  }

  // private showTransferPanel() {
  //     let selectedCorrespondenceTransfer = new CorrespondenceTransfer();
  //     selectedCorrespondenceTransfer.correspondenceId = this.props.Record.id
  //     this.setState({ showTransferPanel: true, selectedCorrespondenceTransfer: selectedCorrespondenceTransfer });
  // }

  _handleCorrespondenceTranserToDepartmentsChange(id: number) {
    if (this.state.selectedCorrespondenceTransfer) {
      let selectedCorrespondenceTransfer = this.state
        .selectedCorrespondenceTransfer;
      selectedCorrespondenceTransfer.toDepartmentId = id[0];
      this.setState({
        selectedCorrespondenceTransfer: selectedCorrespondenceTransfer
      });
    }
  }
  _handleCorrespondenceTranserToDepartmentsCommentsChange(comment: string) {
    if (this.state.selectedCorrespondenceTransfer) {
      let selectedCorrespondenceTransfer = this.state
        .selectedCorrespondenceTransfer;
      selectedCorrespondenceTransfer.comment = comment;
      this.setState({
        selectedCorrespondenceTransfer: selectedCorrespondenceTransfer
      });
    }
  }
  _handleCorrespondenceTranserToReasonsChange(reason: any) {
    //debugger;
    if (this.state.selectedCorrespondenceTransfer) {
      let selectedCorrespondenceTransfer = this.state
        .selectedCorrespondenceTransfer;
      selectedCorrespondenceTransfer.reason = reason.key;
      this.setState({
        selectedCorrespondenceTransfer: selectedCorrespondenceTransfer
      });
    }
  }

  public render() {
    return (
      <div>
        {this.props.Record.state ? <h4>{this.props.Record.state.name}</h4> : ""}
        {this.props.Record.entityId != 14 &&
        this.props.Record &&
        this.props.Record.actions &&
        this.props.Record.actions.length > 0 ? (
          <div>
            {this.props.Record.actions.map((action: WorkflowAction) => {
              return (
                <div style={{ display: "inline-block" }}>
                  <PrimaryButton
                    onClick={this.props.OnExecuteWorkflowAction(
                      this.props.Record,
                      action
                    )}
                    className="panel-footer-btn"
                  >
                    {action.name}
                  </PrimaryButton>
                </div>
              );
            })}
          </div>
        ) : (
          ""
        )}
        {/* {
                    this.props.Record.entityId == 14 && <div>
                        <PrimaryButton
                            onClick={this.showTransferPanel.bind(this)}
                            style={{ margin: '5px' }}>
                            Transfer
                                    </PrimaryButton>
                    </div>
                } */}
        <div className="">
          <div className="formPreview">
            {!this.props.Record.fields
              ? ""
              : this.props.Record.fields
                  .sort((a: RecordField, b: RecordField) => {
                    if (a.index < b.index) {
                      return -1;
                    }
                    if (a.index > b.index) {
                      return 1;
                    }
                    return 0;
                  })
                  .map((item: RecordField) => {
                    if (item.hidden == true) return "";
                    switch (item.type) {
                      case FieldTypes.Text:
                        return (
                          <div
                            className="ms-Grid-col ms-sm6 ms-md6 ms-lg12"
                            key={`form-field-${item.index}`}
                          >
                            <TextField
                              className="ms-Grid-col ms-lg12"
                              label={item.displayName}
                              value={item.data ? item.data : ""}
                              onChanged={this._handleDataChange.bind(
                                this,
                                item
                              )}
                            />
                          </div>
                        );
                      case FieldTypes.Header:
                        return (
                          <div
                            className="ms-Grid-col ms-sm6 ms-md6 ms-lg12"
                            key={`form-field-${item.index}`}
                          >
                            <h3 className="ms-Grid-col ms-lg12">
                              {item.displayName}
                            </h3>
                          </div>
                        );
                      case FieldTypes.Paragraph:
                        return (
                          <div
                            className="ms-Grid-col ms-sm6 ms-md6 ms-lg12"
                            key={`form-field-${item.index}`}
                          >
                            <p className="ms-Grid-col ms-lg12">
                              {item.displayName}
                            </p>
                          </div>
                        );
                      case FieldTypes.SingleChoice:
                        return (
                          <div
                            className="ms-Grid-col ms-sm6 ms-md6 ms-lg12"
                            key={`form-field-${item.index}`}
                          >
                            <Dropdown
                              className="ms-Grid-col ms-lg12"
                              defaultSelectedKey={item.data}
                              options={item.lookups.map((lookup: any) => {
                                return { key: lookup.id, text: lookup.value };
                              })}
                              label={item.displayName}
                              disabled={item.disabled}
                              onChanged={this._handleChoiceChange.bind(
                                this,
                                item
                              )}
                            />
                          </div>
                        );
                      case FieldTypes.MultipleChoice:
                        return (
                          <div
                            className="ms-Grid-col ms-sm6 ms-md6 ms-lg12"
                            key={`form-field-${item.index}`}
                          >
                            {item.lookups.map((lookup: any) => {
                              return (
                                <Checkbox
                                  className="ms-Grid-col ms-lg12"
                                  defaultChecked={this.isChecked(
                                    item,
                                    lookup.id
                                  )}
                                  key={lookup.id}
                                  label={lookup.value}
                                  onChange={this._handleCheckboxChange.bind(
                                    this,
                                    item,
                                    lookup.id
                                  )}
                                />
                              );
                            })}
                          </div>
                        );
                      case FieldTypes.Multiline:
                        return (
                          <div
                            className="ms-Grid-col ms-sm6 ms-md6 ms-lg12"
                            key={`form-field-${item.index}`}
                          >
                            <TextField
                              className="ms-Grid-col ms-lg12"
                              label={item.displayName}
                              multiline
                              rows={4}
                              value={item.data ? item.data : ""}
                              onChanged={this._handleDataChange.bind(
                                this,
                                item
                              )}
                            />
                          </div>
                        );
                      case FieldTypes.Image:
                        return (
                          <div
                            className="ms-Grid-col ms-sm6 ms-md6 ms-lg7"
                            key={`form-field-${item.index}`}
                          >
                            <div className="ms-Grid-col ms-lg12">
                              {" "}
                              <Label>{item.displayName}</Label>
                              <Image
                                src={this.getFileFullPath(item.extraData)}
                                alt={item.displayName}
                                width={100}
                                onClick={this.downloadFile(item)}
                              />
                            </div>
                            <input
                              type="file"
                              id={"uploadFile" + item.id}
                              onChange={event => {
                                this.uploadFile(event, item);
                              }}
                            />
                          </div>
                        );

                      case FieldTypes.Label:
                        return (
                          <div
                            className="ms-Grid-col ms-sm6 ms-md6 ms-lg12"
                            key={`form-field-${item.index}`}
                          >
                            <Label className="ms-Grid-col ms-lg11">
                              {item.displayName}
                            </Label>
                          </div>
                        );
                      case FieldTypes.Date:
                        return (
                          <div
                            className="ms-Grid-col ms-sm6 ms-md6 ms-lg12"
                            key={`form-field-${item.index}`}
                          >
                            <Label>{item.displayName}</Label>
                            <DatePicker
                              className="ms-Grid-col ms-lg12"
                              value={this.convertDate(item.data)}
                              isRequired={false}
                              placeholder=""
                              strings={this.datepickerStrings}
                              allowTextInput={true}
                              onSelectDate={this._handleDataChange.bind(
                                this,
                                item
                              )}
                            />
                          </div>
                        );
                      case FieldTypes.Currency:
                        return (
                          <div
                            className="ms-Grid-col ms-sm6 ms-md6 ms-lg12"
                            key={`form-field-${item.index}`}
                          >
                            <TextField
                              iconProps={{ iconName: "Money" }}
                              className="ms-Grid-col ms-lg12"
                              label={item.displayName}
                              value={item.data ? item.data : ""}
                              onChanged={this._handleDataChange.bind(
                                this,
                                item
                              )}
                            />
                          </div>
                        );
                      case FieldTypes.Percentage:
                        return (
                          <div
                            className="ms-Grid-col ms-sm6 ms-md6 ms-lg12"
                            key={`form-field-${item.index}`}
                          >
                            <TextField
                              iconProps={{ iconName: "Chart" }}
                              className="ms-Grid-col ms-lg12"
                              label={item.displayName}
                              value={item.data ? item.data : ""}
                              onChanged={this._handleDataChange.bind(
                                this,
                                item
                              )}
                            />
                          </div>
                        );
                      case FieldTypes.Number:
                        return (
                          <div
                            className="ms-Grid-col ms-sm6 ms-md6 ms-lg12"
                            key={`form-field-${item.index}`}
                          >
                            <TextField
                              iconProps={{ iconName: "NumberField" }}
                              className="ms-Grid-col ms-lg12"
                              label={item.displayName}
                              value={item.data ? item.data : ""}
                              onChanged={this._handleDataChange.bind(
                                this,
                                item
                              )}
                            />
                          </div>
                        );
                      case FieldTypes.Boolean:
                        return (
                          <div
                            className="ms-Grid-col ms-sm6 ms-md6 ms-lg7"
                            key={`form-field-${item.index}`}
                          >
                            <div className="choiceGroup ms-Grid-col ms-lg11">
                              <ChoiceGroup
                                options={[
                                  {
                                    key: "true",
                                    text: "Yes",
                                    disabled: false
                                  },
                                  {
                                    key: "false",
                                    text: "No",
                                    disabled: false
                                  }
                                ]}
                                onChange={this._handleBooleanChange.bind(
                                  this,
                                  item
                                )}
                                label={item.displayName}
                                defaultSelectedKey={
                                  item.data ? item.data.toString() : "false"
                                }
                              />
                            </div>
                          </div>
                        );
                      case FieldTypes.Document:
                        return (
                          <div
                            className="ms-Grid-col ms-sm6 ms-md6 ms-lg7"
                            key={`form-field-${item.index}`}
                          >
                            <Label>{item.displayName}</Label>
                            <Link
                              className="choiceGroup ms-Grid-col ms-lg11"
                              value={item.data}
                              onClick={this.downloadFile(item)}
                            >
                              {item.extraData ? item.extraData.name : ""}
                            </Link>
                            <input
                              type="file"
                              id={"uploadFile" + item.id}
                              onChange={event => {
                                this.uploadFile(event, item);
                              }}
                            />
                          </div>
                        );
                      case FieldTypes.Callout:
                        return (
                          <div
                            className="ms-Grid-col ms-sm6 ms-md6 ms-lg5"
                            key={`form-field-${item.index}`}
                          >
                            <div className="choiceGroup ms-Grid-col ms-lg10">
                              <div
                                className="buttonArea"
                                ref={this._menuButtonElement}
                              >
                                <IconButton
                                  iconProps={{ iconName: "Chat" }}
                                  onClick={this._onShowMenuClicked}
                                />
                              </div>
                              <Callout
                                className="ms-CalloutExample-callout callout"
                                ariaLabelledBy={"callout-label-1"}
                                ariaDescribedBy={"callout-description-1"}
                                role={"alertdialog"}
                                gapSpace={0}
                                target={this._menuButtonElement.value}
                                onDismiss={this._onCalloutDismiss}
                                setInitialFocus={true}
                                hidden={!this.state.isCalloutVisible}
                              >
                                <div className="ms-CalloutExample-inner calloutContent">
                                  <div className="ms-CalloutExample-content">
                                    <p
                                      className="ms-CalloutExample-subText"
                                      id={"callout-description-1"}
                                    >
                                      {item.displayName}
                                    </p>
                                  </div>
                                </div>
                              </Callout>
                            </div>
                          </div>
                        );
                      case FieldTypes.EntityReference:
                        return item.records ? (
                          <div
                            className="ms-Grid-col ms-sm6 ms-md6 ms-lg7"
                            key={`form-field-${item.index}`}
                          >
                            <div className="choiceGroup ms-Grid-col ms-lg11">
                              <ComboBox
                                defaultSelectedKey={item.data}
                                selectedKey="C"
                                label={item.displayName}
                                id="Basicdrop3"
                                ariaLabel="Basic ComboBox example"
                                allowFreeform={false}
                                autoComplete="on"
                                options={item.records.records.map(
                                  (record: any) => {
                                    return {
                                      key: record.id,
                                      text: record.name
                                    };
                                  }
                                )}
                                onRenderOption={this._onRenderFontOption}
                                // tslint:disable:jsx-no-lambda
                                onFocus={() => console.log("onFocus called")}
                                onBlur={() => console.log("onBlur called")}
                                onMenuOpen={() =>
                                  console.log("ComboBox menu opened")
                                }
                                onChanged={this._handleChoiceChange.bind(
                                  this,
                                  item
                                )}
                                // tslint:enable:jsx-no-lambda
                              />
                            </div>
                          </div>
                        ) : (
                          ""
                        );
                      case FieldTypes.ReferencedEntity:
                      case FieldTypes.ManyToManyRelated:
                        return item.records ? (
                          <div
                            className="ms-Grid-col ms-sm12 ms-md12 ms-lg12"
                            key={`form-field-${item.type}${item.index}`}
                          >
                            <div>
                              <CommandsBar Commands={this.state.commands} />
                            </div>
                            <div className="choiceGroup ms-Grid-col ms-lg11">
                              <RecordsListView
                                Records={item.records.records}
                                SelectedRecordChanged={this.selectedRecordChanged.bind(
                                  this,
                                  item.records.enableSelection,
                                  item.records.enableCreation
                                )}
                              />
                            </div>
                          </div>
                        ) : (
                          ""
                        );
                      case FieldTypes.Html:
                        let editor;
                        const contentBlocks = convertFromHTML(
                          item.data ? item.data : ""
                        );
                        if (contentBlocks && contentBlocks.contentBlocks) {
                          const contentState = ContentState.createFromBlockArray(
                            contentBlocks.contentBlocks,
                            contentBlocks.entityMap
                          );
                          editor = EditorState.createWithContent(contentState);
                        } else {
                          editor = EditorState.createEmpty();
                        }

                        return (
                          <div
                            className="ms-Grid-col ms-sm6 ms-md6 ms-lg12"
                            key={`form-field-${item.index}`}
                          >
                            <Label>{item.displayName}</Label>
                            {/* <ReactQuill value={item.data ? item.data : ""} onChange={this._handleDataChange.bind(this, item)} /> */}
                            <Editor
                            
                              defaultEditorState={editor}
                              toolbarClassName="customEditorToolbar"
                              //wrapperClassName="wrapperClassName"
                              editorClassName="customEditorMain"
                              onEditorStateChange={this._handleEditorStateChange.bind(
                                this,
                                item
                              )}
                            />
                          </div>
                        );
                      case FieldTypes.MultipleDocuments:
                        return (
                          <div
                            className="ms-Grid-col ms-sm6 ms-md6 ms-lg12"
                            key={`form-field-${item.index}`}
                          >
                            <Label>{item.displayName}</Label>
                            <MultipleFileUpload
                              initialFiles={item.extraData}
                              onChanged={this._handleFilesChange.bind(
                                this,
                                item
                              )}
                            />
                          </div>
                        );
                      case FieldTypes.OrganizationUnit:
                        if (item.id == 165 && !item.data) {
                          item.data = this._loggedInUser.department;
                        }
                        return (
                          <div
                            className="ms-Grid-col ms-sm6 ms-md6 ms-lg12"
                            key={`form-field-${item.index}`}
                          >
                            <Label>{item.displayName}</Label>
                            <OrganizationalUnitsTreeComboBox
                              disabled={item.id == 165}
                              value={item.data}
                              multiple={false}
                              onChanged={this._handleOrganizationUnitChange.bind(
                                this,
                                item
                              )}
                            />
                          </div>
                        );
                      case FieldTypes.MultipleOrganizationUnits:
                        return (
                          <div
                            className="ms-Grid-col ms-sm6 ms-md6 ms-lg12"
                            key={`form-field-${item.index}`}
                          >
                            <Label>{item.displayName}</Label>
                            <OrganizationalUnitsTreeComboBox
                              value={item.data}
                              multiple={true}
                              onChanged={this._handleMultipleOrganizationUnitsChange.bind(
                                this,
                                item
                              )}
                            />
                          </div>
                        );
                    }
                    return "";
                  })}
          </div>
        </div>
        <Panel
          className="panelStyle"
          isOpen={this.state.showTransferPanel}
          onDismiss={this.closeTransferPanel.bind(this)}
          type={PanelType.medium}
          headerText="Transfer Correspondence"
          isLightDismiss={true}
          hasCloseButton={false}
          onRenderFooter={this._showTransferFormButtons}
          onRenderHeader={this._onReadnderHader}
        >
          <div className="ms-Grid-row">
            <div className="ms-Grid-col ms-sm12">
              <Label>Department</Label>
              <OrganizationalUnitsTreeComboBox
                onChanged={this._handleCorrespondenceTranserToDepartmentsChange.bind(
                  this
                )}
              />
            </div>
            <div className="ms-Grid-col ms-sm12">
              <TextField
                className="ms-Grid-col ms-lg12"
                label="Comment"
                multiline
                rows={4}
                onChanged={this._handleCorrespondenceTranserToDepartmentsCommentsChange.bind(
                  this
                )}
              />
            </div>
            <div className="ms-Grid-col ms-lg12">
              <Dropdown
                className="ms-Grid-col ms-lg12"
                options={this.state.reasonLookups.map((lookup: any) => {
                  return { key: lookup.id, text: lookup.value };
                })}
                label="Reason"
                onChanged={this._handleCorrespondenceTranserToReasonsChange.bind(
                  this
                )}
              />
            </div>
            ;
            {/* <d
                        iv className="ms-Grid-col ms-lg12" style={{ marginTop: 15 }}>
                            <label className='ms-font-xl	ms-fontWeight-semibold	'>Handler Parameters</label>
                        </div>
                        {
                            this.state.selectedWorkflowHandler && this.state.selectedWorkflowHandler.handlerParams &&
                            this.state.selectedWorkflowHandler.handlerParams.map((element: any) => {
                                return (<div className="ms-Grid-col ms-lg12">
                                    <TextField label={element.name} required={element.required} />
                                </div>)
                            })} */}
          </div>
        </Panel>
      </div>
    );
  }

  private getCommonCommands(
    entityId: number,
    enableSelection: boolean,
    enableCreation: boolean
  ): Command[] {
    let commands = new Array<Command>();
    if (enableCreation) {
      commands.push({
        key: "addRecord",
        name: "Create Record",
        icon: "Add",
        onClick: this.addRecord.bind(this, entityId)
      });
    }
    if (enableSelection) {
      commands.push({
        key: "selectRecord",
        name: "Select Record",
        icon: "Add",
        onClick: this.selectRecord.bind(this, entityId)
      });
    }
    return commands;
  }
  private getRecordCommands(
    record: Record,
    enableSelection: boolean,
    enableCreation: boolean
  ): Command[] {
    let commands = this.getCommonCommands(
      record.entityId,
      enableSelection,
      enableCreation
    );
    if (enableCreation) {
      commands.push(
        {
          key: "removeRecord",
          name: "Remove",
          icon: "Remove",
          onClick: this.deleteRecord.bind(this, record)
        },
        {
          key: "edit",
          name: "Edit",
          icon: "Edit",
          onClick: this.editRecord.bind(this, record)
        }
      );
    }
    if (enableSelection) {
      commands.push({
        key: "unselectRecord",
        name: "Unselect",
        icon: "Unselect",
        onClick: this.unselectRecord.bind(this, record)
      });
    }
    return commands;
  }

  private unselectRecord(record: Record) {
    if (record) {
      this.getRecord(record.entityId, 0, false);
    }
  }
  private selectRecord(entityId: number) {
    this.getRecord(entityId, 0, false);
  }

  private addRecord(entityId: number) {
    this.getRecord(entityId, 0, false);
  }

  private editRecord(record: Record) {
    if (record) {
      this.getRecord(record.entityId, record.id, false);
    }
  }

  private deleteRecord(record: Record) {
    if (record) {
      this._recordService.deleteRecord(record.entityId, record.id).then(
        () => {
          //this.loadRecords();
        },
        (error: any) => {
          alert(error);
        }
      );
    }
  }

  private selectedRecordChanged(
    enableSelection: boolean,
    enableCreation: boolean,
    entity: any
  ) {
    if (!entity) return;

    this.setState({
      selectedItem: entity,
      commands: this.getRecordCommands(entity, enableSelection, enableCreation)
    });
  }

  private getRecord(entityId: number, recordId: number, isViewMode: boolean) {
    if (recordId == 0) {
      this._recordService.getEmptyRecord(entityId).then(
        result => {
          if (isViewMode)
            this.setState({ selectedItem: result, showViewPanel: true });
          else this.setState({ selectedItem: result, showPanel: true });

          result.fields.forEach(f => {
            if (f.type === FieldTypes.EntityReference && f.extraData !== null) {
              let criteria = new ListRecordsCriteria();
              criteria.entityId = f.extraData as number;
              criteria.asLookup = true;

              this._recordService.listRecords(criteria).then(result => {
                f.records = result;
                this.setState({ record: this.state.record });
              });
            }
          });
          this.setState({ record: result });
        },
        error => {
          alert(error);
        }
      );
    } else {
      this._recordService.getRecord(entityId, recordId).then(
        result => {
          if (isViewMode)
            this.setState({ selectedItem: result, showViewPanel: true });
          else this.setState({ selectedItem: result, showPanel: true });

          result.fields.forEach(f => {
            if (f.type === FieldTypes.EntityReference && f.extraData !== null) {
              let criteria = new ListRecordsCriteria();
              criteria.entityId = f.extraData as number;
              criteria.asLookup = true;
              this._recordService.listRecords(criteria).then(result => {
                f.records = result;
                this.setState({ record: this.state.record });
              });
            } else if (
              f.type === FieldTypes.ReferencedEntity ||
              f.type === FieldTypes.ManyToManyRelated
            ) {
              let criteria = f.extraData as ListRecordsCriteria;
              this._recordService.listRecords(criteria).then(result => {
                f.records = result;
                this.setState({ record: this.state.record });
              });
            }
          });
          this.setState({ record: result });
        },
        error => {
          alert(error);
        }
      );
    }
  }

  private _onShowMenuClicked = (): void => {
    this.setState({
      isCalloutVisible: !this.state.isCalloutVisible
    });
  };

  private _onCalloutDismiss = (): void => {
    this.setState({
      isCalloutVisible: false
    });
  };
  _handleDataChange(item: RecordField, value: any) {
    item.data = value;
  }
  _handleBooleanChange(
    item: RecordField,
    ev: React.FormEvent<HTMLElement>,
    selected: any
  ) {
    item.data = selected.key;
  }

  _handleFilesChange(item: RecordField, ids: Array<number>) {
    item.data = ids;
  }

  _handleOrganizationUnitChange(item: RecordField, ids: Array<number>) {
    if (ids && ids.length > 0) item.data = ids[0];
    else item.data = null;
  }

  _handleMultipleOrganizationUnitsChange(
    item: RecordField,
    ids: Array<number>
  ) {
    item.data = ids;
  }

  _handleEditorStateChange(item: RecordField, editorState: any) {
    item.data = draftToHtml(convertToRaw(editorState.getCurrentContent()));
  }

  //     _handleDatePickerChange(item:RecordField,value: Date) {
  //         debugger;
  //         let date = new Date(value.toLocaleDateString());
  // item.data = new Date(date.getFullYear(),date.getMonth(),date.getDate());
  //     };
  _handleChoiceChange(item: RecordField, value: any) {
    item.data = value.key;
  }
  _handleCheckboxChange(
    item: RecordField,
    lookupId: number,
    ev: React.FormEvent<HTMLElement>,
    isChecked: boolean
  ) {
    if (!item.data) {
      item.data = [];
    }

    if (isChecked && !item.data.includes(lookupId)) {
      item.data.push(lookupId);
    } else if (!isChecked) {
      item.data.splice(item.data.indexOf(lookupId), 1);
    }
  }
  private isChecked(item: RecordField, lookupId: number) {
    if (!item.data) return false;
    return item.data.includes(lookupId);
  }
  private convertDate(date: any): Date | undefined {
    if (date == null) return undefined;

    if (date instanceof Date) return date;

    return new Date(date.replace("T", " "));
    // // replace anything but numbers by spaces
    // dtstr = dtstr.replace(/\D/g," ");

    // // trim any hanging white space
    // dtstr = dtstr.replace(/\s+$/,"");

    // // split on space
    // let dtcomps : Array<string>= dtstr.split(" ");

    // // not all ISO 8601 dates can convert, as is
    // // unless month and date specified, invalid
    // if (dtcomps.length < 3) return "";
    // // if time not provided, set to zero
    // if (dtcomps.length < 4) {
    //   dtcomps[3] = "0";
    //   dtcomps[4] =  "0";
    //   dtcomps[5] =  "0";
    // }

    // // modify month between 1 based ISO 8601 and zero based Date
    // dtcomps[1] = (parseInt(dtcomps[1]) - 1).toString();

    // var convdt = new
    //     Date(Date.UTC(parseInt(dtcomps[0]),parseInt(dtcomps[1]),parseInt(dtcomps[2]),parseInt(dtcomps[3]),parseInt(dtcomps[4]),parseInt(dtcomps[5])));

    // return convdt.toUTCString();
  }

  private getFileFullPath(file: any) {
    return this._fileService.getFullPath(file);
  }
  private uploadFile(event: any, field: RecordField) {
    if (event.target.files && event.target.files.length > 0) {
      const formData = new FormData();

      for (let file of event.target.files) formData.append(file.name, file);

      this._fileService.uploadFileContent(formData).then(result => {
        field.extraData = result;
        field.data = field.extraData.id;
      });
    }
  }

  private downloadFile(field: RecordField) {
    return (): void => {
      if (field.extraData) {
        window.open(this._fileService.getFullPath(field.extraData));
      }
    };
  }

  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>
    );
  };
}
