import React from 'react';
import * as actions from './EditAlertActions';
import {checkDeepEquals, debounce, cloneDeep,dateFormatter,triggerGAEvent} from '../../UtilitiesFunctions/objectUtilities';
import Comment from '../ChatWidget/Comment';
import InformationTab from '../ChatWidget/InformationTab';
import EditAlertSelectInput from './EditAlertSelectInput';
import Button from '../formElements/Button';
import Tooltip from '../Tooltip/Tooltip';
import style from './EditAlerts.scss';
import {doHttpGet, doHttpPost,camelCaseToNormalString, abortRequest} from '../../UtilitiesFunctions/ajaxUtilities';
import Modal from 'react-modal';
import injectTapEventPlugin from 'react-tap-event-plugin';
import Toast from "../Toast/Toast";
import ChatWidget from "../ChatWidget/ChatWidget";
import DateTimePicker from '../formElements/DateTimePicker';
import * as _ from "lodash";
import moment from "moment";


injectTapEventPlugin();
export default class EditAlerts extends React.Component{

    constructor(props) {    
        super(props);
        this.state = {saveBtnDisabled: true, data: [], editData: [],
         EditModalDropDownData:(this.props.EditModalDropDownData ? this.props.EditModalDropDownData:[]),
         commentHistory: [], documentData: [], 
         uploadingDocument: false ,
         toastData: {}, 
         showToast: false, 
         lastComment: '', 
         breakDownReasons: {}, 
         selectedBreakDownReason: {}, 
         dispatchTime: null, 
         unloadingTimestamps:{
            etaTimestamp : null,
            cwhReachedTimestamp : null,
            expectedUnloadingTimestamp: null,
            actualUnloadingTimestamp : null
         },
         alertId: null, 
         timeConstraintsMinHr: 0, 
         timeConstraintsMinMinute: 0,   
         timeConstraintsMaxHr:23,
         timeConstraintsMaxMinute:59,              
         showEtaDropDown: false,
         showULCompletedAtDropDown: false,
         filterValues :{},
         closeTripFlag : false,
         showULExpectedCompletionTimeDropDown: false,
         confirmClose:false,
         showConfirmClose:false,
         disableAllFlag:false,
         disableAssignEscalateInform:false,
         appointmentHistoryColumns:[{                    
                             Header : 'Unloading Time',
                             id:'vehicleNumber',
                             accessor: props => {return(
                                <div>{props.overrideTime ? dateFormatter(props.overrideTime) : '-'}</div>)
                            }
                            },{
                            Header : 'Last Updated By',
                            id:'currentTrip',
                            accessor: props => { return(<div>
                                {props.updatedBy == 1 ? 'System' : props.updatedBy}
                                </div>
                                )}
                           },{
                            Header : 'Last Updated At',
                            id:'lastUpdatedTimestamp',
                            accessor: props => {return(
                                    <div>{
                                        props.updatedTime ? 
                                        dateFormatter(props.updatedTime) : '-'
                                    }
                                    </div>
                                    )
                            }},{
                            Header : 'Reason',
                            id:'reason',
                            accessor: props => (props.overrideReason) ? (props.overrideReason) : '-' 
                        }],
         appointmentHistoryRows:[],
         showCwhReachedAtDropDown: false};
    }

    componentDidMount(){
            // for prime-ops
        if(!this.props.EditModalDropDownData || this.props.isCalledFromAnotherRepo){
            let EditModalDropDownData = actions.getEditModalDropdownData();
            let columns = actions.getEditColumns()
            this.setState({
                EditModalDropDownData: actions.getEditModalDropdownData()
            });
            this.getDropdownData(this.props.data.ticketType);
            this.setEditModalData(this.props.data, EditModalDropDownData);
            this.setBasicData(this.props.data, columns[this.props.data.ticketType]);
            this.setAlertIdForNotification(this.props.data);
        }
        //for prime-panel-new
        else{
            this.setEditModalData(this.props.data, this.state.EditModalDropDownData);
            this.setBasicData(this.props.data, this.props.alertTypeToAlertColumnsMap[this.props.selectedTab].alertEditColumns);
            this.setAlertId(this.props.data, this.props.completeData);
        }
        let vntStr = this.props.data ? this.props.data.body : '';
        if(vntStr){
            let lastIndex = vntStr.lastIndexOf(',');
            if(lastIndex >= 0){
            let vntId = vntStr.substr(lastIndex,vntStr.length - lastIndex + 1);
            if(vntId.length > 7 && this.props.selectedTab === 'UNLOADING_VEHICLES'){
                 vntId = vntId.substr(7,vntId.length - 6);
                 if(null != vntId){
                    vntId = parseInt(vntId);
                    this.fetchAppointmentDeliveryData(vntId);
                 }
            }
            }
    }
        this.setState({breakDownReasons: actions.getBreakdownReasons()});
    }

    componentWillReceiveProps(nextProps) {
        // if(nextProps.EditModalBasicData.ticketId !== this.props.EditModalBasicData.ticketId) {
        //     // this.props.getCommentData(nextProps.EditModalBasicData.ticketId);
        //     this.props.setBasicData(nextProps.EditModalBasicData, this.props.selectedTab, this.props.alertTypeToAlertColumnsMap);
        // }
        // if(nextProps.ticket_updated) {
        //     this.props.onModalClose();
        //     this.props.updateTicketStatus(false);
        // }

    }

