import * as React from "react";
// import { RecordService, CachingService } from '../../../../Services';

import { Breadcrumb, DocumentCard, IColumn } from "office-ui-fabric-react/lib";
import { Record, ListRecordsCriteria } from "../../../../Models";
import { CachingService, RecordService } from "../../../../Services";
import { FormattedMessage } from "react-intl";
import GroupedListView from "../../../../Controls/GroupedListView";
import { Pagination } from "../../../../Models/Pagination";
import { LoadingService } from "../../../../Services/LoadingService";
import { FieldTypes } from "../../../../Enums";
import { FormView } from "../../../../Customizations/Controls/FormView";

// import { FieldTypes } from "../../Enums";

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

class RecordsGroupedList extends React.Component<any, any> {
  private _cachingService = new CachingService();
  private _pageSize = 10;
  private _recordService: RecordService = new RecordService();
  private _loadingService = new LoadingService();
  // private Criteria: any;
  constructor(props: {}) {
    super(props);
    this.state = {
      records: new Array<Record>(),
      totalNumberOfRecords: 0,
      totalPages: 0,
      screenIconClassName: this._cachingService.read("screenIconClassName"),
      screenTitle: this._cachingService.read("screenTitle"),
      groupRecords: [{ name: "Group 1", id: 1 }, { name: "Group2", id: 2 }],
      selectedItem: { entityId: 14 },
      Record: { entityId: 14 }

    };

    let criteria = this._cachingService.read("Params") as ListRecordsCriteria;
    if (!criteria) {
      criteria = new ListRecordsCriteria();
      criteria.asLookup = false;
      criteria.entityId = this.props.match.params.id;

    }
    criteria.pagination = new Pagination();
    criteria.pagination.start = 0;
    criteria.pagination.count = this._pageSize;
    // this.Criteria = criteria;
  }
  render() {
    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>
          <div className="ms-Grid-col ms-sm12 ms-lg6">
            <DocumentCard className="w-100p layout-card">
              <GroupedListView
                Records={this.state.groupRecords}
                onCollapse={this._onCollapse.bind(this)}
                selectedRecordChanged={this.selectedRecordChanged.bind(this)}
              />
            </DocumentCard>
          </div>
          <div className="ms-Grid-col ms-sm12 ms-lg6">
            <DocumentCard className="w-100p layout-card">
              {
                this.state.selectedItem.fields &&
                <FormView
                  Record={this.state.selectedItem} />

              }
            </DocumentCard>
          </div>
        </div>
      </div>
    );
  }

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

  loadRecords = (id: any, index: number, criteria?: ListRecordsCriteria) => {
    // this.setState({ loadingData: true });
    // let _criteria = new ListRecordsCriteria();
    let _criteria = { "entityId": 14, "fullTextSearch": "", "asLookup": false, "query": [{ "fieldId": 156, "value": "10", "queryOperator": 0 }], "pagination": { "start": 0, "count": 0 }, "sorting": { "fieldId": 0, "direction": 0 } };

    let records;
    // if (criteria) _criteria = criteria;
    // else _criteria = this.state.criteria;
    // _criteria = this.Criteria;
    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
        //   },
        //   () => {
        //     this.forceUpdate();
        //   }
        // );
        records = result.records;
        this.state.groupRecords[index].conversations = records;
        this.setState({ groupRecords: this.state.groupRecords },
          () => {
            this.forceUpdate();
          })
      },
      error => {
        alert(error);
        this._loadingService.hide();
      }
    );
    return records;
  };

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

          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 });
        },
        error => {
          alert(error);
        }
      );
    } else {
      this._recordService.getRecord(entityId, recordId).then(
        result => {
          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 });
              });
            } 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 });
        },
        error => {
          alert(error);
        }
      );
    }
  }

  _onCollapse(id: number) {
    let index = this.state.groupRecords.map((x: any) => { return x.id; }).indexOf(id)
    if (!this.state.groupRecords[index].conversations) {
      this.loadRecords(id, index);
      this.setState({ groupRecords: this.state.groupRecords });
    }
  }


  private selectedRecordChanged(entity: any) {
    if (!entity)
      return;
    //debugger;
    this.setState({ selectedItem: entity });
    this.getRecord(entity.entityId, entity.id, true);
  }


}

export default RecordsGroupedList;
