import * as React from "react";
import { FormView as CoreFormView } from "../../Controls/FormView";
import { Panel, PanelType, DefaultButton, IconButton, Dialog, DialogType, DialogFooter, Label } from "office-ui-fabric-react";
import { FormattedMessage } from "react-intl";
import { TransferToDepartment, CorrespondenceTransfer } from "../../../Models/CorrespondenceTransfer";
import { CorrespondenceReply } from "../../../Models/CorrespondenceReply";
import { RecordService, CachingService, ImportExportService, UserService } from "../../../Services";
// import { FormDisplay } from "./FormDisplay";
import { TransferCorrespondence } from "./TransferCorrespondence";
import { PrimaryButton as NewPrimaryButton } from "../PrimaryButton";
import { ApproveCorrespondence } from "./ApproveCorrespondence";
import { RejectCorrespondence } from "./RejectCorrespondence";
import { CloseCorrespondence } from "./CloseCorrespondence";
import { ReOpenCorrespondence } from "./ReOpenCorrespondence";
import { FieldsControl } from "../FieldsControl";
import { RecordSignature } from "../../../Models/RecordSignature";
import { LoadingService } from "../../../Services/LoadingService";
import { DateUtils } from "../../../Utils";
import { MoveDraftCorrespondence } from "./MoveDraftCorrespondence";
import { UpdateLetterDetails } from "./UpdateLetterDetails";
import { DynamicRecordService } from "../../../Services/DynamicRecordService";
import { ListRecordsCriteria, FieldQuery, Pagination, RecordField, Field } from "../../../Models";
import CountDown from "../../../Controls/CountDown";

import bwipjs from 'bwip-js';
import { CorrespondenceActions } from "../../../Customizations/Services/CorrespondenceActions";

export class FormView extends React.Component<any, any> {

    private _recordService: RecordService = new RecordService();
    private _userService: UserService = new UserService();
    private _dynamicRecordService: DynamicRecordService = new DynamicRecordService();
    private _loggedInUserId: number;
    private _cachingService = new CachingService();
    private _loadingService = new LoadingService();
    private _dateUtils: DateUtils = new DateUtils();
    private _ImportExportService: ImportExportService = new ImportExportService();
    private correspondenceActions: CorrespondenceActions;