    fetchAppointmentDeliveryData = (vntId) => {
        var url = `${this.props.hostUrls.VehicleTrackingUrl}api/v1/deliveryappointment/${vntId}`;
        let promise = doHttpGet(url, {});

        promise.then((response) => {
            if (response.status === 200){
                let data  = response.data;
                this.setState({appointmentHistoryRows:data});
            }
        });
    }

    getInfoTab = () => {
        return(
            <InformationTab 
                columns={this.state.appointmentHistoryColumns} 
                data={this.state.appointmentHistoryRows}
            />
        )
    }

    getExtraTabComponents = () =>{
        let extraTabs = {'Appointment History' : this.getInfoTab()};
        return extraTabs;
    }


    setEditModalData(data, editModalDropdownData){
        this.getCommentData(data.ticketId, true, false);
        let reason  = data.reason?data.reason:'';
        editModalDropdownData.map((dropdownData) => {
            if(dropdownData.label === "Select Reason")
                dropdownData.value = {label: reason, value: reason};
            return dropdownData;
        });

        let filterValues = actions.populateFilterValues(data,editModalDropdownData);
        let filterModifiedValuesForUnloading = actions.modifyFilterValues(Object.assign({},filterValues));
        this.setState({
            EditModalDropDownData: editModalDropdownData,
            filterValues: filterModifiedValuesForUnloading,
            filterDefaultValues: Object.assign({}, filterValues),
            EditModalBasicData: data,
            loadingCommentHistory: true
        });
    }

    setCloseTripFlag = (label,value,EditModalDropDownData) =>{
        let actualUnloadingCompletionTimeIndex = _.findIndex(EditModalDropDownData, function(data) 
                                        { return data.label  === "Actual Unloading Time"});
        let closeTrip = this.state.filterValues['Actual Unloading Time'] &&
             this.state.filterValues['Actual Unloading Time'].value && 
             EditModalDropDownData[actualUnloadingCompletionTimeIndex] &&
             EditModalDropDownData[actualUnloadingCompletionTimeIndex].show &&
             null != value  && value.value == 'POD received'  ;           

             if(this.props.data && (this.props.data['businessType'] === 'Ecom' ||
              this.props.data['businessType'] === 'Zoom')){
                     if((label == 'Vehicle Status'
                         && value
                          && (!(value.value == 'Vehicle Running' || value.value == 'Back at Hub')))
                      || 
                      (!(label == 'Vehicle Status') && this.state.filterValues['Vehicle Status'] && 
                      (!(this.state.filterValues['Vehicle Status'].value == 'Vehicle Running' || this.state.filterValues['Vehicle Status'].value == 'Back at Hub'))
                      )){
                            closeTrip = true;
                        }else
                            closeTrip = false;
              }
            

              this.setState({
                   closeTripFlag : closeTrip,
                   disableAssignEscalateInform  : closeTrip,
                   EditModalDropDownData:EditModalDropDownData,
                   disableAllFlag: false
                });     
        return closeTrip;      
    }

    setBasicData(data, columns){
        let basicData = [];
        if(data && columns ) {
            columns.forEach((field) => {
                if(field.id === 'cwhDetails'){
                    basicData.push({label: field.Header, value:data['cwhCode']})
                }else if(field.id === 'vehicleNoType'){
                    basicData.push({label: field.Header, value:data['vehicleNumber']})
                }else{
                basicData.push({label: field.Header, value: data[field.id]});
            }
            })
        }
        this.setState({editData: basicData, EditModalBasicData: data});

    }

    getCommentData(ticketid, setFilter = true, showLoader = true){
        let url =  this.props.hostUrls.TicketingUrl +`api/v1/info/activityCc/${ticketid}`;
        let promise = doHttpGet(url, {});
        if(showLoader){
            this.setState({loadingCommentHistory: true});
        }
        let _self = this;
        promise.then((response) => {
            _self.setCommentdata(response, setFilter);
        }, (err) => {
        })
    }

    setCommentdata(response, setFilter){
        let data = [], filterValues = this.state.filterValues, documents = [], EditModalDropDownData=this.state.EditModalDropDownData;
        let filterDefaultValues = this.state.filterDefaultValues;
        if (response.status === 200) {
            let comments = response.data.comments;
            documents = response.data.documents;
            let actionToUserMap = response.data.actionToUserMap;
            let asigneeDetails = response.data.asigneeDetails;
            data = actions.sortAndConvertCommentHistory(comments, documents);
            if(setFilter) {
                filterValues = actions.convertFilterValues(actionToUserMap, asigneeDetails, EditModalDropDownData, filterValues);
                filterDefaultValues = actions.convertFilterValues(actionToUserMap, asigneeDetails, EditModalDropDownData, filterDefaultValues);
                EditModalDropDownData = actions.populateEditModalDropdownValues(filterValues, EditModalDropDownData);
            }
        }
        else{
            // dispatch(ToastActions.pushToast({
            //     message: 'Unable to Fetch Comment History'
            // }));
            this.setState({toastData: {
                message: 'Unable to Fetch Comment History!'
            }, showToast: true});
        }
        console.log('setFIlter', setFilter);
        if(setFilter) {
            console.log('inside filter', setFilter);
            this.setState({
                filterValues: filterValues,
                filterDefaultValues: Object.assign({}, filterDefaultValues),
                EditModalDropDownData: EditModalDropDownData,
                commentHistory: data,
                documentData: documents,
                loadingCommentHistory: false
            });
        }
        else{
            this.setState({
                commentHistory: data,
                documentData: documents,
                loadingCommentHistory: false
            });
        }
    }


