import * as React from "react";
import {
  Label,
  DetailsList,
  SelectionMode,
  IColumn,
  TextField,
  IconButton,
  Dropdown,
  PanelType,
  Panel,
  DatePicker,
  IDatePickerStrings
} from "office-ui-fabric-react";
import { MultipleFileUpload } from "../../../Controls";
import { FormattedMessage } from "react-intl";
import {
  TransferToDepartment,
  CorrespondenceTransfer
} from "../../../Models/CorrespondenceTransfer";
import { EntityService, CachingService } from "../../../Services";
import { OrganizationalUnitsForTransferTreeComboBox } from "./OrganizationalUnitsForTransferTreeComboBox";
import { PrimaryButton as NewPrimaryButton } from "../PrimaryButton";
import { LoadingService } from "../../../Services/LoadingService";
import * as classNames from "classnames";
import { DateUtils } from "../../../Utils";
import { RecordField } from "src/Models";

export class TransferCorrespondence extends React.Component<any, any> {
  private _cachingService = new CachingService();
  private _entityService: EntityService = new EntityService();
  private _loggedInUser: any;
  private _correspondeceDepartment: number;
  private datepickerStrings: IDatePickerStrings;
  private _loadingService = new LoadingService();
  private _dateUtils: DateUtils = new DateUtils();

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

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

    let departmentId: number = -1;
    let disabledDepsId: number[] = [];
    if (this.props.Record.fields) {
      this.props.Record.fields.forEach((field: any) => {
        if (field.id == 165) departmentId = field.data;
      });
    }

    if (departmentId == -1) {
      departmentId = this._loggedInUser.department;
    }
    if (departmentId > -1) disabledDepsId.push(departmentId);

    this._correspondeceDepartment = departmentId;

