import * as React from "react";
import { RecordService, CachingService, EntityService, WorkflowService } from "../../../../Services";
import { FieldTypes } from "../../../../Enums";
import { IColumn } from "office-ui-fabric-react/lib/DetailsList";
import {
  Breadcrumb,
  Panel,
  PanelType,
  DefaultButton,
  IconButton,
  DocumentCard,
  OverflowSet,
  IOverflowSetItemProps,
  CommandBarButton,
  SearchBox
} from "office-ui-fabric-react/lib";
import {
  Record,
  ListRecordsCriteria,
  WorkflowHistory,
  CustomEntityFilter,
  FieldQuery
} from "../../../../Models";

import { ListView} from "../../../../Controls/ListView";
import { FiltersControl } from "../../../../Controls/FiltersControl";
import "./RecordsList.css";
import { DateUtils } from "../../../../Utils";
import { RecordsListView } from "../../../../Controls/RecordsListView";
import { Sorting } from "../../../../Models/Sorting";
import { Pagination } from "../../../../Models/Pagination";
import {
  Dialog,
  DialogType,
  DialogFooter
} from "office-ui-fabric-react/lib/Dialog";
// import { ProgressIndicator } from "office-ui-fabric-react/lib/ProgressIndicator";
import { LoadingService } from "../../../../Services/LoadingService";
import { FormattedMessage } from "react-intl";
// import { RecordsHistoryTimeline } from "../../../../Customizations/Controls/RecordsHistoryTimeLine";
// import { FormView } from "../../../../Customizations/Controls/FormView";
// import { QuickFormView } from "../../../../Customizations/Controls/QuickFormView";
// import { NewCommandBar } from "../../../../Controls/NewCommandsBar";
// import { PrimaryButton as NewPrimaryButton } from "../../../../Customizations/Controls/PrimaryButton";
export interface IData {
  columns: IColumn[];
  items: any[];
}
import classnames from "classnames";
// import { TransferCorrespondence } from "../../../../Customizations/Controls/Correspondence/TransferCorrespondence";
// import { ApproveCorrespondence } from "../../../../Customizations/Controls/Correspondence/ApproveCorrespondence";
// import { RejectCorrespondence } from "../../../../Customizations/Controls/Correspondence/RejectCorrespondence";
// import { CloseCorrespondence } from "../../../../Customizations/Controls/Correspondence/CloseCorrespondence";
// import { ReOpenCorrespondence } from "../../../../Customizations/Controls/Correspondence/ReOpenCorrespondence";
// import { FieldsControl } from "../../../../Customizations/Controls/FieldsControl";
// import { ExecuteActionButton } from "../../../../Customizations/Controls/ExecuteActionButton";
import { DynamicRecordService } from "../../../../Services/DynamicRecordService";

export class RecordsList extends React.Component<any, any> {
  private _loadingService = new LoadingService();
  private _recordService: RecordService = new RecordService();
  private _entityService: EntityService = new EntityService();
  private _workflowService: WorkflowService = new WorkflowService();
  private _dateUtils: DateUtils = new DateUtils();
  private _pageSize = 10;
  private _cachingService = new CachingService();
  private _notAuthenticated = true;
  private _loggedInUserId: number;
  private _loggedInUser: any;
  private _dynamicRecordService: DynamicRecordService = new DynamicRecordService();

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

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

    let cachingService: CachingService = new CachingService();
    let criteria = cachingService.read("Params") as ListRecordsCriteria;
    this._loggedInUserId = cachingService.read("UserId");
    this._loggedInUser = cachingService.read("LoggedInUser");
    this._loadingService.show();

    // let screenIconClassName =  cachingService.read("screenIconClassName");
    if (!criteria) {
      criteria = new ListRecordsCriteria();
      criteria.asLookup = false;
      // criteria.entityId = this.props.match.params.id;
    }

    if (this.props.criteria)
      criteria = this.props.criteria

    criteria.pagination = new Pagination();
    criteria.pagination.start = 0;
    criteria.pagination.count = this._pageSize;

    this.state = {
      fullTextSearch: '',
      hideDialog: true,
      hideArchiveDialog: true,
      entityId: criteria.entityId,
      showModal: false,
      selectedItem: { entityId: criteria.entityId },
      commands: new Array<any>(),
      criteria: criteria,
      showPanel: false,
      showWorkflowHistoryPanel: false,
      workflowHistory: new Array<WorkflowHistory>(),
      historyColumns: this.loadWorkflowHistoryColumns(),
      showViewPanel: false,
      showRecordViewPanel: false,
      records: new Array<Record>(),
      history: new Array<Record>(),
      totalNumberOfRecords: 0,
      totalPages: 0,
      screenIconClassName: cachingService.read("screenIconClassName"),
      screenTitle: cachingService.read("screenTitle"),
      loadingData: false,

      approvePanel: false,
      RejectPanel: false,
      CloseCorrespondencePanel: false,
      ReOpenCorrespondencePanel: false,
      MultiTransferPanel: false,
      showReplyNewPanel: false,
      showQuickView: false,
      filters: [],
      selectedFilter: null,
      showFilters: false,

      workflowActions: []
    };