    handleSelectValueChange = (label, value) => {
        if(label=='Escalate To') triggerGAEvent('Tickets','ESCALATE_TICKETS')
        if(label=='Inform To') triggerGAEvent('Tickets','INFORM_TICKETS')     
        if(label !== "Select SubReason")
            this.updateSelectedValues(this.state.filterValues, label, value, this.state.EditModalDropDownData);
        else
            this.setState({selectedBreakDownReason: value});

        //resetting values on breakdown selection
        if(label === "Select Reason")
            this.setState({selectedBreakDownReason: {}, dispatchTime: null});

        //let closeTripFlag = this.setCloseTripFlag(label,value);

        //setting flags for unloading
        if(label === "Vehicle Status")
            this.handleVehicleStatusChange(value ? value.value : null, label,value);


       /* if(label === "ETA" || label === 'Cwh Reached At' || label === 'Expected Unloading Time' || label === 'Actual Unloading Time'){
            th
        }*/

        let _self = this;
        setTimeout(() => {
            _self.setSaveBtnVisibility();
        }, 100);

    }

    checkUnloadingFields = (delta) =>{
        let enableFlag = true;
        this.state.EditModalDropDownData.forEach((entry) =>{
                if(entry.type === 'calender' && entry.show){
                        let index = _.findIndex(delta,(deltaEntry) =>{
                            return deltaEntry.label === entry.label;
                        })

                    if(index < 0)
                        enableFlag=false;
                }
            })
            return enableFlag; 
    }

    setSaveBtnVisibility = () => {
        let delta = this.getUpdateDelta();
        let saveBtnEnabled = (
            (this.state.filterValues["Select Reason"] &&
            this.state.filterValues["Assign To"] &&
            this.state.filterValues["Assign To"].label &&
            this.props.data.ticketStatus !== 'CLOSED')            
        );
        if(this.checkBreakdownVisibility()) {
            if(saveBtnEnabled)
                saveBtnEnabled = (this.state.selectedBreakDownReason && this.state.selectedBreakDownReason.label && this.state.dispatchTime);
        }
        else{
            saveBtnEnabled = (delta.length > 0 && this.props.data.ticketStatus !== 'CLOSED');
        }
        this.setState({saveBtnDisabled: !saveBtnEnabled});
    }

    updateSelectedValues(filterValues, label, value, EditModalDropDownData) {
        let test = Object.assign({},filterValues);
        test[label] = value;
        EditModalDropDownData = actions.populateEditModalDropdownValues(test, EditModalDropDownData);
        this.setState({
            filterValues: test,
            EditModalDropDownData: EditModalDropDownData
        });
    }

    cancelSave = () =>{
        this.setState({disableAllFlag: false,showConfirmClose:false, saveBtnDisabled:false});
    }

    handleOnSave = () => {
        if(this.state.closeTripFlag && !this.state.showConfirmClose){
            this.setState({showConfirmClose : true,disableAllFlag:true});
        }else{
        this.setState({saveBtnDisabled: true});
        let delta = this.getUpdateDelta();
        this.updateTicket(this.state.EditModalBasicData.ticketId, delta, this.props.user);
        if(this.checkBreakdownVisibility())
            this.updateEtd();
    }
}

    getUpdateDelta = () => {
        let delta = [];
        let filterdefaultValues =  this.state.filterDefaultValues;
        let filterValues = this.state.filterValues;
        let EditModalDropDownData = this.state.EditModalDropDownData;
        let keySet = Object.keys(filterValues);
        keySet.forEach((label) => {
            if(!(label in filterdefaultValues) || !checkDeepEquals(filterdefaultValues[label], filterValues[label])){
                if( filterValues && filterValues[label] && (filterValues[label].value || filterValues[label].length > 0)) {
                     let index = _.findIndex(EditModalDropDownData, function(data) 
                        { return data.label  === label});
                     if(EditModalDropDownData[index] && ((EditModalDropDownData[index].type === 'calender' && EditModalDropDownData[index].show )
                        || !(EditModalDropDownData[index].type === 'calender'))){
                            delta.push({ label: label, value: filterValues[label]});                    
                     }
                }
            }
        });
        return delta;
    }

