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 { Checkbox } from "office-ui-fabric-react/lib/components/Checkbox";
import { Image } from "office-ui-fabric-react/lib/Image";
import {
  Record,
  RecordField,
  Command,
  ListRecordsCriteria,
  WorkflowAction,
  OrganizationUnit
} 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,
  DefaultButton,
  Dialog,
  DialogType,
  DialogFooter
} from "office-ui-fabric-react";
import { RecordsListView, CommandsBar, MultipleFileUpload } from ".";
import { PrimaryButton as NewPrimaryButton } from "../Customizations/Controls/PrimaryButton";
// import Gallery from "react-fine-uploader";
// import ReactQuill from "react-quill";
// import 'react-quill/dist/quill.snow.css';

// import {
//   convertToRaw,
// } from "draft-js";
// import draftToHtml from "draftjs-to-html";
import "react-draft-wysiwyg/dist/react-draft-wysiwyg.css";
import "react-fine-uploader/gallery/gallery.css";
import { FormattedMessage } from "react-intl";

import classnames from "classnames";
import { TransferCorrespondence } from "../Customizations/Controls/Correspondence/TransferCorrespondence";
import { CorrespondenceTransfer } from "../Models/CorrespondenceTransfer";
import { AxiosPromise } from "axios";
import { OrganizationalUnitsTreeComboBox } from "./OrganizationalUnitsTreeComboBox";
import { UsersDropdown } from "./UsersDropdown";
import { LoadingService } from "../Services/LoadingService";
import { DateUtils } from "../Utils";
import { Dropdown } from "../Customizations/Controls/Dropdown";
import { MoveDraftCorrespondence } from "../Customizations/Controls/Correspondence/MoveDraftCorrespondence";
import { Editor } from "./HtmlEditor";
import { DateTimePicker } from "./DateTimePicker";
// import { Editor } from "./HtmlEditor";
export class FieldsControl 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 datepickerStrings: IDatePickerStrings;
  private _loadingService = new LoadingService();
  private fieldsForm: any = React.createRef<HTMLElement>();
  private _dateUtils: DateUtils = new DateUtils();
  constructor(props: any) {
    super(props);

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

    this.state = {
      isCalloutVisible: false,
      commands: new Array<Command>(),
      submitted: false,
      MultiTransferPanel: false,
      MoveDraftCorrespondencePanel: false,
      selectedCorrespondenceTransfer: new CorrespondenceTransfer(),
      reasonLookups: [
        { id: 0, value: "option 1" },
        { id: 1, value: "option 2" },
        { id: 2, value: "option 3" }
      ],
      hideDialogCancelDialoge: true
    };

    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: [
          "يناير",
          "فبراير",
          "مارس",
          "ابريل",
          "مايو",
          "يونيو",
          "يوليو",
          "اغسطس",
          "سبتمبر",
          "اكتوبر",
          "نوفمبر",
          "ديسمبر"
        ]
      };
    }
  }
  quillModules = {
    toolbar: [
      [{ header: [1, 2, false] }],
      ["bold", "italic", "underline", "strike", "blockquote"],
      [
        { list: "ordered" },
        { list: "bullet" },
        { indent: "-1" },
        { indent: "+1" }
      ],
      ["link", "image"],
      ["clean"]
    ]
  };

  quillFormats = [
    "header",
    "bold",
    "italic",
    "underline",
    "strike",
    "blockquote",
    "list",
    "bullet",
    "indent",
    "link",
    "image"
  ];
  // private _showTransferFormButtons = (): JSX.Element => {
  //   return (
  //     <div className="ms-modalExample-footer modalFooter">
  //       <NewPrimaryButton
  //         onClick={this.transferCorrespondence.bind(this)}
  //         style={{ marginRight: "8px" }}
  //       >
  //         Transfer222
  //       </NewPrimaryButton>
  //     </div>
  //   );
  // };
  formSubmit(event: any = null) {
    //debugger;
    var promise = null;
    if (event) event.preventDefault();
    this.setState({ submitted: true });

    let requiredFields = 0;
    this.props.fields.forEach((field: any) => {
      if (!field.allowNull && (field.data == null && field.extraData == null)) {
        requiredFields++;
      }
    });
    if (requiredFields == 0) {
      promise = this.props.onSubmit(this.props.fields);
      if (event) event.target.reset();
      if (
        this.props.isWizard &&
        this.props.totalSteps > this.props.currentStep
      ) {
        this.props.nextStep();
      }
    }

    return promise;
  }

  private _setColWidth(id: any): string {
    if (this.props.setColWidth)
      return this.props.setColWidth(id);
    else
      return "ms-Grid-col ms-sm12 ms-lg12";
  }

  _saveAsDraft(button?: any) {
    //debugger;
    this.setState({ submitted: true });

    if (this.fieldsForm.current.checkValidity()) {
      if (button && button.block) button.block();
      var promise = null;
      // if (this.fieldsForm.current) this.fieldsForm.preventDefault();

      let requiredFields = 0;
      this.props.fields.forEach((field: any) => {
        if (!field.allowNull && (field.data == null && field.extraData == null)) {
          requiredFields++;
        }
      });
      if (requiredFields == 0) {
        promise = this.props.saveAsDraft(this.props.fields);
        // if (this.fieldsForm.current) this.fieldsForm.target.reset();
      }
      if (button && button.unblock) button.unblock();
      return promise;
    }

  }

  _handleFilesChange(item: RecordField, ids: Array<number>, files: File[]) {
    if (ids && ids.length == 0) {
      item.data = null;
      item.extraData = null;
    } else {
      item.data = ids;
      item.extraData = files;
    }
    this.forceUpdate();
  }

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

      item.extraData = organizationUnits[0];
    } else {
      item.data = null;
      item.extraData = null;
    }

    if (item.onChanged)
      item.onChanged(item);
  }

  _handleMultipleOrganizationUnitsChange(
    item: RecordField,
    ids: Array<number>,
    organizationUnits: OrganizationUnit[]
  ) {
    item.data = ids;
    item.extraData = organizationUnits;
  }

  _handleEditorStateChange(item: RecordField, e: any) {
    // if(item)

    item.data = e.target.getContent();
    if (item.data.trim() == "<p></p>") item.data = null;
    this.forceUpdate();
  }

  _setFormsubmitted(button?: any) {
    if (button && button.block) button.block();
    this.setState({ submitted: true, MultiTransferPanel: false, MoveDraftCorrespondencePanel: false });
    if (button && button.unblock) button.unblock();
  }



  _setFormsubmittedForTransfer(button: any) {
    if (button && button.block) button.block();
    this.setState({ submitted: true, MultiTransferPanel: true, MoveDraftCorrespondencePanel: false });
    if (button && button.unblock) button.unblock();
  }


  _setFormsubmittedForMoveCorrespondence(button: any) {
    if (button && button.block) button.block();
    this.setState({ submitted: true, MultiTransferPanel: false, MoveDraftCorrespondencePanel: true });
    if (button && button.unblock) button.unblock();
  }

  private closeMultiTransferPanel() {
    this.setState({ MultiTransferPanel: false });
  }

  private closeMoveDraftCorrespondencePanel() {
    this.setState({ MoveDraftCorrespondencePanel: false });
  }

  private transferMultiCorrespondence(
    obj: CorrespondenceTransfer,
    button: any
  ) {
    // let _this = this;
    if (button && button.block) button.block();
    var promise: AxiosPromise<number> = this.formSubmit();
    if (promise) {
      this._loadingService.show();
      this.setState({ MultiTransferPanel: false });
      promise.then(result => {
        obj.correspondenceId = result.data;
        this._recordService.transferCorrespondence(obj).then(
          () => {

            if (button && button.unblock) button.unblock();
            //      this.setState({ MultiTransferPanel: false });
            this._loadingService.hide();

          },
          (error: any) => {
            alert(error);
            this._loadingService.hide();

          }
        );
      });
    }
  }

  private moveDraftCorrespondence(
    obj: CorrespondenceTransfer,
    button: any
  ) {
    // let _this = this;
    if (button && button.block) button.block();
    var promise: AxiosPromise<number> = this.formSubmit();
    if (promise) {
      this._loadingService.show();
      this.setState({ MoveDraftCorrespondencePanel: false });
      promise.then(result => {
        obj.correspondenceId = result.data;
        this._recordService.moveDraftCorrespondence(obj).then(
          () => {

            if (button && button.unblock) button.unblock();
            //      this.setState({ MoveDraftCorrespondencePanel: false });
            this._loadingService.hide();

          },
          (error: any) => {
            alert(error);
            this._loadingService.hide();

          }
        );
      });
    }
  }

  // private onClickCancel(){
  //   this.props.history.push("/dashboard")
  // }
  _handleBlur(isRequired: any) {
    if (isRequired) {
    }
  }

  public render() {
    return (
      <div>
        <div>
          <form className="ms-Grid" onSubmit={this.formSubmit.bind(this)} ref={this.fieldsForm}>
            <div className="formPreview ms-Grid-row ">
              {!this.props.fields
                ? ""
                : this.props.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, index: any) => {
                    if (item.hidden == true) return "";

                    switch (item.type) {
                      case FieldTypes.Text:
                        return (
                          <div
                            id={item.displayName}
                            className={this._setColWidth(item.id)}
                            key={index}
                          >
                            <TextField
                              className=" ms-lg12"
                              label={item.displayName}
                              errorMessage={
                                !item.allowNull &&
                                  !item.data &&
                                  this.state.submitted
                                  ? "Required"
                                  : ""
                              }
                              required={!item.allowNull}
                              value={item.data ? item.data : ""}
                              onChanged={this._handleDataChange.bind(
                                this,
                                item
                              )}
                            />
                          </div>
                        );
                      case FieldTypes.Header:
                        return (
                          <div
                            id={item.displayName}
                            className={this._setColWidth(item.id)}
                            key={index}
                          >
                            <h3 className=" ms-lg12">{item.displayName}</h3>
                          </div>
                        );
                      case FieldTypes.Paragraph:
                        return (
                          <div
                            id={item.displayName}
                            className={this._setColWidth(item.id)}
                            key={index}
                          >
                            <p className=" ms-lg12">{item.displayName}</p>
                          </div>
                        );
                      case FieldTypes.SingleChoice:
                        return (
                          <div
                            id={item.displayName}
                            className={this._setColWidth(item.id)}
                            key={index}
                          >
                            <Dropdown
                              className=" ms-lg12"
                              field={item}
                              defaultSelectedKey={item.data}
                              options={item.lookups.map((lookup: any) => {
                                return { key: lookup.id, text: lookup.value };
                              })}
                              label={item.displayName}
                              disabled={item.disabled}
                              errorMessage={
                                !item.allowNull &&
                                  !item.data &&
                                  this.state.submitted
                                  ? "Required"
                                  : ""
                              }
                              required={!item.allowNull}
                              onChanged={this._handleChoiceChange.bind(
                                this,
                                item
                              )}
                            />
                          </div>
                        );
                      case FieldTypes.MultipleChoice:
                        return (
                          <div
                            id={item.displayName}
                            className={this._setColWidth(item.id)}
                            key={index}
                          >
                            {item.lookups.map((lookup: any) => {
                              return (
                                <Checkbox
                                  className=" 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
                            id={item.displayName}
                            className={this._setColWidth(item.id)}
                            key={index}
                          >
                            <TextField
                              className=" ms-lg12"
                              errorMessage={
                                !item.allowNull &&
                                  !item.data &&
                                  this.state.submitted
                                  ? "Required"
                                  : ""
                              }
                              required={!item.allowNull}
                              label={item.displayName}
                              multiline
                              rows={4}
                              value={item.data ? item.data : ""}
                              onChanged={this._handleDataChange.bind(
                                this,
                                item
                              )}
                            />
                          </div>
                        );
                      case FieldTypes.Image:
                        return (
                          <div
                            id={item.displayName}
                            className="ms-Grid-col ms-sm12 ms-md12 ms-lg7"
                            key={index}
                          >
                            <div className=" 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
                            id={item.displayName}
                            className={this._setColWidth(item.id)}
                            key={index}
                          >
                            <Label className=" ms-lg11">
                              {item.displayName}
                            </Label>
                          </div>
                        );
                      case FieldTypes.Date:
                        return (
                          <div
                            id={item.displayName}
                            className={this._setColWidth(item.id)}
                            key={index}
                          >
                            <DatePicker
                              label={item.displayName}
                              className=" ms-lg12"
                              value={this.convertDate(item.data)}
                              placeholder=""
                              minDate={new Date()}
                              strings={this.datepickerStrings}
                              allowTextInput={true}
                              isRequired={!item.allowNull}
                              onSelectDate={this._handleDataChange.bind(
                                this,
                                item
                              )}
                              formatDate={this._onFormatDate.bind(this)}
                            />
                          </div>
                        );
                      case FieldTypes.DateTime:
                        return (
                          <div
                            id={item.displayName}
                            className={this._setColWidth(item.id)}
                            key={index}
                          >
                            <DateTimePicker
                              displayName={item.displayName}
                              allowNull={item.allowNull}
                              defaultValue={item.data}
                              onChange={this._handleDataChange.bind(
                                this,
                                item
                              )}
                            >
                            </DateTimePicker>
                          </div>
                        );
                      case FieldTypes.Currency:
                        return (
                          <div
                            id={item.displayName}
                            className={this._setColWidth(item.id)}
                            key={index}
                          >
                            <TextField
                              iconProps={{ iconName: "Money" }}
                              className=" ms-lg12"
                              label={item.displayName}
                              value={item.data ? item.data : ""}
                              onChanged={this._handleDataChange.bind(
                                this,
                                item
                              )}
                            />
                          </div>
                        );
                      case FieldTypes.Percentage:
                        return (
                          <div
                            id={item.displayName}
                            className={this._setColWidth(item.id)}
                            key={index}
                          >
                            <TextField
                              iconProps={{ iconName: "Chart" }}
                              className=" ms-lg12"
                              label={item.displayName}
                              value={item.data ? item.data : ""}
                              onChanged={this._handleDataChange.bind(
                                this,
                                item
                              )}
                            />
                          </div>
                        );
                      case FieldTypes.Number:
                        return (
                          <div
                            id={item.displayName}
                            className={this._setColWidth(item.id)}
                            key={index}
                          >
                            <TextField
                              iconProps={{ iconName: "NumberField" }}
                              className=" ms-lg12"
                              label={item.displayName}
                              value={item.data ? item.data : ""}
                              onChanged={this._handleDataChange.bind(
                                this,
                                item
                              )}
                            />
                          </div>
                        );
                      case FieldTypes.Boolean:
                        return (
                          <div
                            id={item.displayName}
                            className="ms-Grid-col ms-sm12 ms-md12 ms-lg7"
                            key={index}
                          >
                            <div className="choiceGroup  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
                            id={item.displayName}
                            className="ms-Grid-col ms-sm6 ms-md12 ms-lg7"
                            key={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
                            id={item.displayName}
                            className="ms-Grid-col ms-sm6 ms-md12 ms-lg5"
                            key={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
                            id={item.displayName}
                            className={this._setColWidth(item.id)}
                            key={index}
                          >
                            <div className="choiceGroup">
                              <Dropdown
                                defaultSelectedKey={item.data}
                                label={item.displayName}
                                id="Basicdrop3"
                                field={item}
                                ariaLabel={item.displayName}
                                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")}
                                onChanged={this._handleChoiceChange.bind(
                                  this,
                                  item
                                )}
                              // tslint:enable:jsx-no-lambda
                              />
                            </div>
                          </div>
                        ) : (
                            ""
                          );
                      case FieldTypes.ReferencedEntity:
                      case FieldTypes.ManyToManyRelated:
                        return item.records ? (
                          <div
                            id={item.displayName}
                            className={this._setColWidth(item.id)}
                            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
                            id={item.displayName}
                            className={this._setColWidth(item.id)}
                            key={index}
                          >
                            <Label required={!item.allowNull}>
                              {item.displayName}
                            </Label>
                            {/* <ReactQuill 
                                            className={ !item.allowNull && !item.data && this.state.submitted?  'quill-error' : ''}

                                        value={item.data?item.data:""} onChange={this._handleHtmlDataChange.bind(this,item)} 
                                        modules={this.quillModules}
                                            formats={this.quillFormats}/> */}
                            <div
                              className={
                                !item.allowNull &&
                                  !item.data &&
                                  this.state.submitted
                                  ? "editor-error"
                                  : ""
                              }
                            >
                              <Editor
                                initialValue={item.data}
                                onChange={this._handleEditorStateChange.bind(
                                  this,
                                  item
                                )} />
                              {/* <Editor
                                // textAlignment={
                                //   this._cachingService.readPersistant(
                                //     "Language"
                                //   ) == 1
                                //     ? "right"
                                //     : "left"
                                // }
                                defaultEditorState={editor}
                                toolbarClassName="customEditorToolbar"
                                //wrapperClassName="wrapperClassName"
                                editorClassName="customEditorMain"
                                onEditorStateChange={this._handleEditorStateChange.bind(
                                  this,
                                  item
                                )}
                              /> */}

                            </div>
                            {!item.allowNull &&
                              !item.data &&
                              this.state.submitted ? (
                                <Label className="error-label">Required</Label>
                              ) : (
                                ""
                              )}
                          </div>
                        );
                      case FieldTypes.MultipleDocuments:
                        return (
                          <div
                            id={item.displayName}
                            className={this._setColWidth(item.id)}
                            key={index}
                          >
                            <Label required={!item.allowNull}>
                              {item.displayName}
                            </Label>
                            <div
                              className={
                                !item.allowNull &&
                                  !item.data &&
                                  this.state.submitted
                                  ? "attachment-error"
                                  : ""
                              }
                            >
                              <MultipleFileUpload
                                Record={this.props.Record}
                                initialFiles={item.extraData}
                                onChanged={this._handleFilesChange.bind(
                                  this,
                                  item
                                )}
                              />
                              {/* <Gallery uploader={uploader} >
                                        </Gallery> */}
                            </div>
                            {!item.allowNull &&
                              !item.data &&
                              this.state.submitted ? (
                                <Label className="error-label">Required</Label>
                              ) : (
                                ""
                              )}
                          </div>
                        );
                      case FieldTypes.OrganizationUnit:
                        // if (item.id == 165 && !item.data) {
                        //   item.data = this._loggedInUser.department;
                        // }
                        return (
                          <div
                            id={item.displayName}
                            className={this._setColWidth(item.id)}
                            key={index}
                          >
                            <OrganizationalUnitsTreeComboBox
                              label={item.displayName}
                              required={!item.allowNull}
                              //disabled={item.id == 165}
                              value={item.data}
                              errorMessage={
                                !item.allowNull &&
                                  !item.data &&
                                  this.state.submitted
                                  ? "Required"
                                  : ""
                              }
                              multiple={false}
                              onChanged={this._handleOrganizationUnitChange.bind(
                                this,
                                item
                              )}
                            />
                          </div>
                        );
                      case FieldTypes.MultipleOrganizationUnits:
                        return (
                          <div
                            id={item.displayName}
                            className={this._setColWidth(item.id)}
                            key={index}
                          >
                            <Label>{item.displayName}</Label>
                            <OrganizationalUnitsTreeComboBox
                              value={item.data}
                              multiple={true}
                              onChanged={this._handleMultipleOrganizationsChange.bind(
                                this,
                                item
                              )}
                            />
                          </div>
                        );
                      case FieldTypes.User:
                        return (
                          <div
                            id={item.displayName}
                            className={this._setColWidth(item.id)}
                            key={index}
                          >
                            <UsersDropdown
                              className=" ms-lg12"
                              defaultSelectedKey={[item.data]}
                              label={item.displayName}
                              required={!item.allowNull}
                              multiSelect={item.multipleSelection == true}
                              disabled={item.disabled}
                              getUsersCondition={item.extraData ? item.extraData.getUsersCondition : null}
                              errorMessage={
                                !item.allowNull &&
                                  !item.data &&
                                  this.state.submitted
                                  ? "Required"
                                  : ""
                              }
                              onChanged={this._handleUserChange.bind(
                                this,
                                item
                              )}
                            />
                          </div>
                        );
                      case FieldTypes.MultipleUsers:
                        return (
                          <div
                            id={item.displayName}
                            className={this._setColWidth(item.id)}
                            key={index}
                          >
                            <UsersDropdown
                              className=" ms-lg12"
                              defaultSelectedKey={item.data}
                              label={item.displayName}
                              field={item}
                              multiSelect={true}
                              disabled={item.disabled}
                              errorMessage={
                                !item.allowNull &&
                                  !item.data &&
                                  this.state.submitted
                                  ? "Required"
                                  : ""
                              }
                              getUsersCondition={item.extraData ? item.extraData.getUsersCondition : null}
                              required={!item.allowNull}
                              onChanged={this._handleMultipleUsersChange.bind(
                                this,
                                item
                              )}
                            />
                          </div>
                        );
                      case FieldTypes.ReadOnly:
                        return (
                          <div
                            id={item.displayName}
                            className="ms-Grid-col ms-sm6 ms-md6 ms-lg12"
                            key={index}
                          >
                            {/* <TextField className="ms-Grid-col ms-lg12" label={item.displayName} value={item.data ? item.data : ""} onChanged={this._handleDataChange.bind(this, item)} /> */}
                            <Label>{item.displayName}</Label>
                            <div className="form-field-view">{item.data}</div>
                          </div>
                        );
                    }
                    return "";
                  })}
              {!this.props.panelMode &&
                <div>
                  {this.props.isWizard ? (
                    <div className="ms-Grid-col my-25">
                      <DefaultButton
                        className="mr-15"
                        onClick={this._openCancelDialog.bind(this)}
                      >
                        <FormattedMessage id="Cancel" />
                      </DefaultButton>
                      {this.props.currentStep > 1 &&
                        <PrimaryButton
                          className="mr-15"
                          data-automation-id="test"
                          text="Previos"
                          type="button"
                          disabled={this.props.currentStep == 1 ? true : false}
                          onClick={this.props.previousStep}
                          onRenderText={this._onRenderButtonText}
                        />
                      }
                      {this.props.currentStep < this.props.totalSteps &&
                        <NewPrimaryButton
                          className="mr-15"
                          data-automation-id="test"
                          text="Next"
                          type="submit"
                          onClick={this._setFormsubmitted.bind(this)}
                          onRenderText={this._onRenderButtonText}
                          disabled={this.props.currentStep < this.props.totalSteps ? false : true}
                        />
                      }
                      {this.props.Record.entityId == 14 && (
                        <NewPrimaryButton
                          className="mr-15"
                          data-automation-id="test"
                          text={"SaveAsDraft"}
                          type="button"
                          onClick={this._saveAsDraft.bind(this)}
                          onRenderText={this._onRenderButtonText}
                        />
                      )}
                      {(this.props.Record.entityId == 24 || this.props.Record.entityId == 32 || this.props.Record.entityId == 33
                        || this.props.Record.entityId == 34 || this.props.Record.entityId == 35 || this.props.Record.entityId == 36) && (
                          <NewPrimaryButton
                            className="mr-15"
                            data-automation-id="test"
                            text={"Create"}
                            type="button"
                            onClick={this._saveAsDraft.bind(this)}
                            onRenderText={this._onRenderButtonText}
                          />
                        )}
                      {this.props.currentStep == this.props.totalSteps && this.props.Record.entityId == 14 && (
                        <NewPrimaryButton
                          className="mr-15"
                          data-automation-id="test"
                          text={"SaveAndSend"}
                          onClick={this._setFormsubmittedForTransfer.bind(this)}
                          onRenderText={this._onRenderButtonText}
                        />
                      )}
                      {this.props.currentStep == this.props.totalSteps && this.props.Record.entityId == 14 && (
                        <NewPrimaryButton
                          className=""
                          data-automation-id="test"
                          text={"SendAsDraft"}
                          onClick={this._setFormsubmittedForMoveCorrespondence.bind(this)}
                          onRenderText={this._onRenderButtonText}
                        />
                      )}
                    </div>
                  ) : (
                      <div
                        className={classnames("ms-Grid-col ms-sm12 ms-md12", {
                          [this.props.colLgBtnClass]: this.props.colLgBtnClass,
                          "ms-lg12": !this.props.colLgFieldClass
                        })}
                      >
                        <NewPrimaryButton
                          className=""
                          data-automation-id="test"
                          text={
                            this.props.actionBtnName
                              ? this.props.actionBtnName
                              : "Submit"
                          }
                          type="submit"
                          onClick={this._setFormsubmitted.bind(this)}
                          onRenderText={this._onRenderButtonText}
                        />
                      </div>
                    )}
                </div>
              }



              {this.props.currentStep == this.props.totalSteps &&
                this.props.actions &&
                this.props.actions.length > 0 ? (
                  <div className="action-btn-group">
                    {this.props.actions.map((action: WorkflowAction) => {
                      return (
                        <div style={{ display: "inline-block" }}>
                          <PrimaryButton
                            onClick={this.props.OnExecuteWorkflowAction.bind(
                              this,
                              action
                            )}
                            style={{ margin: "25px 15px 0 0" }}
                            key={action.name}
                          >
                            {action.name}
                          </PrimaryButton>
                        </div>
                      );
                    })}
                  </div>
                ) : (
                  ""
                )}
            </div>
          </form>
        </div>
        <TransferCorrespondence
          open={this.state.MultiTransferPanel}
          closeMultiTransferPanel={this.closeMultiTransferPanel.bind(this)}
          onTransferSubmit={this.transferMultiCorrespondence.bind(this)}
          Record={{ id: 0 }}
          fromCreate={true}
        />
        <MoveDraftCorrespondence open={this.state.MoveDraftCorrespondencePanel} closeMoveDraftCorrespondencePanel={this.closeMoveDraftCorrespondencePanel.bind(this)}
          onTransferSubmit={this.moveDraftCorrespondence.bind(this)}
          Record={{ id: 0 }}></MoveDraftCorrespondence>

        <Dialog
          hidden={this.state.hideDialogCancelDialoge}
          // onDismiss={this._closeCancelDialoge.bind(this)}
          dialogContentProps={{
            type: DialogType.normal,
            title:
              this._cachingService.readPersistant("Language") == 1
                ? "هل أنت متأكد من إلغاء المراسلة؟"
                : "Are you sure you want to cancel this message?",
            subText: this._cachingService.readPersistant("Language") == 1 ?
              "اذا قمت بإلغاء المراسلة فسوف يتم حذف كل المدخلات في هذه الشاشة"
              : 'By cancelling the message, you will loose all the data entered in the form.'
          }
          }
          modalProps={{
            titleAriaId: this._labelId,
            subtitleAriaId: this._subTextId,
            isBlocking: false,
            containerClassName: "ms-dialogMainOverride"
          }}
        >
          <DialogFooter>
            <PrimaryButton
              onClick={this._cancelCreateCorrespondence.bind(this)}
            >
              <FormattedMessage id="OK" />
            </PrimaryButton>
            <DefaultButton onClick={this._closeCandelDialog.bind(this)}>
              <FormattedMessage id="Cancel" />
            </DefaultButton>
            {/* <DefaultButton onClick={this._closeDialog} text="Cancel" /> */}
          </DialogFooter>
        </Dialog>
      </div>
    );
  }

  _handeusersChange(item: any, items: any) {
    //debugger;
  }
  _cancelCreateCorrespondence() {
    this.setState({ hideDialogCancelDialoge: true })
    this.props.history.push("/dashboard")
  }
  _closeCandelDialog() {
    this.setState({ hideDialogCancelDialoge: true })
  }

  private _onFormatDate = (date: any): string => {
    // return date.getDate() + '/' + (date.getMonth() + 1) + '/' + (date.getFullYear() % 100);
    return this._dateUtils.formatDateTime(date);
  };

  _openCancelDialog() {
    if (this.props.cancelFunction)
      this.props.cancelFunction();
    else
      this.setState({ hideDialogCancelDialoge: false })
  }
  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._loadingService.show();
      this._recordService.deleteRecord(record.entityId, record.id).then(
        () => {
          //this.loadRecords();
          this._loadingService.hide();

        },
        (error: any) => {
          alert(error);
          this._loadingService.hide();

        }
      );
    }
  }

  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._loadingService.show();
      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._loadingService.show();
              this._recordService.listRecords(criteria).then(result => {
                f.records = result;
                this.setState({ record: this.state.record });
                this._loadingService.hide();
              });
            }
          });
          this.setState({ record: result });
          this._loadingService.hide();
        },
        error => {
          alert(error);
          this._loadingService.hide();

        }
      );
    } else {
      this._recordService.getRecord(entityId, recordId).then(
        result => {
          if (isViewMode)
            this.setState({ selectedItem: result, showViewPanel: true });
          else this.setState({ selectedItem: result, showPanel: true });
          this._loadingService.show();

          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._loadingService.show();
              this._recordService.listRecords(criteria).then(result => {
                f.records = result;
                this.setState({ record: this.state.record });
                this._loadingService.hide();

              });
            } else if (
              f.type === FieldTypes.ReferencedEntity ||
              f.type === FieldTypes.ManyToManyRelated
            ) {
              let criteria = f.extraData as ListRecordsCriteria;
              this._loadingService.show();

              this._recordService.listRecords(criteria).then(result => {
                f.records = result;
                this.setState({ record: this.state.record });
                this._loadingService.hide();

              });
            }
          });
          this.setState({ record: result });
          this._loadingService.hide();

        },
        error => {
          alert(error);
          this._loadingService.hide();

        }
      );
    }
  }

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

  private _onCalloutDismiss = (): void => {
    this.setState({
      isCalloutVisible: false
    });
  };
  _handleDataChange(item: RecordField, value: any) {
    item.data = value;
    this.forceUpdate();
  }
  _handleHtmlDataChange(item: RecordField, value: any) {
    if (value == "<p><br></p>") {
      value = null;
    }
    item.data = value;
    this.forceUpdate();
  }
  _handleBooleanChange(
    item: RecordField,
    ev: React.FormEvent<HTMLElement>,
    selected: any
  ) {
    item.data = selected.key;
    this.forceUpdate();
  }
  //     _handleDatePickerChange(item:RecordField,value: Date) {
  //
  //         let date = new Date(value.toLocaleDateString());
  // item.data = new Date(date.getFullYear(),date.getMonth(),date.getDate());
  //     };
  _handleChoiceChange(item: RecordField, value: any) {
    if (item.multipleSelection == true) {
      if (!item.data) item.data = [];
      if (value.selected == true) item.data.push(value.key);
      else item.data.push(item.data.indexOf(value.key), 1);
    } else {
      item.data = value.key;
    }

    if (item.onChanged) item.onChanged(item);

    this.forceUpdate();
  }

  // _handleMultipleUsersChange(item: RecordField, value: any) {
  //   if (!item.data) item.data = [];
  //   if (value.selected == true) item.data.push(value.key);
  //   else item.data.push(item.data.indexOf(value.key), 1);

  //   this.forceUpdate();
  // }

  _handleMultipleUsersChange(item: RecordField, value: any) {
    if (!item.data) item.data = [];
    // if (value.selected == true) item.data.push(value.key);
    // else item.data.push(item.data.indexOf(value.key), 1);
    //debugger;
    item.data = value;
    this.forceUpdate();
  }

  _handleUserChange(item: RecordField, value: any) {
    // if (value.selected == true) item.data.push(value.key);
    // else item.data.push(item.data.indexOf(value.key), 1);
    //debugger;
    if (value.length > 0)
      item.data = value[0];
    else
      item.data = null;
    this.forceUpdate();
  }


  _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);
    }
    this.forceUpdate();
  }
  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 _onRenderButtonText = (item: any): JSX.Element => {
    return <FormattedMessage id={item.text} />;
  };
  // 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>
  //   );
  // };
}