    this.loadRecords();
    this.getFilters();
  }

  private getCorrespondenceActions() {
    if (this.state.selectedItem) {
      let criteria: ListRecordsCriteria = new ListRecordsCriteria();
      criteria.asLookup = false;
      criteria.entityId = 28;
      criteria.query = new Array<FieldQuery>();
      let query = new FieldQuery();
      query.fieldId = 280;
      query.value = this.state.selectedItem.id;
      criteria.query.push(query);
      criteria.pagination = new Pagination();
      criteria.pagination.start = 0;
      criteria.pagination.count = 99999;

      this._loadingService.show();
      this._dynamicRecordService.listRecords(criteria).then(
        (result: any) => {
          this._loadingService.hide();
          console.log(result);

          // this.state.reasonLookups = result;
          this.setState({ correspondenceActions: result });
          this.setState({
            commands: this.getRecordCommands(this.state.selectedItem)
          });
        },
        error => {
          // alert(error.text());
          // this.toastr.error('', error.text());
          //this.displayAlertModal(error.text());
          alert(error);
          this._loadingService.hide();
        }
      );
    }
  }

  isActionAuthorized(actionName: string) {
    let isAuthorized: boolean = false;
    if (this.state.correspondenceActions) {
      this.state.correspondenceActions.forEach((action: any) => {
        if (action.Name == actionName)
          isAuthorized = true;
      });
    }

    return isAuthorized;
  }

  private _onRenderItem = (item: any): JSX.Element | null => {
    // debugger;
    return <FormattedMessage id={item.text} />;
  };

  private getFilters() {
    let _this = this;
    this._entityService.listFilters(this.state.entityId).then(
      (result: any) => {

        console.log(result);

        result.forEach((filter: CustomEntityFilter) => {
          if (filter.criteria && filter.criteria.query) {
            filter.criteria.query.forEach((query: FieldQuery) => {
              if (query.value)
                query.value = query.value.replace("{{loggedInDepartmentId}}", _this._loggedInUser.organizationUnit.id)
            })
          }
        });

        // this.state.reasonLookups = result;
        this.setState({ filters: result });
      },
      error => {
        // alert(error.text());
        // this.toastr.error('', error.text());
        //this.displayAlertModal(error.text());
        alert(error);
        this._loadingService.hide();
      }
    );
  }

  private loadWorkflowActions(record: any) {
    this._loadingService.show();
    this._workflowService.getWorkflowActions(this.state.entityId, 0, record.id).then(
      (result: any) => {

        console.log(result);
        this._loadingService.hide();
        // this.state.reasonLookups = result;
        this.setState({ workflowActions: result });

        this.setState({
          commands: this.getRecordCommands(
            record
          )
        });
      },
      error => {
        // alert(error.text());
        // this.toastr.error('', error.text());
        //this.displayAlertModal(error.text());
        alert(error);
        this._loadingService.hide();
      }
    );
  }


  private loadWorkflowHistoryColumns() {
    let historyColumns = new Array<any>();
    historyColumns.push({
      dataType: "string",
      fieldName: "action",
      name: "Action",
      minWidth: 50,
      maxWidth: 100
    });
    historyColumns.push({
      dataType: "string",
      fieldName: "dateOfAction",
      name: "Date of action",
      minWidth: 50,
      maxWidth: 100,
      onRender: (item?: any, index?: number, column?: IColumn) => {
        return <div>{this._dateUtils.formatDateTime(item.dateOfAction)}</div>;
      }
    });
    historyColumns.push({
      dataType: "string",
      fieldName: "notes",
      name: "Notes",
      minWidth: 50,
      maxWidth: 100
    });
    historyColumns.push({
      dataType: "string",
      fieldName: "state",
      name: "State",
      minWidth: 50,
      maxWidth: 100
    });

    return historyColumns;
  }

  private getCommonCommands(): any[] {
    let commands = new Array<any>();
    // commands.push(
    //     {
    //         key: "addRecord",
    //         name: "CreateRecord",
    //         icon: "Add",
    //         onClick: this.addRecord.bind(this)
    //     });
    return commands;
  }
  private getRecordCommands(record: Record): any[] {
    let commands = this.getCommonCommands();
    if (record && record.id) {


      commands.push(
        // {
        //     key: "removeRecord",
        //     name: "Remove",
        //     icon: "Remove",
        //     onClick: this._showDeleteDialog.bind(this) //this.deleteRecord.bind(this)
        // },

        {
          key: "ViewRecord",
          name: this._cachingService.readPersistant("Language") == 1 ? "عرض" : "View",
          iconProps: {
            iconName: "View"
          },
          onClick: this.viewEntityRecord.bind(this)
        }
      );

      if (false && record.hasWorkflow) {
        commands.push({
          key: "workflowHistory",
          name: "History",
          icon: "History",
          onClick: this.viewRecordWorkflowHistory.bind(this)
        });
      }

      commands.push({
        key: "history",
        name: this._cachingService.readPersistant("Language") == 1 ? "تسلسل الأحداث" : "History",
        iconProps: {
          iconName: "History"
        },
        onClick: this.viewRecordHistory.bind(this)
      });

      commands = commands.concat(this._getWorkflowCommands(record));

      commands = commands.concat(this._getActualWorkflowCommands(record));
    }
    return commands;
  }

  private _getActualWorkflowCommands(record: Record) {
    let commands = new Array<any>();

    this.state.workflowActions.forEach((workflowAction: any) => {
      commands.push({
        key: workflowAction.displayName,
        name: workflowAction.displayName,
        iconProps: {
          className: workflowAction.iconClassName
        },
        onRender: (item: any) => {
          return null;
          // return (<ExecuteActionButton style={{ 'height': '100%' }} onExecute={this.onExecuteWorkflowAction.bind(this)} workflowAction={workflowAction} entityId={this.state.entityId}
          //   recordId={this.state.selectedItem.id}
          //   Record={this.state.selectedItem}>
          //   <FormattedMessage id={item.name || "command"} />
          // </ExecuteActionButton>)
        }
      });
    });

    return commands;
  }

  // private onExecuteWorkflowAction() {
  //   debugger;
  //   //this.loadWorkflowActions(this.state.selectedItem)
  //   this.loadRecords();
  //   this.getRecord(this.state.entityId, this.state.selectedItem.id, true);
  //   this.setState({ 'selectedItem': { entityId: this.state.entityId, id: this.state.selectedItem.id } })
  // }

  private _getWorkflowCommands(record: Record) {
    let commands = new Array<any>();
    let status: number = -1;

    if (record && record.fields) {
      record.fields.forEach((field: any) => {
        if (field.id == 176) status = field.data;

        // if (field.Id == 181 || field.Id == 182 || field.Id == 192 || field.Id == 194 || field.Id == 199
        //     || field.Id == 200 || field.Id == 201 || field.Id == 202)
        //     field.hidden = true;
        // else
        //     field.hidden = false;
      });
    }

    if (status == -1) return commands;

    if (status == 22) {
      commands.push({
        key: "edit",
        name: "Edit",
        iconProps: {
          iconName: "Edit"
        },
        onClick: this.editRecord.bind(this)
      });
    }

    if (status != 62 && status != 103 && status != 104)
      commands.push({
        key: "Forward",
        name: this._cachingService.readPersistant("Language") == 1 ? "إرسال" : "Forward",
        iconProps: {
          iconName: "Forward"
        },
        onClick: this.showTransferPanel.bind(this)
      });

    // if (status != 62 && status != 22 && status != 103 && status != 104)
    //   commands.push({
    //     key: "ReplyNew",
    //     name: this._cachingService.readPersistant("Language") == 1 ? "Send New" : "Send New",
    //     iconProps: {
    //       iconName: "DocumentReply"
    //     },
    //     onClick: this.replyNewCorrespondence.bind(this)
    //   });

    // if (status != 62 && status != 22 && status != 103 && status != 104 && this.isActionAuthorized('Approve'))
    //   commands.push({
    //     key: "Approve",
    //     name: this._cachingService.readPersistant("Language") == 1 ? "موافق" : "Approve",
    //     iconProps: {
    //       iconName: "Reply"
    //     },
    //     onClick: this.showApprovePanel.bind(this)
    //   });

    // if (status != 62 && status != 22 && status != 103 && status != 104 && this.isActionAuthorized('Reject'))
    //   commands.push({
    //     key: "Reject",
    //     name: this._cachingService.readPersistant("Language") == 1 ? "غير موافق" : "Reject",
    //     iconProps: {
    //       iconName: "Reply"
    //     },
    //     onClick: this.showRejectPanel.bind(this)
    //   });

    // if (status != 62 && status != 22 && status != 103 && status != 104)
    //   commands.push({
    //     key: "Close",
    //     name: this._cachingService.readPersistant("Language") == 1 ? "إغلاق" : "Close",
    //     iconProps: {
    //       iconName: "ClosePane"
    //     },
    //     onClick: this.showCloseCorrespondencePanel.bind(this)
    //   });

    //commands = commands.concat(this.showReOpenButton(record, status));
    //commands = commands.concat(this.showArchiveButton(record, status));

    return commands;
  }

  showReOpenButton(record: Record, status: number) {
    let commands = new Array<any>();
    if (!record || !record.fields) return commands;
    //debugger;
    if (status == 62) {
      let initiator = 0;
      let canBeOpened;

      record.fields.forEach((field: any) => {
        if (field.id == 197) {
          initiator = field.data;
        }

        if (field.id == 201) {
          canBeOpened = field.data;
        }
      });

      if (initiator == this._loggedInUserId && canBeOpened == true) {
        commands.push({
          key: "ReOpen",
          name: this._cachingService.readPersistant("Language") == 1 ? "إعادة فتح" : "ReOpen",
          iconProps: {
            iconName: "OpenPane"
          },
          onClick: this.showReOpenCorrespondencePanel.bind(this)
        });
      }

      return commands;
    }

    return commands;
  }

  showArchiveButton(record: Record, status: number) {
    let commands = new Array<any>();
    if (!record || !record.fields) return commands;
    //debugger;
    if (status == 62 || status == 104) {
      let initiator = 0;

      record.fields.forEach((field: any) => {
        if (field.id == 197) {
          initiator = field.data;
        }
      });

      if (initiator == this._loggedInUserId) {
        commands.push({
          key: "Archive",
          name: this._cachingService.readPersistant("Language") == 1 ? "إعادة فتح" : "Archive",
          iconProps: {
            iconName: "Archive"
          },
          onClick: this._showArchiveDialog.bind(this)
        });
      }

      return commands;
    }

    return commands;
  }

  private showTransferPanel(button: any) {
    this.setState({ MultiTransferPanel: true });
  }

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

  // private transferMultiCorrespondence(
  //   obj: CorrespondenceTransfer,
  //   button: any
  // ) {
  //   if (button && button.block) button.block();
  //   this._recordService.transferCorrespondence(obj).then(
  //     () => {
  //       this.setState({ MultiTransferPanel: false });
  //       this.getRecord(this.state.selectedItem.entityId, this.state.selectedItem.id, true);
  //       if (button && button.unblock) button.unblock();
  //     },
  //     (error: any) => {
  //       alert(error);
  //     }
  //   );
  // }

  // private showApprovePanel(button: any) {
  //   this.setState({ approvePanel: true });
  // }

  // private closeApprovePanel() {
  //   this.setState({ approvePanel: false });
  // }

  // private showRejectPanel(button: any) {
  //   this.setState({ RejectPanel: true });
  // }

  // private closeRejectPanel() {
  //   this.setState({ RejectPanel: false });
  // }

  // private showCloseCorrespondencePanel(button: any) {
  //   this.setState({ CloseCorrespondencePanel: true });
  // }

  // private closeCloseCorrespondencePanel() {
  //   this.setState({ CloseCorrespondencePanel: false });
  // }

  // OnPostCloseCorrespondence() {
  //   this.setState({ CloseCorrespondencePanel: false, status: 62, buttons: this._getButtons(62) });
  // }

  showReOpenCorrespondencePanel(button: any) {
    this.setState({ ReOpenCorrespondencePanel: true });
  }

  closeReOpenCorrespondencePanel() {
    this.setState({ ReOpenCorrespondencePanel: false });
  }

  private closeReplyNewPanel() {
    this.setState({ showReplyNewPanel: false });
  }

  private renderReplyNewPanelBody = (): JSX.Element => {
    return (
      <div>
        {/* <FieldsControl Record={this.state.emptyCorrespondence}
          fields={this.state.emptyCorrespondence.fields}
          actions={this.state.emptyCorrespondence.actions}
          panelMode={true} /> */}
      </div>
    );
  };

  private renderReplyNewPanelFooterContent = (): JSX.Element => {
    return (
      <div className="sticky-footer-btns">
        {/* <NewPrimaryButton
          onClick={this.postReply.bind(this)}
          className="panel-footer-btn"
        >
          <FormattedMessage id="Reply" />
        </NewPrimaryButton>
        <DefaultButton
          className="panel-footer-btn"
          onClick={() => {
            return this.closeReplyNewPanel();
          }}
        >
          <FormattedMessage id="Cancel" />
        </DefaultButton> */}
      </div>
    );
  };

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

  //   //debugger;
  //   let replyObj = new CorrespondenceReply();
  //   replyObj.correspondenceId = this.state.selectedItem.id;
  //   replyObj.newCorrespondence = this.state.emptyCorrespondence;
  //   this._loadingService.show();
  //   this._recordService.replyWithNewCorrespondence(replyObj).then(
  //     result => {
  //       //this.loadRecords();
  //       this.setState({ showReplyNewPanel: false });
  //       if (button && button.unblock) button.unblock();
  //       this._loadingService.hide();

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

  //     }
  //   );
  // }

  replyNewCorrespondence(button: any) {
    if (button && button.block) button.block();
    this._loadingService.show();

    this._recordService.getEmptyCorrespondenceRecordForReply(14).then(
      result => {
        // debugger;
        this.setState({ emptyCorrespondence: result, showReplyNewPanel: true });
        if (button && button.unblock) button.unblock();
        this._loadingService.hide();

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

      }
    );
  }

  private selectedRecordChanged(entity: any) {
    if (!entity) return;

    this.setState({
      selectedItem: entity,
      commands: this.getRecordCommands(entity)
    });
    this.getCorrespondenceActions();
    this.getRecord(entity.entityId, entity.id, true);
  }

  private _onRenderOverflowItem(item: IOverflowSetItemProps): JSX.Element {
    if (item.onRender) {
      return item.onRender(item);
    }
    return <CommandBarButton style={{ background: 'transparent' }} iconProps={{ className: 'fal fa-filter' }} menuProps={item.subMenuProps}
      text={item.name} />;
  }

  private _onRenderOverflowButton(overflowItems: any[] | undefined): JSX.Element {
    return (
      <CommandBarButton style={{ background: 'transparent' }} menuIconProps={{ iconName: 'More' }} menuProps={{ items: overflowItems! }} />
    );
  }

  private changeFullTextSearch(value: any) {

    this.setState({ 'fullTextSearch': value })
    //this.loadRecords(undefined, value);
  }

  private applyFullTextSearch(value: any) {

    this.loadRecords();
  }
  private pressEnterOnSearch(e: any) {
    debugger;
  }

  private toggleFitlers() {
    this.setState({ showFilters: !this.state.showFilters })
  }

  private applyFilters(fieldQueries: FieldQuery[]) {
    let criteria: ListRecordsCriteria;

    criteria = this._cachingService.read("Params") as ListRecordsCriteria;

    criteria.query = criteria.query.concat(fieldQueries);

    criteria.pagination = new Pagination();
    criteria.pagination.start = 0;
    criteria.pagination.count = this._pageSize;

    this.loadRecords(criteria);
  }

  public render(): JSX.Element {

    if (this._notAuthenticated) {
      return (<div></div>);
    }

    var replyNewTitle = "Reply";

    if (this.state.selectedItem && this.state.selectedItem.fields) {
      this.state.selectedItem.fields.forEach((field: any) => {
        if (field.id == 170)
          replyNewTitle = "{ " + field.data + " } - " + replyNewTitle;
      });
    }

    // debugger;
    return (
      <div>
        <div className="ms-Grid-row">
          <div className="ms-Grid-col ms-sm12">
            <div className="breadcrumb-container">
              <i className={this.state.screenIconClassName} />
              <Breadcrumb
                items={[
                  { text: this.state.screenTitle, key: this.state.screenTitle }
                ]}
                ariaLabel={"Website breadcrumb"}
                onRenderItem={this._onRenderItem}
              />
            </div>
            <div
              className={classnames(
                "ms-Grid-col ms-sm12 ms-md12",
                { "ms-lg6": this.state.selectedItem.fields && this.state.showQuickView },
                { "ms-lg12": !this.state.selectedItem.fields && !this.state.showQuickView }
              )}
            >
              <DocumentCard className="w-100p layout-card">
                <div className="">
                  {/* {this.state.loadingData && (
                    <ProgressIndicator barHeight={3} />
                  )} */}
                  <div style={{ display: 'inline-table', 'width': '100%' }}>
                    <OverflowSet className="recordsListTopMenu"
                      items={[
                        {
                          key: 'search',
                          onRender: (item: any) => {
                            return <SearchBox placeholder={this._cachingService.readPersistant("Language") == 0 ? "Search" : "بحث"} onChange={this.changeFullTextSearch.bind(this)}
                              onBlur={this.applyFullTextSearch.bind(this)} onKeyPress={this.pressEnterOnSearch.bind(this)} />;
                          }
                        },
                        {
                          key: 'Filter',
                          name: 'Filters',
                          icon: 'Add',
                          ariaLabel: 'Filters',
                          onRender: () => {
                            return <CommandBarButton onClick={this.toggleFitlers.bind(this)}
                              style={{ marginLeft: '10px', background: this.state.showFilters ? 'rgba(200, 200, 200, 0.2)' : 'transparent' }}
                              iconProps={{ className: 'fal fa-filter' }}
                            ><FormattedMessage id='Filters'></FormattedMessage></CommandBarButton>
                          }
                        }
                      ]}
                      onRenderOverflowButton={this._onRenderOverflowButton}
                      onRenderItem={this._onRenderOverflowItem}
                    />
                  </div>

                  <div style={{ display: (this.state.showFilters ? '' : 'none') }}>
                    <FiltersControl entityId={this.state.entityId} applyFilters={this.applyFilters.bind(this)}
                      filters={this.state.filters}></FiltersControl>
                  </div>
                  <div>
                    {/* <NewCommandBar Commands={this.state.commands} /> */}
                  </div>
                  <div className="">
                    <RecordsListView
                      defaultSorting={this.state.criteria.sorting}
                      TotalPages={this.state.totalPages}
                      Records={this.state.records}
                      LoadRecordsWithNewCriteria={this.loadRecordsWithNewCriteria.bind(
                        this
                      )}
                      SelectedRecordChanged={this.selectedRecordChanged.bind(
                        this
                      )}
                    />
                  </div>
                </div>
              </DocumentCard>
            </div>
            <div
              className={classnames(
                "ms-Grid-col ms-sm12 ms-md12",
                { "ms-lg6": this.state.selectedItem.fields && this.state.showQuickView },
                { "d-none": !this.state.showQuickView }
              )}
            >
              <DocumentCard
                className={
                  "w-100p layout-card quickview-card " +
                  this.state.selectedItem.fields
                }
              >
                <div className="quickview-header">
                  <IconButton
                    iconProps={{ iconName: "Clear" }}
                    title="close"
                    ariaLabel="close"
                    onClick={this.closeQuickView.bind(this)}
                  />
                </div>
                <div className="">
                  <div className="">
                    {/* {this.state.selectedItem.fields && (
                      <QuickFormView
                        OnExecuteWorkflowAction={this.executeAction.bind(this)}
                        Record={this.state.selectedItem}
                      />
                    )} */}
                  </div>
                </div>
              </DocumentCard>
            </div>
          </div>
        </div>
        {/* <div className="layout-card"> */}
        {/* <div className="">
                        {this.state.loadingData && <ProgressIndicator barHeight={3} />}
                        <div><CommandsBar Commands={this.state.commands} /></div>
                        <div className="" >
                            <RecordsListView TotalPages={this.state.totalPages} Records={this.state.records}
                                LoadRecordsWithNewCriteria={this.loadRecordsWithNewCriteria.bind(this)}
                                SelectedRecordChanged={this.selectedRecordChanged.bind(this)}></RecordsListView>
                        </div>
                    </div> */}
        <Panel
          className="panelStyle"
          isOpen={this.state.showPanel}
          onDismissed={this.closePanel.bind(this)}
          type={PanelType.large}
          onRenderFooter={this.renderPanelFooterContent.bind(this)}
          onRenderBody={this.renderPanelBody.bind(this)}
          isFooterAtBottom={true}
          headerText="RecordDetails"
          headerClassName="panelHeaderStyle"
          hasCloseButton={false}
          isBlocking={true}
          onRenderHeader={this._onReadnderHader}
        />
        <Panel
          className="panelStyle"
          isOpen={this.state.showViewPanel}
          onDismissed={this.closeViewPanel.bind(this)}
          type={PanelType.medium}
          isFooterAtBottom={true}
          onRenderBody={this.viewRecordrenderPanelBody.bind(this)}
          headerText="ViewRecord"
          headerClassName="panelHeaderStyle"
          hasCloseButton={false}
          isLightDismiss={true}
          isBlocking={true}
          onRenderHeader={this._onReadnderHader}
        />
        <Panel
          className="panelStyle"
          isOpen={this.state.showRecordViewPanel}
          onDismissed={this.closeRecordViewPanel.bind(this)}
          type={PanelType.medium}
          isFooterAtBottom={true}
          onRenderBody={this.showViewRecordrenderPanelBody.bind(this)}
          headerText="ViewRecord"
          headerClassName="panelHeaderStyle"
          hasCloseButton={false}
          isLightDismiss={true}
          onRenderHeader={this._onReadnderHader}
        />
        <Panel
          className="panelStyle"
          isOpen={this.state.showWorkflowHistoryPanel}
          onDismissed={this.closeWorkflowHistoryPanel.bind(this)}
          type={PanelType.custom}
          onRenderBody={this.renderWorkflowHistoryPanelBody.bind(this)}
          headerText="History"
          isFooterAtBottom={true}
          headerClassName="panelHeaderStyle"
          hasCloseButton={false}
          isLightDismiss={true}
          customWidth="390px"
        />
        <Panel
          className="panelStyle"
          isOpen={this.state.showHistoryPanel}
          onDismissed={this.closeHistoryPanel.bind(this)}
          type={PanelType.custom}
          onRenderBody={this.renderHistoryPanelBody.bind(this)}
          headerText="History"
          headerClassName="panelHeaderStyle"
          isFooterAtBottom={true}
          hasCloseButton={false}
          isLightDismiss={true}
          isBlocking={true}
          onRenderHeader={this._onReadnderHader}
          customWidth="390px"
        />
        <Dialog
          hidden={this.state.hideDialog}
          onDismiss={this._closeDeleteDialog}
          dialogContentProps={{
            type: DialogType.normal,
            title:
              this._cachingService.readPersistant("Language") == 0
                ? "Delete"
                : "حذف",
            subText:
              this._cachingService.readPersistant("Language") == 0
                ? "Are you sure you want to delete the selected record?"
                : "هل تريد حذف هذه المراسلة؟"
          }}
          modalProps={{
            titleAriaId: "myLabelId",
            subtitleAriaId: "mySubTextId",
            isBlocking: false,
            containerClassName: "ms-dialogMainOverride"
          }}
        >
          {
            null /** You can also include null values as the result of conditionals */
          }
          <DialogFooter>
            {/* <NewPrimaryButton
              onClick={this.deleteRecord.bind(this)}
              text="Delete"
              onRenderText={this._onRenderButtonText}
            /> */}
            <DefaultButton
              onClick={this._closeDeleteDialog}
              text="Cancel"
              onRenderText={this._onRenderButtonText}
            />
          </DialogFooter>
        </Dialog>
        <Dialog
          hidden={this.state.hideArchiveDialog}
          onDismiss={this._closeArchiveDialog}
          dialogContentProps={{
            type: DialogType.normal,
            title:
              this._cachingService.readPersistant("Language") == 0
                ? "Archive"
                : "الأرشيف",
            subText:
              this._cachingService.readPersistant("Language") == 0
                ? "Are you sure you want to archive the selected record?"
                : "هل أنت متأكد انك تريد أرشفة هذه المراسلة؟"
          }}
          modalProps={{
            titleAriaId: "myLabelId",
            subtitleAriaId: "mySubTextId",
            isBlocking: false,
            containerClassName: "ms-dialogMainOverride"
          }}
        >
          {
            null /** You can also include null values as the result of conditionals */
          }
          <DialogFooter>
            {/* <NewPrimaryButton
              onClick={this.archiveRecord.bind(this)}
              text="Archive"
              onRenderText={this._onRenderButtonText}
            /> */}
            <DefaultButton
              onClick={this._closeArchiveDialog}
              text="Cancel"
              onRenderText={this._onRenderButtonText}
            />
          </DialogFooter>
        </Dialog>
        {/* <TransferCorrespondence
          open={this.state.MultiTransferPanel}
          closeMultiTransferPanel={this.closeMultiTransferPanel.bind(this)}
          onTransferSubmit={this.transferMultiCorrespondence.bind(this)}
          Record={this.state.selectedItem}
        />

        <ApproveCorrespondence
          open={this.state.approvePanel}
          closeApprovePanel={this.closeApprovePanel.bind(this)}
          Record={this.state.selectedItem}
        />

        <RejectCorrespondence
          open={this.state.RejectPanel}
          closeRejectPanel={this.closeRejectPanel.bind(this)}
          Record={this.state.selectedItem}
        />

        <CloseCorrespondence
          open={this.state.CloseCorrespondencePanel}
          closeCloseCorrespondencePanel={this.closeCloseCorrespondencePanel.bind(
            this
          )}
          OnPostSubmit={() => {
            this.closeCloseCorrespondencePanel();
            this.getRecord(this.state.selectedItem.entityId, this.state.selectedItem.id, true);
          }}
          Record={this.state.selectedItem}
        />

        <ReOpenCorrespondence
          open={this.state.ReOpenCorrespondencePanel}
          closeReOpenCorrespondencePanel={this.closeReOpenCorrespondencePanel.bind(
            this
          )}
          Record={this.state.selectedItem}
        /> */}

        <Panel
          className="panelStyle"
          isOpen={this.state.showReplyNewPanel}
          onDismissed={this.closeReplyNewPanel.bind(this)}
          type={PanelType.large}
          onRenderFooter={this.renderReplyNewPanelFooterContent.bind(this)}
          onRenderBody={this.renderReplyNewPanelBody.bind(this)}
          headerText={replyNewTitle}
          isFooterAtBottom={true}
          //styles={{ IsFooterSticky: true }}
          headerClassName="panelHeaderStyle"
          hasCloseButton={false}
          isBlocking={true}
          onRenderHeader={this._onReadnderHader}
        />
        {/* </div> */}
      </div>
    );
  }
  private closePanel() {
    this.setState({ showPanel: false });
  }
  private closeViewPanel() {
    this.setState({ showViewPanel: false });
  }
  private closeRecordViewPanel() {
    this.setState({ showRecordViewPanel: false });
  }
  private closeWorkflowHistoryPanel() {
    this.setState({ showWorkflowHistoryPanel: false });
  }
  private closeHistoryPanel() {
    this.setState({ showHistoryPanel: false });
  }
  private renderPanelFooterContent = (): JSX.Element => {
    return (
      <div>
        <div className="ms-Grid-row">
          {/* <NewPrimaryButton
            className="panel-footer-btn"
            onClick={this.saveRecord.bind(this)}
          >
            <FormattedMessage id="SaveAsDraft" />
          </NewPrimaryButton>
          <DefaultButton
            className="panel-footer-btn"
            onClick={() => {
              return this.closePanel();
            }}
          >
            Cancel
          </DefaultButton> */}
        </div>
      </div>
    );
  };

  private renderWorkflowHistoryPanelBody = (): JSX.Element => {
    return (
      <div style={{ padding: 30, paddingTop: 10 }}>
        <ListView
          selectionModeType={false}
          Items={this.state.workflowHistory}
          Columns={this.state.historyColumns}
        />
      </div>
    );
  };
  private renderHistoryPanelBody = (): JSX.Element => {
    return (
      <div>
        {/* <RecordsHistoryTimeline Items={this.state.history} /> */}
      </div>
    );
  };
  private renderPanelBody = (): JSX.Element => {
    return (
      <div>
        {/* <FieldsControl
          OnExecuteWorkflowAction={this.executeAction.bind(this)}
          Record={this.state.selectedItem}
          fields={this.state.selectedItem.fields}
          actions={this.state.selectedItem.actions}
          panelMode={true}
        /> */}
      </div>
    );
  };

  // private refreshTable() {
  //   this.setState({
  //     selectedItem: { entityId: this.state.entityId },
  //     commands: this.getCommonCommands(),
  //     showQuickView: false
  //   });
  //   this.loadRecords();
  // }

  private viewRecordrenderPanelBody = (): JSX.Element => {
    return (
      <div style={{ padding: 30, paddingTop: 10 }}>
        {/* <FieldsControl
          OnExecuteWorkflowAction={this.executeAction.bind(this)}
          Record={this.state.selectedItem}
          fields={this.state.selectedItem.fields}
          actions={this.state.selectedItem.actions}
          panelMode={true}
        /> */}
      </div>
    );
  };
  // private showHeader =(item:any): JSX.Element => {
  //     return(
  //         <div className="panelHeaderTitle">{item}</div>
  //     )
  // }
  private showViewRecordrenderPanelBody = (): JSX.Element => {
    //debugger;
    return (
      <div>
        {/* <FormView refreshTable={this.refreshTable.bind(this)}
          loadRecord={this.getRecord.bind(this, this.state.selectedItem.entityId, this.state.selectedItem.id)}
          closePanel={this.closeRecordViewPanel.bind(this)}
          OnExecuteWorkflowAction={this.executeAction.bind(this)}
          Record={this.state.selectedItem}
        /> */}
      </div>
    );
  };

  // private executeAction(record: Record, action: WorkflowAction) {
  //   return (): void => {

  //     this.loadRecords();
  //     this.setState({
  //       records: this.state.records,
  //       showPanel: false,
  //       commands: this.getCommonCommands()
  //     });

  //     return;

  //     this._loadingService.hide();

  //     this.setState({ loadingData: true });
  //     this._loadingService.show();

  //     this._recordService
  //       .executeAction(action.id, record.entityId, record)
  //       .then(
  //         result => {
  //           this.loadRecords();
  //           this.setState({
  //             records: this.state.records,
  //             showPanel: false,
  //             commands: this.getCommonCommands()
  //           });
  //           this._loadingService.hide();

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

  //         }
  //       );
  //   };
  // }
  // private addRecord() {
  //     this.getRecord(this.state.entityId, 0, false);
  // }

  private editRecord() {
    if (this.state.selectedItem) {
      this.props.history.push("/recordWizard/" + this.state.selectedItem.id)
    }
  }
  private viewEntityRecord() {
    //debugger;
    if (this.state.selectedItem.fields) {
      this.setState({ showRecordViewPanel: true });
    }
  }

  // private viewRecord() {
  //     if (this.state.selectedItem) {
  //         this.getRecord(this.state.selectedItem.entityId, this.state.selectedItem.id, true);
  //     }
  // }

  private viewRecordWorkflowHistory() {
    if (this.state.selectedItem) {
      this._loadingService.show();

      this.setState({ loadingData: true });
      this._recordService
        .getWorkflowHistory(
          this.state.selectedItem.entityId,
          this.state.selectedItem.id
        )
        .then(result => {
          let historyItems = new Array<any>();
          if (result && result.length > 0) {
            result.forEach((item: WorkflowHistory) => {
              historyItems.push({
                dateOfAction: item.dateOfAction,
                notes: item.notes,
                state: item.state ? item.state.name : "",
                action: item.action ? item.action.name : ""
              });
            });

          }
          this.setState({
            loadingData: false,
            showWorkflowHistoryPanel: true,
            workflowHistory: historyItems
          });
          this._loadingService.hide();
        });


    }
  }

  private viewRecordHistory() {
    if (this.state.selectedItem) {
      this._loadingService.show();

      this.setState({ loadingData: true });
      this._recordService
        .getHistory(
          this.state.selectedItem.entityId,
          this.state.selectedItem.id
        )
        .then(result => {
          this.setState({
            loadingData: false,
            showHistoryPanel: true,
            history: result
          });
          this._loadingService.hide();

        });
    }
  }

  // private saveRecord(button: any) {
  //   if (button && button.block) button.block();
  //   this._loadingService.show();
  //   return (): void => {
  //     this.setState({ loadingData: true });
  //     this._recordService.saveRecord(this.state.selectedItem).then(
  //       result => {
  //         this.loadRecords();
  //         this.setState({ showPanel: false });
  //         if (button && button.unblock) button.unblock();
  //         this._loadingService.hide();
  //       },
  //       error => {
  //         alert(error);
  //         if (button && button.unblock) button.unblock();
  //         this._loadingService.hide();
  //       }
  //     );
  //   };
  // }

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

  //   this._closeDeleteDialog();

  //   if (this.state.selectedItem) {
  //     this.setState({ loadingData: true });
  //     this._loadingService.show();
  //     this._recordService
  //       .deleteRecord(
  //         this.state.selectedItem.entityId,
  //         this.state.selectedItem.id
  //       )
  //       .then(
  //         result => {
  //           this.loadRecords();
  //           if (button && button.block) button.block();
  //           this._loadingService.hide();

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

  //         }
  //       );
  //   }
  // }

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

  //   this._closeArchiveDialog();

  //   if (this.state.selectedItem) {
  //     this.setState({ loadingData: true });
  //     this._recordService
  //       .archiveRecord(
  //         this.state.selectedItem.entityId,
  //         this.state.selectedItem.id
  //       )
  //       .then(
  //         result => {
  //           this.loadRecords();
  //           if (button && button.block) button.block();
  //         },
  //         error => {
  //           alert(error);
  //           if (button && button.block) button.block();
  //         }
  //       );
  //   }
  // }

  loadRecordsWithNewCriteria = (
    sorted: number,
    sortedDescending: boolean,
    page: number
  ) => {
    const criteria = this.state.criteria;

    if (sorted > -1) {
      criteria.sorting = new Sorting();
      criteria.sorting.fieldId = sorted;
      criteria.sorting.direction = sortedDescending == true ? 1 : 0;
    } else {
      criteria.sorting = null;
    }

    criteria.pagination = new Pagination();
    criteria.pagination.start = page;
    criteria.pagination.count = this._pageSize;

    this.loadRecords(criteria);
  };

  loadRecords = (criteria?: ListRecordsCriteria, fullTextSearch: string = '') => {
    //debugger;
    this.setState({ loadingData: true });
    let _criteria = new ListRecordsCriteria();

    if (criteria) _criteria = criteria;
    else _criteria = this.state.criteria;

    if (fullTextSearch)
      _criteria.fullTextSearch = fullTextSearch;
    else
      _criteria.fullTextSearch = this.state.fullTextSearch;

    this._loadingService.show();
    this._recordService.listRecords(_criteria).then(
      result => {
        let totalPages = Math.ceil(
          result.totalNumberOfRecords / this._pageSize
        );
        this._loadingService.hide();
        this.setState(
          {
            loadingData: false,
            criteria: _criteria,
            totalNumberOfRecords: result.totalNumberOfRecords,
            totalPages: totalPages,
            records: result.records,
            commands: this.getRecordCommands(this.state.selectedItem)
          },
          () => {
            this.forceUpdate();
          }
        );
        this._loadingService.hide();
      },
      error => {
        alert(error);
        this._loadingService.hide();
      }
    );
  };

  private getRecord(entityId: number, recordId: number, isViewMode: boolean) {
    this.setState({ loadingData: true });
    this._loadingService.show();
    if (recordId == 0) {
      this._recordService.getEmptyRecord(entityId).then(
        result => {
          // debugger;
          if (isViewMode)
            this.setState({ selectedItem: result, showViewPanel: true });
          // this.setState({ selectedItem: result, showRecordViewPanel: 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({ loadingData: false, record: result });
          this._loadingService.hide();

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

        }
      );
    } else {
      this._recordService.getRecord(entityId, recordId).then(
        result => {

          this.loadWorkflowActions(result);

          if (isViewMode)
            this.setState({
              selectedItem: result,
              commands: this.getRecordCommands(
                result
              ),  /*showRecordViewPanel: true */
              showQuickView: true
            });
          // this.setState({ selectedItem: result, showViewPanel: true });
          else
            this.setState({
              selectedItem: result,
              commands: this.getRecordCommands(result), /* showPanel: true */
              showQuickView: 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({ loadingData: false, record: result });
          this._loadingService.hide();

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

        }
      );
    }
  }

  // private _showDeleteDialog = (): void => {
  //     this.setState({ hideDialog: false });
  // };

  private _closeDeleteDialog = (): void => {
    this.setState({ hideDialog: true });
  };

  private _showArchiveDialog = (): void => {
    this.setState({ hideArchiveDialog: false });
  };

  private _closeArchiveDialog = (): void => {
    this.setState({ hideArchiveDialog: true });
  };


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

  private _onRenderButtonText = (item: any): JSX.Element => {
    return <FormattedMessage id={item.text} />;
  };

  private closeQuickView() {
    this.setState({ showQuickView: false })
  }
}