    getDropdownData(selectedTab = 'TOUCHING_MISSING'){
        let url =  this.props.hostUrls.partTruckUrl + `api/v1/alerts/reasonsAndTeams?alertType=${selectedTab}`;
        let promise = doHttpGet(url, {});
        let _self = this;
        promise.then((response) => {
            let data = {"reasons": [], "teams": [], inputData: []};
            let deleteReasons = [];
            if (response.status === 200) {
                let dropdownData = response.data;
                for (let i = 0; i < dropdownData.reasons.length; i++) {
                    let reason = {};
                    reason.label = reason.value = dropdownData.reasons[i];
                    data["reasons"].push(reason);
                }
                for (let i = 0; i < dropdownData.deleteReasons.length; i++) {
                    let reason = {};
                    reason.label = reason.value = dropdownData.deleteReasons[i];
                    deleteReasons.push(reason);
                }
                for (let i = 0; i < dropdownData.groupDetailDtoList.length; i++) {
                    let team = {};
                    team.label = dropdownData.groupDetailDtoList[i].name;
                    team.value = dropdownData.groupDetailDtoList[i].path;
                    data["teams"].push(team);
                }

            let vehicleStatusDataForUnloading = [{
                label : 'Vehicle Running',
                value : 'Vehicle Running'
              },{
                label : 'Cwh Reached',
                value : 'Cwh Reached'
              },{
                label : 'Unloading Started',
                value : 'Unloading Started'
              },{
                label: 'Unloading completed;POD pending',
                value: 'Unloading completed;POD pending'
              },{
                label: 'POD received',
                value: 'POD received'
              },{
                label: 'Back at Hub',
                value: 'Back at Hub'
              }];

                let inputData = [];
                let filterValues = _self.state.filterValues;
                inputData.push(actions.getInputData(data["reasons"], "Select Reason", false, false,filterValues,'dropdown',true,"reasons"));
                inputData.push(actions.getInputData(data["teams"], "Assign To", false, false,filterValues,'dropdown',true,"assignedTo"));
                inputData.push(actions.getInputData(data["teams"], "Inform To", false, true,filterValues,'dropdown',true,"informTo"));
                if(selectedTab === 'UNLOADING_VEHICLES'){
                    inputData.push(actions.getInputData(vehicleStatusDataForUnloading,"Vehicle Status",false,false,filterValues,'dropdown',true,"vehicleStatus"));
                    inputData.push(actions.getInputData({},"ETA",false,false,filterValues,'calender',false,"eta"));
                    inputData.push(actions.getInputData({},"Cwh Reached At",false,false,filterValues,'calender',false,"cwhReachedTimestamp"));
                    inputData.push(actions.getInputData({},"Expected Unloading Time",false,false,filterValues,'calender',false,"expectedUnloadingTimestamp"));
                    inputData.push(actions.getInputData({},"Actual Unloading Time",false,false,filterValues,'calender',false,"actualUnloadingTimestamp"));

                  }
                data["inputData"] = inputData;
                let dropdownDataValues = cloneDeep(data);
                _self.getManagerData(dropdownDataValues);
                inputData.push(actions.getInputData([], "Escalate To", false, true, filterValues,'dropdown',true,"escalateTo"));
                this.setState({
                    EditModalDropDownData: inputData
                })
            }

        }, (err) => {

        })
    }
    getManagerData(data){
            let url = this.props.hostUrls.partTruckUrl + `api/v1/alerts/managers`;
            let promise = doHttpGet(url, {});
            let _self = this;
            promise.then((response) => {
                let escalateData = [];
                if (response.status === 200) {
                    let responseData = response.data;
                    responseData.forEach((data, i) => {
                        escalateData.push({label: data.name + ' | ' + data.department, value: data.email});
                    });
                }
                else{
                    // dispatch(ToastActions.pushToast({
                    //     message: 'Unable to Fetch Manager Data'
                    // }));
                }
                let filterValues = _self.state.filterValues;
                data["inputData"].push(actions.getInputData(escalateData, "Escalate To", false, true, filterValues,'dropdown',true,"escalateTo"));
                this.setState({
                    EditModalDropDownData: data.inputData
                })

            }, (err) => {

            })
    }

    updateTicket =(ticketid, delta, user) => {
        if(delta.length > 0) {
            let url = this.props.hostUrls.TicketingUrl + `api/v1/activity/${ticketid}/update_actions_metadata`;
            let assigneeDetails = {}
            let actionToPersonMap = {};
            let updatedMetadata = {};
            let self = this.props;
            delta.forEach((item) => {
                if (item.label === "Assign To"){
                    assigneeDetails = {userType: "GROUP", userId: item.value.value, name: item.value.label};
                }
                else if (item.label === "Inform To") {
                    actionToPersonMap['INFORM'] = [];
                    item.value.forEach((selectedItem) => {
                        actionToPersonMap['INFORM'].push({userType: "GROUP", userId: selectedItem.value, name: selectedItem.label});
                    });

                }
                else if (item.label === "Escalate To") {
                    actionToPersonMap['ESCALATE'] = [];
                    item.value.forEach((selectedItem) => {
                        actionToPersonMap['ESCALATE'].push({userType: "USER", userId: selectedItem.value, name: selectedItem.label});
                    });
                }
                else if (item.label === "Select Reason" )
                    updatedMetadata['reason'] = item.value.value;

                else if(item.label === 'Vehicle Status')
                    updatedMetadata['unloadingStatus'] = item.value.value;

                else if(item.label  === 'ETA' || item.label === 'Cwh Reached At' || 
                    item.label === 'Actual Unloading Time' 
                    || item.label === 'Expected Unloading Time'){
                    updatedMetadata[item.value.label] = item.value.value;
                }

                if(self.data && (self.data['businessType'] == 'Ecom' || self.data['businessType'] =='Zoom') && item.label === 'Cwh Reached At'){
                    updatedMetadata['actualUnloadingTimestamp'] = item.value.value;                    
                }

                if(self.data && (self.data['businessType'] == 'Ecom' || self.data['businessType'] =='Zoom')  && item.label === 'Actual Unloading Time'){
                    updatedMetadata['cwhReachedTimestamp'] = item.value.value;                    
                }



            });
            triggerGAEvent('Tickets','SAVE_TICKETS')
            if(this.checkBreakdownVisibility()){
                updatedMetadata["etd"] = this.state.dispatchTime.valueOf();
                updatedMetadata["break_down_reason"] = this.state.selectedBreakDownReason.value;
            }
            let data = {
                ticketId: ticketid,
                assigneeDetails: assigneeDetails,
                actionToPersonMap: actionToPersonMap,
                updatedBy: user.email,
                updatedMetadata: updatedMetadata,
                comment: this.state.lastComment
            };
            let promise = doHttpPost(url, data, {});
            promise.then((response) => {
                if (response.status === 200) {
                    this.props.onModalClose(true);
                    this.setState({saveBtnDisabled: false});
                    if(this.props.closeNotificationOnSave){
                        let obj = {
                            ticketId: ticketid,
                            createdTimestamp : (new Date).getTime()
                        }
                        this.props.closeNotificationOnSave(obj);
                    }

                                   //TODO on update ticket
                }
                else {
                    this.setState({toastData: {
                        message: 'Some error occurred while updating ticket!'
                    }, showToast: true});

                }

            }, (err) => {

            })
        }
        else{
            this.setState({toastData: {
                message: 'Nothing to Save!'
            }, showToast: true});
        }
    }

