
import * as React from "react";
import { DocumentCard, DocumentCardTitle, DocumentCardStatus, DocumentCardActivity, Panel, PanelType, IconButton } from "office-ui-fabric-react";

import "./RecordQuickView.css";
import { DateUtils } from "../../Utils";
import { FormattedMessage } from "react-intl";
import { FormView } from "./FormView";
import { CachingService, OrganizationService, UserService, EntityService } from "../../Services";

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

    private _dateUtils: DateUtils = new DateUtils();
    // private _recordService: RecordService = new RecordService();
    private _entityService: EntityService = new EntityService();
    private _organizationService: OrganizationService = new OrganizationService();
    private _userService: UserService = new UserService();
    private _cachingService: CachingService = new CachingService();

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

        this.state = {
            showRecordViewPanel: false,
            Record: this.props.Record,
            reasonLookups: []
        }

        this._getCreatedBy();
        this._getFromDepartment();
        this._getToDepartments();
        this._getReasons();
    }

    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 showViewRecordrenderPanelBody = (): JSX.Element => {
        //debugger;
        return (
            <div >
                <FormView Record={this.state.selectedItem} />
            </div>)
    }

    _getReasons() {
        this._entityService.getReasonLookups('transfer').then((result: any) => {

            // this.state.reasonLookups = result;
            this.setState({ reasonLookups: result })

        }, error => {
            // alert(error.text());
            // this.toastr.error('', error.text());            
            //this.displayAlertModal(error.text());
            alert(error);
        });
    }

    _getReason(reasonId: number) {
        let reasonText = "";
        if (this.state.reasonLookups.length > 0) {
            this.state.reasonLookups.forEach((reason: any) => {
                if (reason.id == reasonId)
                    reasonText = reason.value;
            })
        }

        return reasonText;
    }

    // private getRecord(entityId: number, recordId: number, isViewMode: boolean) {
    //     this.setState({ loadingData: true });

    //     this._recordService.getRecord(entityId, recordId)
    //         .then(result => {

    //             this.setState({ selectedItem: result, showRecordViewPanel: true });

    //         }, error => {

    //             alert(error);
    //         });

    // }

    private _getFromDepartment() {
        if (this.state.Record && this.state.Record.FromDepartment && !this.state.Record.FromDepartmentObj) {
            this._organizationService.getOrganization(this.state.Record.FromDepartment)
                .then(result => {
                    this.state.Record.FromDepartmentObj = result.data;
                    this.forceUpdate();
                }, error => {

                    alert(error);
                });
        }
    }

    private _getToDepartments() {
        if (this.state.Record && this.state.Record.ToDepartments) {
            this.state.Record.ToDepartments.forEach((dep: any) => {
                if (dep.ToDepartment)
                    this._organizationService.getOrganization(dep.ToDepartment)
                        .then(result => {
                            dep.ToDepartmentObj = result.data;
                            this.forceUpdate();
                        }, error => {

                            alert(error);
                        });
            });

        }
    }

    private _getCreatedBy() {
        if (this.state.Record && this.state.Record.CreatedBy && !this.state.Record.CreatedByObj) {
            this._userService.getUser(this.state.Record.CreatedBy)
                .then(result => {
                    this.state.Record.CreatedByObj = result.data;
                    this.forceUpdate();
                }, error => {

                    alert(error);
                });
        }
    }

    // private viewEntityRecord(id: number) {
    //     this.getRecord(14, id, true);
    // }

    private closeRecordViewPanel() {
        this.setState({ showRecordViewPanel: false });
    };

    public render(): JSX.Element {
        let element = this.state.Record;
        let _title = element.FromDepartmentObj ? (element.FromDepartmentObj.name + " ") : "";
        let _activity = "";
        let _title_prefix = "";

        let lang = this._cachingService.readPersistant("Language");

        if (element.Status == 22) {
            _title = _title + (lang == 1 ? " انشأت المراسلة" : "created correspondence ");
            _activity = lang == 1 ? " انشأت" : "Created ";
        }
        else if (element.Status == 71) {
            _title = _title + (lang == 1 ? "مراسلة محولة " : "forwarded correspondence ");
            _activity = lang == 1 ? "صادرة " : "Sent ";
            _title_prefix = lang == 1 ? "إلي: " : "To: ";
        }
        else if (element.Status == 24) {
            _title = _title + (lang == 1 ? "مراسلة مستقبلة " : "received correspondence");
            _activity = lang == 1 ? "واردة " : "Received ";
            _title_prefix = lang == 1 ? "من: " : "From: ";
        }
        else if (element.Status == 72) {
            _title = _title + (lang == 1 ? "تم الرد عليها بحالة الموافقة " : "approved correspondence");
            _activity = lang == 1 ? "صادرة " : "Sent ";
            _title_prefix = lang == 1 ? "إلي: " : "To: ";
        }
        else if (element.Status == 74) {
            _title = _title + (lang == 1 ? "تم الرد عليها بحالة رفض " : "rejected correspondence");
            _activity = lang == 1 ? "صادرة " : "Sent ";
            _title_prefix = lang == 1 ? "إلي: " : "To: ";
        }
        else if (element.Status == 75) {
            _title = _title + (lang == 1 ? "تم الرد عليها بمراسلة جديدة " : "replied with new correspondence");
            _activity = lang == 1 ? "صادرة " : "Sent ";
            _title_prefix = lang == 1 ? "إلي: " : "To: ";
        }
        else if (element.Status == 26) {
            _title = _title + (lang == 1 ? "استقبلت موافقة " : "received approval");
            _activity = lang == 1 ? "واردة " : "Received ";
            _title_prefix = lang == 1 ? "من: " : "From: ";
        }
        else if (element.Status == 27) {
            _title = _title + (lang == 1 ? "استقبلت رفض " : "received rejection");
            _activity = lang == 1 ? "واردة " : "Received ";
            _title_prefix = lang == 1 ? "من: " : "From: ";
        }
        else if (element.Status == 62) {
            _title = _title + ("closed correspondence");
            _activity = "Sent ";
            _title_prefix = "Sent to: ";
        }
        else if (element.Status == 78) {
            _title = _title + ("re opened correspondence");
            _activity = "Sent ";
            _title_prefix = "Sent to: ";
        }
        else if (element.Status == 103) {
            _title = _title + ("archived correspondence");
            _activity = "Archived ";
            _title_prefix = "Sent to: ";
        }
        else if (element.Status == 104) {
            _title = _title + ("exported correspondence externally");
            _activity = "Exported ";
            _title_prefix = "Exported to: ";
        }
        else if (element.Status == 1011) {
            _title = _title + ("signed correspondence");
            _activity = "Signed ";
            _title_prefix = "Sent to: ";
        }
        else if (element.Status == 1012) {
            _title = _title + ("unsigned correspondence");
            _activity = "UnSigned ";
            _title_prefix = "Sent to: ";
        }
        else if (element.Status == 1013) {
            _title = _title + ("moved correspondence");
            _activity = "Moved ";
            _title_prefix = "Sent to: ";
        }
        else if (element.Status == 2004) {
            _title = _title + ("updated letter details");
            _activity = "Updated ";
            _title_prefix = "Updated to: ";
        }

        _activity = _activity + this._dateUtils.formatDate(element.CreatedDate)

        return (<div><DocumentCard>

            <div className="ms-ConversationTile-TitlePreviewArea">
                <DocumentCardTitle
                    title={_title}
                    shouldTruncate={true}

                />
                {element.ToDepartments.map((obj: any) => {
                    obj.Comments = obj.Comments.replace(/<[^>]*>/g, '');
                    return (<div className={"transferInfo"}>
                        <DocumentCardTitle
                            title={_title_prefix + (obj.ToDepartmentObj ? obj.ToDepartmentObj.name : "")}
                            shouldTruncate={true}
                            showAsSecondaryTitle={true}

                        />
                        <DocumentCardTitle
                            title={'Reason: ' + this._getReason(obj.Reason)}
                            shouldTruncate={true}
                            showAsSecondaryTitle={true}
                        />
                        <DocumentCardTitle
                            title={obj.Comments}
                            shouldTruncate={true}
                            showAsSecondaryTitle={true}
                        >
                        </DocumentCardTitle>

                        {obj.Attachments && obj.Attachments.length > 0 &&
                            <DocumentCardStatus statusIcon="attach" status={obj.Attachments.length + "  Attachments"} />
                        }
                    </div>
                    )
                })}

            </div>
            {element.CreatedByObj &&
                <DocumentCardActivity
                    activity={_activity}
                    people={[
                        { name: element.CreatedByObj.name, profileImageSrc: '' },
                    ]}
                />
            }
            {/* <div className="quickviewqActions card-view-icon">
                <DocumentCardActions
                    actions={[
                        {

                            iconProps: { iconName: 'View' },
                            onClick: (ev: any) => {
                                this.viewEntityRecord(element.CorrespondenceId);
                            },
                            text: this._cachingService.readPersistant("Language") == 1 ? "عرض" : "View",
                            buttonType: ButtonType.primary,
                            ariaLabel: 'View Correspondence',
                            primary: true
                        }
                    ]}
                />
            </div> */}
        </DocumentCard>
            <Panel
                className="panelStyle"
                isOpen={this.state.showRecordViewPanel}
                onDismissed={this.closeRecordViewPanel.bind(this)}
                type={PanelType.medium}
                onRenderBody={this.showViewRecordrenderPanelBody.bind(this)}
                headerText="ViewRecord"
                headerClassName="panelHeaderStyle"
                hasCloseButton={false}
                isLightDismiss={true}
                isFooterAtBottom={true}
                onRenderHeader={this._onReadnderHader}

            >

            </Panel>
        </div>
        )
    }
}