    // private fieldsControl: FieldsControl;
    constructor(props: any) {
        super(props);
        let status = 0;
        let cachingService: CachingService = new CachingService();
        this._loggedInUserId = cachingService.read('UserId');

        if (this.props.Record.fields) {
            this.props.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;
            });

        }

        this.state = {
            hideArchiveDialog: true,
            hideExportExternalDialog: true,
            hideSignDialog: true,
            hideUnSignDialog: true,
            hideDownloadingPDFDialog: true,
            selectedCorrespondenceTransfer: new TransferToDepartment(),
            status: status,
            actionRecords: new Array<TransferToDepartment>(),
            replyObj: new CorrespondenceReply(),
            approvePanel: false,
            RejectPanel: false,
            CloseCorrespondencePanel: false,
            ReOpenCorrespondencePanel: false,
            UpdateLetterDetailsPanel: false,
            buttons: [],
            MultiTransferPanel: false,
            MoveDraftCorrespondencePanel: false,
            emptyCorrespondence: { entityId: 14 },
            correspondenceActions: []
        };

        //this._getButtons(status);
        this.getRecordApprovalEntries();
        this.getRecordComments();
        this.correspondenceActions = new CorrespondenceActions(this.props.Record, status, () => {
            this.setState({ buttons: this._getButtons(this.state.status) });
        });
    }

    componentDidUpdate(prevProps: any, prevState: any) {

        if (prevProps.Record !== this.props.Record) {
            let status = 0;
            if (this.props.Record.fields) {

                this.props.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;
                });

            }

            this.setState({ status: status });
            //this._getButtons(status);
            this.getRecordApprovalEntries();
            this.getRecordComments();

            this.correspondenceActions.RecordStatus = status;
            this.setState({ buttons: this._getButtons(this.state.status) });
        }
    }

    private _setColWidth(id: any): string {
        switch (id) {
            case 155: {
                return " ms-Grid-col ms-sm12 ms-lg6";
            }
            case 156: {
                return " ms-Grid-col ms-sm12 ms-lg6";
            }
            case 157: {
                return "ms-Grid-col ms-sm12 ms-lg6";
            }
            case 159: {
                return "ms-Grid-col ms-sm12 ms-lg6";
            }
            case 163: {
                return "ms-Grid-col ms-sm12 ms-lg6";
            }
            case 164: {
                return "ms-Grid-col ms-sm12 ms-lg6";
            }
            case 165: {
                return "ms-Grid-col ms-sm12 ms-lg6";
            }
            case 175: {
                return "ms-Grid-col ms-sm12 ms-lg6";
            }
            case 176: {
                return "ms-Grid-col ms-sm12 ms-lg6";
            }
            case 189: {
                return "ms-Grid-col ms-sm12 ms-lg6";
            }
            case 190: {
                return "ms-Grid-col ms-sm12 ms-lg6";
            }
            case 191: {
                return "ms-Grid-col ms-sm12 ms-lg6";
            }
            case 227: {
                return "ms-Grid-col ms-sm12 ms-lg6";
            }
            case 228: {
                return "ms-Grid-col ms-sm12 ms-lg6";
            }
            case 303: {
                return "ms-Grid-col ms-sm12 ms-lg6";
            }
            case 304: {
                return "ms-Grid-col ms-sm12 ms-lg6";
            }


            default: {
                return "ms-Grid-col ms-sm12 ms-lg12";
            }
        }
    }

    componentDidMount() {
        this.renderBarCode();
    }

    renderBarCode() {

        //debugger;
        let value = this.props.Record.fields.filter((field: Field) => {
            return field.id == 170;
        })
        if (value) {
            Array.from(document.getElementsByClassName('RecordBarCode')).forEach((canvas) => {
                bwipjs(canvas, {
                    bcid: 'code128',       // Barcode type
                    text: this.props.Record.id.toString(),    // Text to encode
                    scale: 2,               // 3x scaling factor
                    height: 8,              // Bar height, in millimeters
                    includetext: false,            // Show human-readable text
                    // textxalign:  'center',       // Always good to set this
                }, function (err: any, cvs: any) {
                    if (err) {
                        // Decide how to handle the error
                        // `err` may be a string or Error object
                    } else {
                        // Nothing else to do in this example...
                    }
                });
            });


        }
    }

    getRecordComments() {
        if (this.props.Record.id) {
            let criteria: ListRecordsCriteria = new ListRecordsCriteria();
            criteria.asLookup = false;
            criteria.entityId = 23;
            criteria.query = new Array<FieldQuery>();
            let query = new FieldQuery();
            query.fieldId = 247;
            query.value = this.props.Record.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);


                    if (result)
                        result.forEach((comment: any) => {
                            comment.CreatedByObj = {};
                            this._getCreatedBy(comment);
                        });

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

    private _getCreatedBy(obj: any) {
        if (obj && obj.CreatedBy) {
            this._userService.getUser(obj.CreatedBy)
                .then(result => {
                    obj.CreatedByObj = result.data;
                    this.forceUpdate();
                }, error => {

                    alert(error);
                });
        }
    }

    getRecordApprovalEntries() {
        if (this.props.Record.id) {
            this._recordService.getCorrespondenceApprovalEntries(this.props.Record.id).then(
                (result: any) => {
                    this._loadingService.hide();
                    console.log(result);

                    if (result) {
                        result.forEach((entry: any) => {
                            entry.CreatedByObj = {};
                            this._getCreatedBy(entry);
                        });
                        // this.state.reasonLookups = result;
                        this.setState({ approvalEntries: result });
                        this.correspondenceActions.ApprovalEntries = result;
                        this.setState({ buttons: this._getButtons(this.state.status) })
                    }
                },
                error => {
                    // alert(error.text());
                    // this.toastr.error('', error.text());
                    //this.displayAlertModal(error.text());
                    alert(error);
                    this._loadingService.hide();
                }
            );
        }
    }

    private _getButtons(status: number) {
        return <div className="sticky-footer-btns">
            {status == 22 &&
                <NewPrimaryButton
                    onClick={this.showMoveDraftCorrespondencePanel.bind(this)}
                    className="panel-footer-btn">
                    <FormattedMessage id="SendAsDraft" />
                </NewPrimaryButton>
            }

            {this.correspondenceActions.isActionAuthorized('Forward') &&
                <NewPrimaryButton
                    onClick={this.showTransferPanel.bind(this)}
                    className="panel-footer-btn">
                    <FormattedMessage id="Forward" />
                </NewPrimaryButton>
            }

            {this.correspondenceActions.isActionAuthorized('ReplyNew') &&
                <NewPrimaryButton
                    onClick={this.replyNewCorrespondence.bind(this)}
                    className="panel-footer-btn">
                    <FormattedMessage id="Reply New" />
                </NewPrimaryButton>
            }

            {this.correspondenceActions.isActionAuthorized('Approve') &&
                <NewPrimaryButton
                    onClick={this.showApprovePanel.bind(this)}
                    className="panel-footer-btn">
                    <FormattedMessage id="Approve" />
                </NewPrimaryButton>
            }

            {this.correspondenceActions.isActionAuthorized('Reject') &&

                <NewPrimaryButton
                    onClick={this.showRejectPanel.bind(this)}
                    className="panel-footer-btn">
                    <FormattedMessage id="Reject" />
                </NewPrimaryButton>
            }

            {this.correspondenceActions.isActionAuthorized('Close') &&
                <NewPrimaryButton
                    onClick={this.showCloseCorrespondencePanel.bind(this)}
                    className="panel-footer-btn">
                    <FormattedMessage id="Close" />
                </NewPrimaryButton>
            }

            {this.showReOpenButton(status)}

            {this.showArchiveButton(status)}
            {this.showSignButton(status)}
            {this.showUnSignButton(status)}
            {this.showExportExternalButton(status)}
            {this.showUpdateLetterDetailsButton(status)}

            <NewPrimaryButton
                onClick={this._downloadPdf.bind(this)}
                className="panel-footer-btn">
                <FormattedMessage id="DownloadPdf" />
            </NewPrimaryButton>
        </div>
    }

    private _downloadPdf(item: any) {

        var subject = "";
        this.props.Record.fields.forEach((field: any) => {
            if (field.id == 153) {
                subject = field.data;
            }
        })

        this._ImportExportService.downloadFile(this.props.Record.id, 14, subject);

        this.showDownloadingPDFDialog();
    }

    private showDownloadingPDFDialog() {
        this.setState({ hideDownloadingPDFDialog: false });
    }

    private _closeDownloadingPDFDialog() {
        this.setState({ hideDownloadingPDFDialog: true });
    }

    private showReOpenButton(status: number) {
        //debugger;

        return (this.correspondenceActions.isActionAuthorized("ReOpen") && <NewPrimaryButton
            onClick={this.showReOpenCorrespondencePanel.bind(this)}
            className="panel-footer-btn">
            <FormattedMessage id="ReOpen" />
        </NewPrimaryButton>);

    }

    private showExportExternalButton(status: number) {
        return (this.correspondenceActions.isActionAuthorized('ExportExternal') && <NewPrimaryButton
            onClick={this._showExportExternalDialog.bind(this)}
            className="panel-footer-btn">
            <FormattedMessage id="Export External" />
        </NewPrimaryButton>);


    }

    private showUpdateLetterDetailsButton(status: number) {
        return (this.correspondenceActions.isActionAuthorized('UpdateLetterDetails') && <NewPrimaryButton
            onClick={this.showUpdateLetterDetailsPanel.bind(this)}
            className="panel-footer-btn">
            <FormattedMessage id="Edit Letter Details" />
        </NewPrimaryButton>);

    }

    private showArchiveButton(status: number) {
        return (this.correspondenceActions.isActionAuthorized('Archive') && <NewPrimaryButton
            onClick={this._showArchiveDialog.bind(this)}
            className="panel-footer-btn">
            <FormattedMessage id="Archive" />
        </NewPrimaryButton>);

    }

    private showSignButton(status: number) {
        //debugger;
        if (this.correspondenceActions.isActionAuthorized('Sign')) {
            if (this.props.Record.signatures) {
                var userSignatureExists = false;

                this.props.Record.signatures.forEach((sign: RecordSignature) => {
                    if (sign.signatureCreatedById == this._loggedInUserId)
                        userSignatureExists = true;
                });

                if (userSignatureExists == false)
                    return <NewPrimaryButton
                        onClick={this._showSignDialog.bind(this)}
                        className="panel-footer-btn">
                        <FormattedMessage id="Sign" />
                    </NewPrimaryButton>;
            }
        }
        return "";
    }

    private showUnSignButton(status: number) {
        //debugger;

        if (status == 106) {
            if (this.props.Record.signatures && this.props.Record.length > 0) {
                var userSignatureExists;

                this.props.Record.signatures.forEach((sign: RecordSignature) => {
                    if (sign.signatureCreatedById == this._loggedInUserId)
                        userSignatureExists = true;
                });

                if (userSignatureExists == true)
                    return <NewPrimaryButton
                        onClick={this._showUnSignDialog.bind(this)}
                        className="panel-footer-btn">
                        <FormattedMessage id="UnSign" />
                    </NewPrimaryButton>;
            }
        }

        return "";
    }

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

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


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


            });

    }

    private renderPanelBody = (): JSX.Element => {
        this.state.emptyCorrespondence.fields.forEach((field: RecordField) => {
            if (field.id == 165) {
                field.hidden = false;
                field.data = null;
            }
        });
        return (
            <div>
                <FieldsControl
                    Record={this.state.emptyCorrespondence}
                    fields={this.state.emptyCorrespondence.fields}
                    // onSubmit={this.handleSubmit.bind(this)}
                    actions={this.state.emptyCorrespondence.actions}
                    // onRef={(ref: any) => (this.fieldsControl = ref)} 
                    panelMode={true} />
            </div>)
    }
    private closePanel() {
        this.setState({ showPanel: false });
    };
    private renderPanelFooterContent = (): 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.closePanel() }}>
                    <FormattedMessage id="Cancel" />
                </DefaultButton>
            </div>
        );
    };

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

        // this.fieldsControl._setFormsubmitted;
        debugger;

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

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

    };

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

        this._closeArchiveDialog();

        if (this.props.Record.id) {
            this.setState({ loadingData: true });
            this._recordService
                .archiveRecord(
                    14,
                    this.props.Record.id
                )
                .then(
                    result => {
                        //this.loadRecords();
                        if (button && button.block) button.unblock();
                        if (this.props.loadRecord)
                            this.props.loadRecord();
                    },
                    error => {
                        alert(error);
                        if (button && button.block) button.unblock();
                    }
                );
        }
    }

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

        this._closeSignDialog();

        if (this.props.Record.id) {
            this.setState({ loadingData: true });
            this._recordService
                .signRecord(
                    14,
                    this.props.Record.id
                )
                .then(
                    result => {
                        if (button && button.block) button.unblock();
                        if (this.props.loadRecord)
                            this.props.loadRecord();

                    },
                    error => {
                        alert(error);
                        if (button && button.block) button.unblock();
                    }
                );
        }
    }

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

        this._closeUnSignDialog();

        if (this.props.Record.id) {
            this.setState({ loadingData: true });
            this._recordService
                .unSignRecord(
                    14,
                    this.props.Record.id
                )
                .then(
                    result => {
                        if (button && button.block) button.unblock();
                        if (this.props.loadRecord)
                            this.props.loadRecord();


                    },
                    error => {
                        alert(error);
                        if (button && button.block) button.unblock();
                    }
                );
        }
    }

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

        this._closeExportExternalDialog();

        if (this.props.Record.id) {
            this.setState({ loadingData: true });
            this._recordService
                .exportExternal(
                    14,
                    this.props.Record.id
                )
                .then(
                    result => {
                        if (button && button.block) button.unblock();
                        if (this.props.loadRecord)
                            this.props.loadRecord();
                    },
                    error => {
                        alert(error);
                        if (button && button.block) button.unblock();
                    }
                );
        }
    }

    public render(): JSX.Element {
        var barCodeText = "";
        var remaningDays = null;
        var recordStatus = 0;

        if (this.props.Record.fields) {
            //debugger;
            this.props.Record.fields.forEach((field: any) => {

                if (field.id == 156 || field.id == 165 || field.id == 170 || field.id == 174 || field.id == 175 ||
                    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.id == 204 || field.id == 234 ||
                    field.id == 235 || field.id == 237 || field.id == 251 || field.id == 252 ||
                    field.id == 254 || field.type == 14)
                    field.hidden = true;
                else
                    field.hidden = false;

                if (field.id == 170) {
                    field.showAsBarCodeText = true;
                    barCodeText = field.data;
                }

                if (field.id == 159) {
                    remaningDays = field.data;
                }

                if (field.id == 176) {
                    recordStatus = field.data;
                }
            });

        }

        return (
            <div>

                {/* {this.state.buttons} */}
                <i className="iconsmind-Mail-Read" style={{ float: 'right', fontSize: 40, padding: '5px 20px 0 0', opacity: .4 }}></i>
                {recordStatus != 22 &&
                    <div className="row-c">
                        <div className="col-c-lg-6">
                            <Label > <FormattedMessage id="PendingDays" /> </Label>
                            <CountDown remaningDays={remaningDays} />
                        </div>
                        <div className="col-c-lg-6 barcode-container">
                            <div className="record-barcode-container">
                                <div className="barcode-internal-container">
                                    <canvas className="RecordBarCode"></canvas>
                                </div>
                                <div className="barCodeText">{barCodeText}</div>
                            </div>
                        </div>
                    </div>
                }
                <CoreFormView
                    {...this.props} setColWidth={this._setColWidth.bind(this)}>
                </CoreFormView>

                {this.state.comments && this.state.comments.length > 0 &&
                    <div className="ms-Grid-col ms-sm6 ms-md6 ms-lg12">
                        {/* <TextField className="ms-Grid-col ms-lg12" label={item.displayName} value={item.data ? item.data : ""} onChanged={this._handleDataChange.bind(this, item)} /> */}
                        <Label><FormattedMessage id="Comments" /></Label>
                        <div className="form-field-view">
                            {this.state.comments.map((comment: any) => {
                                return (<div>
                                    <p>{this._dateUtils.formatDate(comment.CreatedDate)} - {comment.CreatedByObj.name}:
                                    <br />
                                        {comment.Comments}</p>
                                </div>);
                            })}
                        </div>

                    </div>
                }

                {this.state.approvalEntries && this.state.approvalEntries.length > 0 &&
                    <div className="ms-Grid-col ms-sm6 ms-md6 ms-lg12">
                        {/* <TextField className="ms-Grid-col ms-lg12" label={item.displayName} value={item.data ? item.data : ""} onChanged={this._handleDataChange.bind(this, item)} /> */}
                        <Label><FormattedMessage id="Approval Entries" /></Label>
                        <div className="form-field-view">
                            {this.state.approvalEntries.map((approvalEntry: any) => {
                                return (<div>
                                    <p>{approvalEntry.CreatedByObj.name} {approvalEntry.IsRejected == false ? <FormattedMessage id='approved on'></FormattedMessage> : <FormattedMessage id='rejected on'></FormattedMessage>} {this._dateUtils.formatDate(approvalEntry.CreatedDate)}</p>
                                </div>);
                            })}
                        </div>

                    </div>
                }

                {this.state.buttons}

                <TransferCorrespondence open={this.state.MultiTransferPanel} closeMultiTransferPanel={this.closeMultiTransferPanel.bind(this)}
                    onTransferSubmit={this.transferMultiCorrespondence.bind(this)}
                    Record={this.props.Record}></TransferCorrespondence>

                <MoveDraftCorrespondence open={this.state.MoveDraftCorrespondencePanel} closeMoveDraftCorrespondencePanel={this.closeMoveDraftCorrespondencePanel.bind(this)}
                    onTransferSubmit={this.moveDraftCorrespondence.bind(this)}
                    Record={this.props.Record}></MoveDraftCorrespondence>

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

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

                <CloseCorrespondence open={this.state.CloseCorrespondencePanel} closeCloseCorrespondencePanel={this.closeCloseCorrespondencePanel.bind(this)}
                    OnPostSubmit={this.OnPostCloseCorrespondence.bind(this)} Record={this.props.Record}></CloseCorrespondence>

                <ReOpenCorrespondence open={this.state.ReOpenCorrespondencePanel} closeReOpenCorrespondencePanel={this.closeReOpenCorrespondencePanel.bind(this)}
                    OnPostSubmit={this.OnPostReOpenCorrespondence.bind(this)} Record={this.props.Record}></ReOpenCorrespondence>

                <UpdateLetterDetails open={this.state.UpdateLetterDetailsPanel} closeUpdateLetterDetailsPanel={this.closeUpdateLetterDetailsPanel.bind(this)}
                    OnPostSubmit={this.OnPostUpdateLetterDetails.bind(this)} Record={this.props.Record}></UpdateLetterDetails>

                <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)}
                    headerText="Reply New"
                    isFooterAtBottom={true}
                    //styles={{ IsFooterSticky: true }}
                    headerClassName="panelHeaderStyle"
                    hasCloseButton={false}
                    isBlocking={true}
                    onRenderHeader={this._onReadnderHader}
                >

                </Panel>

                <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>
                <Dialog
                    hidden={this.state.hideSignDialog}
                    onDismiss={this._closeSignDialog}
                    dialogContentProps={{
                        type: DialogType.normal,
                        title:
                            this._cachingService.readPersistant("Language") == 0
                                ? "Sign"
                                : "توقيع",
                        subText:
                            this._cachingService.readPersistant("Language") == 0
                                ? "Are you sure you want to sign 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.signRecord.bind(this)}
                            text="Sign"
                            onRenderText={this._onRenderButtonText}
                        />
                        <DefaultButton
                            onClick={this._closeSignDialog}
                            text="Cancel"
                            onRenderText={this._onRenderButtonText}
                        />
                    </DialogFooter>
                </Dialog>

                <Dialog
                    hidden={this.state.hideUnSignDialog}
                    onDismiss={this._closeUnSignDialog}
                    dialogContentProps={{
                        type: DialogType.normal,
                        title:
                            this._cachingService.readPersistant("Language") == 0
                                ? "Cancel Sign"
                                : "الغاء التوقيع",
                        subText:
                            this._cachingService.readPersistant("Language") == 0
                                ? "Are you sure you want to cancel sign from 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.unSignRecord.bind(this)}
                            text="UnSign"
                            onRenderText={this._onRenderButtonText}
                        />
                        <DefaultButton
                            onClick={this._closeUnSignDialog}
                            text="Cancel"
                            onRenderText={this._onRenderButtonText}
                        />
                    </DialogFooter>
                </Dialog>

                <Dialog
                    hidden={this.state.hideDownloadingPDFDialog}
                    onDismiss={this._closeDownloadingPDFDialog.bind(this)}
                    dialogContentProps={{
                        type: DialogType.normal,
                        title:
                            this._cachingService.readPersistant("Language") == 0
                                ? "Download PDF"
                                : "تحميل ك PDF",
                        subText:
                            this._cachingService.readPersistant("Language") == 0
                                ? "PDF is getting downloaded. Please wait for a few seconds."
                                : "الرجاء الانتظار. يتم تحميل المستند بصيغة PDF"
                    }}
                    modalProps={{
                        titleAriaId: "myLabelId",
                        subtitleAriaId: "mySubTextId",
                        isBlocking: false,
                        containerClassName: "ms-dialogMainOverride"
                    }}
                >
                    {
                        null /** You can also include null values as the result of conditionals */
                    }
                    <DialogFooter>
                        <DefaultButton
                            onClick={this._closeDownloadingPDFDialog.bind(this)}
                            text="Close"
                            onRenderText={this._onRenderButtonText}
                        />
                    </DialogFooter>
                </Dialog>

                <Dialog
                    hidden={this.state.hideExportExternalDialog}
                    onDismiss={this._closeExportExternalDialog}
                    dialogContentProps={{
                        type: DialogType.normal,
                        title:
                            this._cachingService.readPersistant("Language") == 0
                                ? "Export External"
                                : "تصدير رسالة خارجية",
                        subText:
                            this._cachingService.readPersistant("Language") == 0
                                ? "Are you sure you want to export correspondence externally?"
                                : "هل انت متأكد من انك تريد تصدير الرسالة خارجياً؟ سوف يتم ارشفة تجميد الرسالة بعد تصديرها"
                    }}
                    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.exportExternalRecord.bind(this)}
                            text="Export External"
                            onRenderText={this._onRenderButtonText}
                        />
                        <DefaultButton
                            onClick={this._closeExportExternalDialog}
                            text="Cancel"
                            onRenderText={this._onRenderButtonText}
                        />
                    </DialogFooter>
                </Dialog>
            </div>
        );
    }

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

    private showMoveDraftCorrespondencePanel(button: any) {
        this.setState({ MoveDraftCorrespondencePanel: true });
    }

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

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

    closeApprovePanel() {
        this.setState({ approvePanel: false })

    }

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

    closeRejectPanel() {
        this.setState({ RejectPanel: false })

    }

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

    closeCloseCorrespondencePanel() {
        this.setState({ CloseCorrespondencePanel: false })

    }

    OnPostCloseCorrespondence() {
        if (this.props.loadRecord)
            this.props.loadRecord();

        this.setState({ CloseCorrespondencePanel: false });
    }

    OnPostApproveCorrespondence() {
        if (this.props.loadRecord)
            this.props.loadRecord();

        this.setState({ approvePanel: false });
    }

    OnPostRejectCorrespondence() {
        if (this.props.loadRecord)
            this.props.loadRecord();

        this.setState({ RejectPanel: false });
    }

    OnPostReOpenCorrespondence() {
        if (this.props.loadRecord)
            this.props.loadRecord();

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

    OnPostUpdateLetterDetails() {
        if (this.props.loadRecord)
            this.props.loadRecord();

        this.setState({ UpdateLetterDetailsPanel: false });
    }

    showUpdateLetterDetailsPanel(button: any) {
        this.setState({ UpdateLetterDetailsPanel: true })
    }

    closeUpdateLetterDetailsPanel() {
        this.setState({ UpdateLetterDetailsPanel: false })

    }

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

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

    }

    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 } }}></IconButton>
                </div>
            </div>
            // <div className="panel-header-text "><FormattedMessage id={item.headerText} /></div>
        )
    }

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

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

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

    private moveDraftCorrespondence(obj: CorrespondenceTransfer, button: any) {
        if (button && button.block) button.block();
        this._recordService.moveDraftCorrespondence(obj).then(
            () => {
                this.setState({ MoveDraftCorrespondencePanel: false });

                if (this.props.refreshTable)
                    this.props.refreshTable();
                if (this.props.closePanel)
                    this.props.closePanel();

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

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

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

    private _showSignDialog = (): void => {
        this.setState({ hideSignDialog: false });
    };

    private _closeSignDialog = (): void => {
        this.setState({ hideSignDialog: true });
    };

    private _showUnSignDialog = (): void => {
        this.setState({ hideUnSignDialog: false });
    };

    private _closeUnSignDialog = (): void => {
        this.setState({ hideUnSignDialog: true });
    };

    private _showExportExternalDialog = (): void => {
        this.setState({ hideExportExternalDialog: false });
    };

    private _closeExportExternalDialog = (): void => {
        this.setState({ hideExportExternalDialog: true });
    };

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

}