    addComment(ticketid, comment){
        let user = this.props.user;
        let commentHistory1 = this.state.commentHistory;
        let commentHistoryData = {userDetail: {name: user.firstName + ' ' +user.lastName}, commentText: comment, lastUpdatedTimestamp: new Date().getTime() };
        commentHistory1.push(actions.convertComment(commentHistoryData));
        this.setState({commentHistory: commentHistory1, lastComment: ''});

        triggerGAEvent('Tickets','COMMENT_TICKETS');
        let url = `${this.props.hostUrls.TicketingUrl}/api/v1/activity/${ticketid}/add_comment`;
        let userDetail = {userType:"USER", userId : user.email}
        let data = {commentText: comment, userDetail: userDetail};
        let promise = doHttpPost(url, data, {});
        let _self = this;
        promise.then((response) => {
            if (response.status === 200) {
                _self.getCommentData(ticketid, false, false);
                   if(_self.props.closeNotificationOnSave){
                        let obj = {
                            ticketId: ticketid
                        }
                        _self.props.closeNotificationOnSave(obj);
                    }
            }

        }, (err) => {

        })
    }

    uploadFiles(event, ticketid){
        //check for file types
        let file = event.target.files[0];
        if(!(file.type === "application/pdf" || file.type === "image/jpeg" || file.type === "image/png")){
            this.setState({toastData: {
                message: 'Only images and pdf files are supported!'
            }, showToast: true});
            return null;
        }
        else if(file.size > 5000000){
            this.setState({toastData: {
                    message: 'File size should be less then 5MB!'
                }, showToast: true});
            return null;
        }

        triggerGAEvent('Tickets','ATTACHMENT_TICKETS');
        this.setState({uploadingDocument: true});
        let user = this.props.user;
        let url = this.props.hostUrls.TicketingUrl + `api/v1/activity/${ticketid}/upload_document`;
        let params = {requestId: 'file-upload'};
        params.headers = {
            'Content-Type': 'multipart/form-data'
        };
        let formData = new FormData();
        formData.append('userEmailId', user.email);
        formData.append('document', event.target.files[0]);

        let promise = doHttpPost(url, formData, params);
        let _self = this;
        promise.then((response) => {
            if (response.status === 200) {
                _self.getCommentData(ticketid, false, true);
                this.setState({toastData: {
                    message: 'Document Uploaded successfully!'
                }, showToast: true});
                this.setState({uploadingDocument: false});
            }
            else{
                // dispatch(ToastActions.pushToast({
                //     message: 'Some error occurred while uploading document!'
                // }));
                this.setState({toastData: {
                    message: 'Some error occurred while uploading document!'
                }, showToast: true});

            }

        }, (err) => {
            // dispatch(ToastActions.pushToast({
            //     message: 'Some error occurred while uploading document!'
            // }));
            this.setState({toastData: {
                message: 'Some error occurred while uploading document!'
            }, showToast: true});
        })
    }

    handleOnToastRemoval(){
        this.setState({toastData: {}, showToast: false});
    }