    this.state = {
      selectedDepartmentsTransfer: new Array<TransferToDepartment>(),
      recordsToTransfer: new Array<TransferToDepartment>(),
      selectedDepsId: [],
      disabledDepsId: disabledDepsId,
      attachedFiles: [],
      reasonLookups: [],
      additionalComments: "",
      expectedResponseDate: null,
      isSubmitted: false,
      treeComboBoxReference: {}
    };

    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: [
          "يناير",
          "فبراير",
          "مارس",
          "ابريل",
          "مايو",
          "يونيو",
          "يوليو",
          "اغسطس",
          "سبتمبر",
          "اكتوبر",
          "نوفمبر",
          "ديسمبر"
        ]
      };
    }

    this.getReasons();
  }

  _handleMultiCorrespondenceTranserToDepartmentsChange(
    ids: Array<number>,
    record: any
  ) {
    // if (this.state.selectedCorrespondencesTransfer) {
    //     let selectedCorrespondenceTransfer = this.state.selectedCorrespondenceTransfer;
    //     selectedCorrespondenceTransfer.toDepartmentId = ids[0];
    //     selectedCorrespondenceTransfer.toDepartmentName = record[0].name;
    //     this.setState({ selectedCorrespondenceTransfer: selectedCorrespondenceTransfer });
    // }
    record.forEach((x: any) => {
      let isExist = this.state.selectedDepartmentsTransfer.findIndex(
        (y: any) => y.id == x.id
      );
      if (isExist <= -1) this.state.selectedDepartmentsTransfer.push(x);
    });
    this.setState({ selectedDepsId: ids });
    this.forceUpdate();
  }

  private _renderTreeComboBoxFooter() {
    return <div className="ms-Grid-col ms-sm12" style={{ position: "sticky", "bottom": "0px", "padding": "10px", textAlign: "left", background: "white" }}>
      <NewPrimaryButton
        onClick={this._handleMultiTransferSubmit.bind(this)}
      >
        <FormattedMessage id="Add" />
      </NewPrimaryButton>
    </div>
  }

  _handleMultiTransferSubmit(button: any) {
    if (button && button.block) button.block();
    let recordsToTransfer = this.state.recordsToTransfer;

    if (this.state.selectedDepartmentsTransfer) {
      this.state.selectedDepartmentsTransfer.forEach((x: any) => {
        let isExist = recordsToTransfer.findIndex(
          (y: any) => y.toDepartmentId == x.id
        );
        if (isExist <= -1) {
          let newTransfer = new TransferToDepartment();
          newTransfer.toDepartmentId = x.id;
          newTransfer.toDepartmentName = x.name;
          recordsToTransfer.push(newTransfer);
        }
      });

      if (this.state.treeComboBoxReference && this.state.treeComboBoxReference.reference) {
        this.state.treeComboBoxReference.reference.dismissMenu();
      }
      if (button && button.unblock) button.unblock();
    }

    this.setState({ recordsToTransfer: recordsToTransfer });

    let disabledDepsId: number[] = this.state.selectedDepsId.slice(0);
    disabledDepsId.push(this._correspondeceDepartment);
    this.setState({ disabledDepsId: disabledDepsId });

    //this.forceUpdate();
  }

  getReasons() {
    this._loadingService.show();
    this._entityService.getReasonLookups("transfer").then(
      (result: any) => {
        this._loadingService.hide();

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

  private _renderItemColumn(
    item: TransferToDepartment,
    index: number,
    column: IColumn
  ) {
    const fieldContent = item[
      column.fieldName as keyof TransferToDepartment
    ] as string;

    switch (column.key) {
      case "ToDepartmentName":
        return <span key={"actions1" + index}>{fieldContent}</span>;

      case "comment":
        return (
          <div key={"actions2" + index} style={{ minWidth: 100 }}>
            <TextField
              className="ms-Grid-col ms-lg12"
              multiline
              rows={1}
              resizable={false}
              onChanged={this._handleMultiTranserToDepartmentsCommentsChange.bind(
                this,
                item,
                index
              )}
            />
          </div>
        );

      case "reason":
        return (
          <div key={"actions3" + index}>
            {/* {this.state.recordsToTransfer[index].reason > 0} */}
            {this.state.isSubmitted &&
              this.state.recordsToTransfer[index].reason == 0}
            <Dropdown
              className={classNames("ms-Grid-col ms-lg12", {
                "red-border":
                  this.state.isSubmitted &&
                  this.state.recordsToTransfer[index].reason == 0
              })}
              options={this.state.reasonLookups.map((lookup: any) => {
                return { key: lookup.id, text: lookup.value };
              })}
              errorMessage={
                this.state.isSubmitted &&
                  this.state.recordsToTransfer[index].reason == 0
                  ? " "
                  : ""
              }
              // value={this.state.selectedCorrespondenceTransfer.reason}

              onChanged={this._handleMultiTranserToReasonsChange.bind(
                this,
                item,
                index
              )}
            />
          </div>
        );
      case "actions":
        return (
          <div key={"actions4" + index} style={{ width: 20 }}>
            <IconButton
              iconProps={{ iconName: "Delete", style: { color: "red" } }}
              onClick={this._handleMultiTransformDelete.bind(this, item, index)}
            />
          </div>
        );

      default:
        return <span key={"actions5" + index}>{fieldContent}</span>;
    }
  }

  _handleMultiTranserToDepartmentsCommentsChange(
    record: any,
    index: number,
    value: any
  ) {
    //debugger;
    this.state.recordsToTransfer[index].comment = value;
    this.setState({ recordsToTransfer: this.state.recordsToTransfer });
  }

  _handleMultiTranserToReasonsChange(record: any, index: number, value: any) {
    this.state.recordsToTransfer[index].reason = value.key;
    this.setState({ recordsToTransfer: this.state.recordsToTransfer });
  }

  _handleMultiTransformDelete(record: any, index: number) {
    //debugger;
    this.state.selectedDepsId.splice(index, 1);
    this.state.recordsToTransfer.splice(index, 1);
    this.state.selectedDepartmentsTransfer.splice(index, 1);

    this.setState({ RemoveDepartmentsMultiSelect: true });
    let _this = this;
    setTimeout(function () {
      let disabledDepsId: number[] = _this.state.selectedDepsId.slice(0);
      disabledDepsId.push(_this._correspondeceDepartment);

      _this.setState({
        RemoveDepartmentsMultiSelect: false,
        recordsToTransfer: _this.state.recordsToTransfer,
        selectedDepsId: _this.state.selectedDepsId,
        selectedDepartmentsTransfer: _this.state.selectedDepartmentsTransfer,
        disabledDepsId: disabledDepsId
      });
    }, 100);
  }

  _handleFilesChange(ids: Array<number>) {
    this.setState({ attachedFiles: ids });
  }

  _handleAditionalCommentsChange(value: any) {
    this.setState({ additionalComments: value });
  }

  _handleExpecedResponseDateChange(value: any) {
    this.setState({ expectedResponseDate: value });
  }

  private transferMultiCorrespondence(button: any) {
    this.setState({ isSubmitted: true });
    let isValid = true;
    if (
      this.state.recordsToTransfer &&
      this.state.recordsToTransfer.length > 0
    ) {
      this.state.recordsToTransfer.forEach((el: any) => {
        //debugger;
        if (el.reason == 0) {
          isValid = false;
        }
      });
      if (isValid) {
        var obj = new CorrespondenceTransfer();
        obj.correspondenceId = this.props.Record.id;
        obj.transferToDepartments = this.state.recordsToTransfer;
        obj.additionalComments = this.state.additionalComments;
        obj.expectedResponseDate = this.state.expectedResponseDate;
        obj.transferToDepartments.forEach((dep: any) => {
          dep.attachments = this.state.attachedFiles;
        });

        if (this.props.onTransferSubmit)
          this.props.onTransferSubmit(obj, button);
      }
    }
  }

  public render(): JSX.Element {

  
    var recordExpectedResponseDate: any = null;
    if (this.props.Record && this.props.Record.fields) {
      this.props.Record.fields.forEach((field: RecordField) => {
        if (field.id == 159){
          recordExpectedResponseDate = new Date(field.data);
        }
      });
    }

    return (
      <Panel
        className="panelStyle"
        isOpen={this.props.open}
        onDismissed={this.props.closeMultiTransferPanel.bind(this)}
        type={PanelType.medium}
        isFooterAtBottom={true}
        headerText="TransferCorrespondence"
        isLightDismiss={true}
        hasCloseButton={false}
        onRenderHeader={this._onReadnderHader.bind(this)}
        onRenderFooter={this._renderFooter.bind(this)}
      >
        <div>
          <div className="ms-Grid-row">
            <div className="ms-Grid-col ms-lg12">
              {/* {this.state.actionRecords &&  */}
              {/* <Label>To Departments List</Label> */}
              {}
              {/* <RecordsListView
                    TotalPages={this.state.totalPages}
                    Records={this.state.actionRecords}
                    LoadRecordsWithNewCriteria={this.loadRecordsWithNewCriteria.bind(
                        this
                    )}
                    Actions={[{ iconName: "Delete", actionType: 0 }]}
                    deleteItem={this.handleDelete.bind(this)}
                /> 
                */}
              {/* } */}
            </div>
          </div>
          <div className="ms-Grid-row">
            <div className="ms-Grid-col ms-sm12">
              <Label className="ms-fontSize-l">
                <FormattedMessage id="SelectDepartments" />
              </Label>
            </div>
            <div className="ms-Grid-col ms-sm12">
              {!this.state.RemoveDepartmentsMultiSelect && (
                <OrganizationalUnitsForTransferTreeComboBox
                  multiple
                  comboboxref={this.state.treeComboBoxReference}
                  correspondence={this.props.Record}
                  value={this.state.selectedDepsId}
                  disabledItems={this.state.disabledDepsId}
                  onRenderLowerContent={this._renderTreeComboBoxFooter.bind(this)}
                  onChanged={this._handleMultiCorrespondenceTranserToDepartmentsChange.bind(
                    this
                  )}
                // value={this.state.selectedCorrespondenceTransfer.toDepartmentId}
                />
              )}
            </div>


            {this.state.recordsToTransfer &&
              this.state.recordsToTransfer.length > 0 && (
                <div className="ms-Grid-col ms-sm12" style={{ marginTop: 20 }}>
                  <DetailsList
                    //className="w-100p"
                    items={this.state.recordsToTransfer}
                    onRenderItemColumn={this._renderItemColumn.bind(this)}
                    //setKey="set"
                    selectionMode={SelectionMode.none}
                    //isHeaderVisible={false}
                    columns={[
                      {
                        key: "ToDepartmentName",
                        name:
                          this._cachingService.readPersistant("Language") == 1
                            ? "القسم"
                            : "Department",
                        fieldName: "toDepartmentName",
                        minWidth: 0,
                        maxWidth: 0
                      },
                      {
                        key: "comment",
                        name:
                          this._cachingService.readPersistant("Language") == 1
                            ? "التعليق"
                            : "Comment",
                        fieldName: "comment",
                        minWidth: 250,
                        maxWidth: 0
                      },
                      {
                        key: "reason",
                        name:
                          this._cachingService.readPersistant("Language") == 1
                            ? "السبب"
                            : "Reason",
                        fieldName: "reason",
                        minWidth: 0,
                        maxWidth: 0
                      },
                      {
                        key: "actions",
                        name: "",
                        fieldName: "actions",
                        minWidth: 20,
                        maxWidth: 20
                      }
                    ]}
                  />
                </div>
              )}
            {!this.props.fromCreate && (
              <div>
                <div className="ms-Grid-col ms-sm12" style={{ marginTop: 20 }}>
                  <Label className="ms-fontSize-l">
                    <FormattedMessage id="AttachDocuments" />
                  </Label>
                </div>
                <div className="ms-Grid-col ms-sm12">
                  <MultipleFileUpload
                    Record={this.props.Record}
                    initialFiles={this.state.attachedFiles}
                    onChanged={this._handleFilesChange.bind(this)}
                  />
                </div>
                <div className="ms-Grid-col ms-sm12" style={{ marginTop: 20 }}>
                  <Label className="ms-fontSize-l">
                    <FormattedMessage id="AdditionalComments" />
                  </Label>
                </div>
                <div className="ms-Grid-col ms-sm12">
                  <TextField
                    className=" ms-lg12"
                    required={false}
                    multiline
                    rows={4}
                    onChanged={this._handleAditionalCommentsChange.bind(this)}
                  />
                </div>
              </div>
            )}

            <div className="ms-Grid-col ms-sm12" style={{ marginTop: 20 }}>
              <Label className="ms-fontSize-l">
                <FormattedMessage id="ExpectedResponseDate" />
              </Label>
            </div>
            <div className="ms-Grid-col ms-sm12">
              <DatePicker
                className=" ms-lg12"
                placeholder=""
                minDate={new Date()}
                maxDate={recordExpectedResponseDate}
                value={this.convertDate(this.state.expectedResponseDate)}
                strings={this.datepickerStrings}
                allowTextInput={true}
                isRequired={false}
                onSelectDate={this._handleExpecedResponseDateChange.bind(this)}
                formatDate={this._onFormatDate.bind(this)}
              />
            </div>
            {/* <d
            iv className="ms-Grid-col ms-lg12" style={{ marginTop: 15 }}>
                <label className='ms-font-xl	ms-fontWeight-semibold	'>Handler Parameters</label>
            </div>
            {
                this.state.selectedWorkflowHandler && this.state.selectedWorkflowHandler.handlerParams &&
                this.state.selectedWorkflowHandler.handlerParams.map((element: any) => {
                    return (<div className="ms-Grid-col ms-lg12">
                        <TextField label={element.name} required={element.required} />
                    </div>)
                })} */}
          </div>
        </div>
      </Panel>
    );
  }

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

  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 _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 _renderFooter = (): JSX.Element => {
    return (
      <div className="sticky-footer-btns">
        <NewPrimaryButton
          disabled={this.state.recordsToTransfer.length == 0}
          onClick={this.transferMultiCorrespondence.bind(this)}
          style={{ margin: "5px" }}
        >
          <FormattedMessage id="Transfer" />
        </NewPrimaryButton>
      </div>
    );
  };
}