   handleVehicleStatusChange = (vehicleStatus,label,value) => {
     let EditModalDropDownData = this.state.EditModalDropDownData;
     let etaIndex = _.findIndex(EditModalDropDownData, function(data) { return data.label  === "ETA" });
     let cwhReachedAtIndex  = _.findIndex(EditModalDropDownData, function(data) { return data.label  === "Cwh Reached At"}); 
     let expectedUnloadingCompletionTimeIndex = _.findIndex(EditModalDropDownData, function(data) { return data.label  === "Expected Unloading Time"});
     let actualUnloadingCompletionTimeIndex = _.findIndex(EditModalDropDownData, function(data) { return data.label  === "Actual Unloading Time"});


         switch (vehicleStatus){
            case 'Vehicle Running':  
                if(etaIndex >= 0)
                    EditModalDropDownData[etaIndex]["show"] = true;

                if(expectedUnloadingCompletionTimeIndex >= 0)
                    EditModalDropDownData[expectedUnloadingCompletionTimeIndex]["show"] = true;

                if(actualUnloadingCompletionTimeIndex >= 0)
                    EditModalDropDownData[actualUnloadingCompletionTimeIndex]["show"] = false;

                if(cwhReachedAtIndex >= 0)
                    EditModalDropDownData[cwhReachedAtIndex]["show"] = false;

            break;

        case 'Cwh Reached':
            if(etaIndex >= 0)
                    EditModalDropDownData[etaIndex]["show"] = false;

                if(expectedUnloadingCompletionTimeIndex >= 0)
                    EditModalDropDownData[expectedUnloadingCompletionTimeIndex]["show"] = true;

                if(actualUnloadingCompletionTimeIndex >= 0)
                    EditModalDropDownData[actualUnloadingCompletionTimeIndex]["show"] = false;

                if(cwhReachedAtIndex >= 0)
                    EditModalDropDownData[cwhReachedAtIndex]["show"] = true;

                break;
         
        case 'Unloading Started':
             if(etaIndex >= 0)
                    EditModalDropDownData[etaIndex]["show"] = false;

                if(expectedUnloadingCompletionTimeIndex >= 0)
                    EditModalDropDownData[expectedUnloadingCompletionTimeIndex]["show"] = true;

                if(actualUnloadingCompletionTimeIndex >= 0)
                    EditModalDropDownData[actualUnloadingCompletionTimeIndex]["show"] = false;

                if(cwhReachedAtIndex >= 0)
                    EditModalDropDownData[cwhReachedAtIndex]["show"] = true;

          
                break;

        case 'Unloading completed;POD pending':
            if(etaIndex >= 0)
                    EditModalDropDownData[etaIndex]["show"] = false;

                if(expectedUnloadingCompletionTimeIndex >= 0)
                    EditModalDropDownData[expectedUnloadingCompletionTimeIndex]["show"] = false;

                if(actualUnloadingCompletionTimeIndex >= 0)
                    EditModalDropDownData[actualUnloadingCompletionTimeIndex]["show"] = true;

                if(cwhReachedAtIndex >= 0)
                    EditModalDropDownData[cwhReachedAtIndex]["show"] = true;
           
          
                break;

          case 'POD received':
            if(etaIndex >= 0)
                    EditModalDropDownData[etaIndex]["show"] = false;

                if(expectedUnloadingCompletionTimeIndex >= 0)
                    EditModalDropDownData[expectedUnloadingCompletionTimeIndex]["show"] = false;

                if(actualUnloadingCompletionTimeIndex >= 0)
                    EditModalDropDownData[actualUnloadingCompletionTimeIndex]["show"] = true;

                if(cwhReachedAtIndex >= 0)
                    EditModalDropDownData[cwhReachedAtIndex]["show"] = true;

                break;
           
          case 'Back at Hub':
            if(etaIndex >= 0)
                    EditModalDropDownData[etaIndex]["show"] = false;

                if(expectedUnloadingCompletionTimeIndex >= 0)
                    EditModalDropDownData[expectedUnloadingCompletionTimeIndex]["show"] = true;

                if(actualUnloadingCompletionTimeIndex >= 0)
                    EditModalDropDownData[actualUnloadingCompletionTimeIndex]["show"] = false;

                if(cwhReachedAtIndex >= 0)
                    EditModalDropDownData[cwhReachedAtIndex]["show"] = true;
            
                break;
                
        default: 
                if(etaIndex >= 0)
                    EditModalDropDownData[etaIndex]["show"] = false;

                if(expectedUnloadingCompletionTimeIndex >= 0)
                    EditModalDropDownData[expectedUnloadingCompletionTimeIndex]["show"] = false;

                if(actualUnloadingCompletionTimeIndex >= 0)
                    EditModalDropDownData[actualUnloadingCompletionTimeIndex]["show"] = false;

                if(cwhReachedAtIndex >= 0)
                    EditModalDropDownData[cwhReachedAtIndex]["show"] = false;
       }

       this.setCloseTripFlag(label,value,EditModalDropDownData);
   }


    handleCommentChange(comment){
        this.setState({lastComment: comment});
    }


    checkBreakdownVisibility = () => {
        console.log('checkBreakdownVisibility', this.state, this.props);
        return (this.state.EditModalDropDownData &&
                this.state.EditModalDropDownData[0] &&
                this.state.EditModalDropDownData[0].value.label &&
                this.state.EditModalDropDownData[0].value.label === "Breakdown" &&
                this.props.selectedTab === "UNSCHEDULED_STOPPAGE"
        );
    }

    handleETDChange = (time) => {
        this.setState({dispatchTime: time});
        this.setSaveBtnVisibility();
        let today = new moment();
        let timeConstraints = {};
        let minHr = 0, minMinutes=0;
        if(time.isSame(today, 'day')){
            minHr = today.hour();
            minMinutes = today.minute();
        }
        this.setState({timeConstraintsMinHr: minHr, timeConstraintsMinMinute: minMinutes});
    }

    handleTimeConstraintChangesForUnloading = (time,key) => {
        let today = new moment();
        let timeConstraints = {};
        let minHr = 0, minMinutes=0 , maxHr=23, maxMinutes=59;

        if(key == 'actualUnloadingTimestamp' || key == 'cwhReachedTimestamp'){
            if(time.isSame(today, 'day')){
                maxHr = today.hour();            
            }

            if(time.isSame(today,'hour')) {
                maxMinutes = today.minute();   
            }
        }else{
           if(time.isSame(today, 'day')){
                minHr = today.hour();            
            }

            if(time.isSame(today,'hour')) {
                minMinutes = today.minute();   
            }
        }
        
        this.setState({
            timeConstraintsMinMinute:minMinutes,
            timeConstraintsMinHr:minHr,
            timeConstraintsMaxHr:maxHr,
            timeConstraintsMaxMinute:maxMinutes
        });
    }

    handleUnloadingTimeChanges = (time,label,key) => {

        let t = time;
        if(time && time._d){            
            this.handleSelectValueChange(label,{label: key,value:time._d.valueOf()});
        }

        else
            this.handleSelectValueChange(label,{});

            this.handleTimeConstraintChangesForUnloading(time,key);

    }

    updateEtd = () => {
            let url = `${this.props.hostUrls.VehicleTrackingUrl}api/v1/alerts/breakdownEtdUpdate`;
            if(isNaN(this.state.alertId))
                return;
            var form = new FormData();
            form.append("alertId", parseInt(this.state.alertId));
            form.append("etd", this.state.dispatchTime.valueOf());
            let promise = doHttpPost(url, form, {});
            promise.then((response) => {
                if (response.status === 200) {

                }
                else {
                    this.setState({toastData: {
                        message: 'Some error occurred while updating ETD'
                    }, showToast: true});

                }

            }, (err) => {

            })
    }

    setAlertId = (data, completeData) => {
        let alertId = null;
        if(data && data.ticketId && completeData){
            let index =  _.findIndex(completeData, function(ticket) { return ticket.ticketId  === data.ticketId });
            if(index >= 0) {
                alertId = completeData[index].alertId
                this.setState({selectedBreakDownReason: {label: completeData[index].break_down_reason, value: completeData[index].break_down_reason}, dispatchTime: new moment(parseInt(completeData[index].etd))});
            }
        }

        this.setState({alertId: alertId});
    }

    setAlertIdForNotification = (data) => {
        let alertId = null, break_down_reason = null, etd=null;
        if(data){
            alertId = data.alertId?data.alertId:null;
            break_down_reason = data.break_down_reason?data.break_down_reason:null;
            etd = data.etd?data.etd:null;
        }
        this.setState({alertId: alertId, selectedBreakDownReason: {label: break_down_reason, value: break_down_reason}, dispatchTime: etd?new moment(parseInt(etd)):null});

    }

    isvalidDate = (current) => {
        let today = new moment();
        if(current.isBefore(today.subtract(1, 'day'))) {
            return false;
        }
        return true;
    }

     isvalidDateForUnloading = (key,current) => {
        let today = new moment();
        if(key == 'actualUnloadingTimestamp' || key == 'cwhReachedTimestamp'){
            if(current.isBefore(today)) {
                return true;
            }
            return false;
        }else{              
                if(current.isBefore(today.subtract(1, 'day'))) {
                    return false;
                 }
                return true;                   
            }        
    }

    getTimeConstraints = () => {
        let timeConstraints = {
            hours: {
                min: this.state.timeConstraintsMinHr,
                max: this.state.timeConstraintsMaxHr
            },
            minutes: {
                min: this.state.timeConstraintsMinMinute,
                max: this.state.timeConstraintsMaxMinute
            }
        };
        return timeConstraints;
    }




    render(){
        const props = this.props;
        let reasonObj = (this.state.EditModalDropDownData && this.state.EditModalDropDownData[0])?this.state.EditModalDropDownData[0]:null;
        let vehicleStatusObj = (this.state.EditModalDropDownData && this.state.EditModalDropDownData.length > 4)?this.state.EditModalDropDownData[3]:null;
        let breakDownReasons = this.state.breakDownReasons;
        let showVehicleStatus = props.selectedTab === 'UNLOADING_VEHICLES' ? true : false;
        let timeConstraints = {
            hours: {
                min: this.state.timeConstraintsMinHr,
                max: 24
            },
            minutes: {
                min: this.state.timeConstraintsMinMinute,
                max: 60
            }
        };
        console.log('Edit alert state', this.state);
        return (
                <Modal
                    isOpen={this.props.showEditModal}
                    portalClassName="ReactModalPortal react-modal edit-modal ui-commons"
                    contentLabel="Modal"
                >
                <div className="edit-alert-body modal-content">
                    <div className="table dialog-header stretch">
                        <div className="tableRow">
                            <div className="tableCell header-text">
                                Edit Alert
                            </div>
                            <div className="closeBtn tableCell">
                                <i className="material-icons" onClick={()=>this.props.onModalClose(false)}>&#xE14C;</i>
                            </div>
                        </div>
                    </div>
                    <div className="edit-ticket-container">
                    <div className="ticket-basic-data">
                        {
                            this.state.editData.map((data, i)=>{
                                return (
                                    <div className= "font-type alert-box-data" key = {i}>
                                        <label>{data.label}</label>
                                        <span>
                                        {
                                            (data.value && data.value.length >= 34)?
                                                <Tooltip
                                                    hoverElement={data.value.substr(0,31)+'...'}
                                                    tooltipText={data.value}
                                                    label={data.value.substr(0,31)+'...'}
                                                />
                                                :
                                                data.value
                                        }
                                        </span>
                                    </div>
                                )
                            })
                        }
                    </div>
                    <div className="edit-ticket-filters top-filters">
                        {
                            vehicleStatusObj !== null  && showVehicleStatus ?
                            (
                            <EditAlertSelectInput
                                data = {vehicleStatusObj.data}
                                label = {vehicleStatusObj.label}
                                value={vehicleStatusObj.value}
                                multiLable={vehicleStatusObj.multiLable}
                                multiSelect={vehicleStatusObj.multiSelect}
                                className="edit-ticket-select"
                                onValueChange={this.handleSelectValueChange.bind(this)}
                                disabled={this.state.disableAllFlag}
                            />
                            ) : ''
                        }{
                            this.state.EditModalDropDownData.map((input, i) => {

                                if(input.type === 'dropdown' ||  !input.show){
                                    return;
                                }

                                return( 
                                <div className="edit-ticket-datetime">
                                <DateTimePicker
                                            label={input.label}
                                            valid={this.isvalidDateForUnloading.bind(this,input.key)}
                                            onDateChange={(time) => {this.handleUnloadingTimeChanges(time,input.label,input.key)}}
                                            timeConstraints={this.getTimeConstraints()}
                                            value={(this.state.filterValues[input.label] && this.state.filterValues[input.label].value) ? moment(this.state.filterValues[input.label].value) : moment()}
                                            placeHolder="Select Time"
                                            disabled={this.state.disableAllFlag}  
                                            className="edit-alert-date"                                          
                                        /> 
                                </div>                               
                            ) 
                            })                           
                            
                        }{
                            reasonObj !== null?
                            (
                            <EditAlertSelectInput
                                data = {reasonObj.data}
                                label = {reasonObj.label}
                                value={reasonObj.value}
                                multiLable={reasonObj.multiLable}
                                multiSelect={reasonObj.multiSelect}
                                className="edit-ticket-select"
                                onValueChange={this.handleSelectValueChange.bind(this)}
                                disabled={this.state.disableAllFlag}
                            />
                            ) : ''
                        }
                        {
                            (this.checkBreakdownVisibility() && breakDownReasons.label)?
                                (
                                    <div>
                                        <EditAlertSelectInput
                                            data = {breakDownReasons.data}
                                            label = {breakDownReasons.label}
                                            value={this.state.selectedBreakDownReason}
                                            multiLable={breakDownReasons.multiLable}
                                            multiSelect={breakDownReasons.multiSelect}
                                            className="edit-ticket-select"
                                            onValueChange={this.handleSelectValueChange.bind(this)}
                                        />
                                        <div className="edit-ticket-datetime">
                                        <DateTimePicker
                                            label="ETD"
                                            onDateChange={this.handleETDChange}
                                            valid={this.isvalidDate.bind(this)}
                                            timeConstraints={this.getTimeConstraints()}
                                            value={this.state.dispatchTime}
                                            placeHolder="Select" 
                                            className="edit-alert-date"                                           
                                        />
                                        </div>
                                    </div>
                                )
                                :''
                        }
                    </div>
                    <div className="edit-ticket-filters">
                        {
                            this.state.EditModalDropDownData.map((input, i) => {
                                let value = (this.state.filterValues && this.state.filterValues[input.label])?this.state.filterValues[input.label]:[];
                                if(input.label === "Select Reason" || input.label === 'Vehicle Status' || input.type === 'calender')
                                    return;
                                return (
                                    <EditAlertSelectInput
                                      key={i}
                                      data = {input.data}
                                      label = {input.label}
                                      value={input.value}
                                      multiLable={input.multiLable}
                                      multiSelect={input.multiSelect}
                                      className="edit-ticket-select"
                                      onValueChange={this.handleSelectValueChange.bind(this)}
                                      disabled={this.state.disableAllFlag || this.state.disableAssignEscalateInform}
                                      />
                                )
                            })
                       
                         }                               
                      {
                            this.state.showConfirmClose ?
                            (<div className="delete-ticket-container">
                              <div className="ticket-basic-data close-trip-label">
                               Are you sure you want to close the trip ?
                            </div>              


                            <div className="edit-footer-close-trip">                               
                                <Button
                                    buttonType="label"
                                    label="No"
                                    className="primaryBtn rf "
                                    disabledBackgroundColor="#ffffff"
                                    disabledLabelColor="rgba(0,0,0,0.4)"
                                    backgroundColor="#ffffff"
                                    labelColor="rgba(0,0,0,0.4)"
                                    style={{width: '70px'}}
                                    onClick={this.cancelSave.bind(this)}
                                    disabled={this.state.saveBtnDisabled}


                                />
                                 <Button
                                    buttonType="label"
                                    label="Yes"
                                    className="primaryBtn rf"
                                    disabledBackgroundColor=" #dd712f"
                                    disabledLabelColor="rgba(1,1,1,0.2)"
                                    backgroundColor="#dd712f"
                                    labelColor="white"
                                    style={{width: '70px'}}
                                    onClick={this.handleOnSave}
                                    disabled={this.state.saveBtnDisabled}
                                />
                            </div>
                            </div>
                               ) 
                                : 
                                  <Button
                            buttonType="label"
                            label={this.state.closeTripFlag ? 'Close Trip' :"SAVE"}
                            className="primaryBtn rf ticket-save-btn"
                            disabledBackgroundColor="rgba(221,113,47,0.2)"
                            disabledLabelColor="rgba(1,1,1,0.2)"
                            backgroundColor="rgba(221,113,47,1)"
                            labelColor="white"
                            style={{width: '150px'}}
                            onClick={this.handleOnSave}
                            disabled={this.state.saveBtnDisabled}
                        />
                            
                        }
                        
                    
                    </div>                  
                    <ChatWidget
                        chatId={(this.state.EditModalBasicData)?this.state.EditModalBasicData.ticketId:''}
                        commentHistory={this.state.commentHistory}
                        documentData={this.state.documentData}
                        loadingCommentHistory={this.state.loadingCommentHistory}
                        uploadingDocument={this.state.uploadingDocument}
                        onAddComment={(ticketId, comment) => this.addComment(ticketId, comment)}
                        onUploadFiles={(event, ticketid) => this.uploadFiles(event, ticketid)}
                        onCommentChange={(comment) => this.handleCommentChange(comment)}
                        extraTabComponents={this.props.selectedTab === 'UNLOADING_VEHICLES' ? this.getExtraTabComponents() : {}}
                    />
                </div>
                </div>
                    {(this.state.showToast)?
                        <Toast
                            toastData={this.state.toastData}
                            onRemove={() => this.handleOnToastRemoval()}
                        />
                        :''
                    }
                </Modal>

        );
    }
}
