import React from 'react';
import Moment from 'react-moment';
import { withNamespaces } from 'react-i18next';
import Complete from '../assets/images/complete.png';
import Delete from '../assets/images/delete.png';
import FileImage from '../assets/images/file.png';
import Upload from '../assets/images/upload.png';
import Img from '../assets/images/document.svg';
import ReactPanZoom from 'react-image-pan-zoom-rotate';
import { createAPIRequest, sendAPI, createAPIRequestFileUpload } from '../services/api/endPoint';
import Config, { Process as process } from '../config/appConstants';
import translateLabel from "../translation";
import "./fileUpload.css"
import { setDocs_Details, store } from "../redux";
import { connect } from 'react-redux';
import loadingImg from '../assets/images/loader.gif';

import Dialog from '@material-ui/core/Dialog';
import MuiDialogTitle from '@material-ui/core/DialogTitle';
import MuiDialogContent from '@material-ui/core/DialogContent';
import MuiDialogActions from '@material-ui/core/DialogActions';
import IconButton from '@material-ui/core/IconButton';
import CloseIcon from '@material-ui/icons/Close';
import FileViewer from 'react-file-viewer';
import { Theme, withStyles, WithStyles, Typography, Button } from '@material-ui/core';
import Swal from 'sweetalert2';
import Utils from '../utils';

const useStyles = theme => ({
  root: {
    flexGrow: 1,
  },
  container: {
    display: 'grid',
    gridTemplateColumns: 'repeat(12, 1fr)',
    gridGap: theme.spacing(3),
  },
  paper: {
    padding: theme.spacing(1),
    textAlign: 'center',
    color: theme.palette.text.secondary,
    whiteSpace: 'nowrap',
    marginBottom: theme.spacing(1),
  },
  card: {
    padding: theme.spacing(1),
    textAlign: 'left',
    color: theme.palette.text.secondary,
    whiteSpace: 'nowrap',
    marginBottom: theme.spacing(1),
  },
  containerCenter: {
    textAlign: 'center',
    justifyContent: 'center'
  },
  backdrop: {
    zIndex: theme.zIndex.drawer + 1,
    color: '#fff',
  },
  btnMinWidth: {
    maxWidth: '10.333333% !important'
  },
  commentBox: {
    width: 570,
    margin: 10,
  },
  divider: {
    margin: theme.spacing(2, 0),
  },
  closeButton: {
    position: 'absolute',
    right: theme.spacing(1),
    top: theme.spacing(1),
    color: theme.palette.grey[500],
  },
  closeButtonAr: {
    position: 'absolute',
    left: theme.spacing(1),
    top: theme.spacing(1),
    color: theme.palette.grey[500],
  }
});

export interface DialogTitleProps extends WithStyles<typeof styles> {
  id: string;
  children: React.ReactNode;
  onClose: () => void;
}

const DialogTitle = withStyles(useStyles)((props: DialogTitleProps) => {
  const { children, classes, onClose, ...other } = props;
  return (
    <MuiDialogTitle disableTypography className={classes.root} {...other}>
      <Typography variant="h6">{children}</Typography>
      {onClose ? (
        <IconButton aria-label="close" className={store.getState().lang.lang === Config.LANG.AR ? classes.closeButtonAr : classes.closeButton} onClick={onClose}>
          <CloseIcon />
        </IconButton>
      ) : null}
    </MuiDialogTitle>
  );
});

const DialogContent = withStyles((theme: Theme) => ({
  root: {
    padding: theme.spacing(2),
    display: 'flex',
    flexDirection: 'column',
    margin: 'auto',
    width: '100%',

  },
}))(MuiDialogContent);

const DialogActions = withStyles((theme: Theme) => ({
  root: {
    margin: 0,
    padding: theme.spacing(1),
  },
}))(MuiDialogActions);

class FileUpload extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isLoad: false,
      isDocs: false,
      allDocument: false,
      tableData: [],
      addTableData: [],
      documentType: [],
      fileNametxt: '',
      count: 0,
      errorFlag: false,
      files: [],
      isImgSource: false,
      uploading: false,
      uploadProgress: {},
      successfullUploaded: false,
      enableAddTable: false,
      responseEmpty: false,
      selectDefault: this.props.i18n.language === Config.LANG.AR ? "أختار نوع الوثيقة" : "Select Document Type",
      isProxyLogin: false,
      btnValidation: false,
      fileExt: "",
      openDialog: false,
      proxyfileDetails: "",
      proxyfileContent: "",
      hideSkipStepBtn :false
    }
    this._isMounted = false;
    this.documentList = {};
    this.loadUploadDoc = false;
    this.uploadFilesLength = 0;
    this.ApplicationCount = 0;
    this.MultipleApplciationData = [];
    this.uploadFilesList = [];
    this.sendRequestCall = this.sendRequestCall.bind(this);
    this.getRowsData = this.getRowsData.bind(this);
    this.AddUploadClick = this.AddUploadClick.bind(this);
    this.deleteUploadClick = this.deleteUploadClick.bind(this);
    this.deleteUploadedFiles = this.deleteUploadedFiles.bind(this);
    this.uploadFiles = this.uploadFiles.bind(this);
    this.handleBackClick = this.handleBackClick.bind(this);
    this.getUploadedDocList = this.getUploadedDocList.bind(this);
    this.navWizard = this.navWizard.bind(this);

    this.uploadFiles_standardDocs =this.uploadFiles_standardDocs.bind(this);
    this.deleteStandardContract = this.deleteStandardContract.bind(this);

    if (this.props.location?.hasOwnProperty("state") && this.props.location.state.hasOwnProperty("eServiceData") && this.props.location.state.eServiceData.isProxyLogin) {
      this.uploadDetails = store.getState().docs_upload_details.hasOwnProperty("proxyDetails") ? store.getState().docs_upload_details.proxyDetails : "";
    } else {
      this.uploadDetails = store.getState().docs_upload_details.hasOwnProperty("fileUploadRequiredDetails") ? store.getState().docs_upload_details.fileUploadRequiredDetails : "";
    }
    if (store.getState().hasOwnProperty("docs_upload_details") && store.getState().docs_upload_details.hasOwnProperty("isDocsUploaded")) {
      this.loadUploadDoc = true;
    }

    this.mimeTypes = {
      pdf: "application/pdf",
      jpeg: "image/jpeg",
      jpg: "image/jpg",
      png: "image/png",
      doc: "application/msword",
      docx: "application/octet-stream;application/vnd.openxmlformats-officedocument.wordprocessingml.document",
      xslx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
    }
  }

 async componentDidMount() {
    this._isMounted = true;
    if (this.loadUploadDoc) {
      // if(store.getState().applicableSubService === "RN06A"){
        this.setState({ hidePrevBtn: true });
      // }
      await this.getDocumentList();
      await this.getUploadedDocList();
      await this.getAddDocumentList();
    } else {
      if ((this.props.hasOwnProperty("eServiceData") && this.props.eServiceData.hasOwnProperty("DocumentsList")) || (this.props.location?.hasOwnProperty("state") && this.props.location.state.hasOwnProperty("eServiceData") && this.props.location.state.eServiceData.isProxyLogin)) {
        let docsList;
        if (this.props.location?.hasOwnProperty("state") && this.props.location.state.hasOwnProperty("eServiceData") && this.props.location.state.eServiceData.isProxyLogin) {
          docsList = this.props.location.state.eServiceData.DocumentsList;
          this.setState({ isProxyLogin: true })
        } else {
          docsList = this.props.eServiceData.DocumentsList;
        }
        let response = Config.RN13_CONTRACT_DOCUMENTS;
        let Uploadlist = [];

        docsList.forEach(function (doctype) {
          response.ApplicableDocDetails.forEach(function (value) {
            if (value.DocumentTypeID === doctype) {
              Uploadlist.push(value);
            } else if (value.DocumentGroupID === doctype) {
              Uploadlist.push(value);
            }
          })
        })
        this.setState({ tableData: [...Uploadlist], isLoad: true });
        this.setState({ count: (this.state.count + this.state.tableData.length) + 1 });
      } else {
        //this condition should be enabled for proxy document attachment after api team confirmation
        if (store.getState().proxyUserDetails.hasOwnProperty("ProxyLoginDetails") && store.getState().proxyUserDetails.ProxyLoginDetails.hasOwnProperty("ProxyID")) {
          this.getProxyUploadedDocList();
        } else {
          this.getDocumentList();
        }
      }
      this.getAddDocumentList();
    }
  }

  async deleteStandardContract(){
    if (store.getState()?.appInfo?.standardContract_doc_info) {
        let response = await sendAPI('PUT', Config.DELETE_DOCUMENTS, store.getState().appInfo.standardContract_doc_info);
        if(response){
          console.log("standard contract deleted successfully");
          this.uploadFiles()
        } else {
          console.log("Delete_error::error");
        }
      }
  }

  async getProxyUploadedDocList() {
    //params will be changing for proxy after confirmation from API Team
    var params = {
      // ApplicationID: this.uploadDetails.ReferenceID,
      // ServiceID: this.uploadDetails.ServiceID,
      // DocumentTypeID: 5,
      // DocumentGroupID: 3,
      ReferenceID: store.getState().proxyUserDetails.ProxyLoginDetails.ProxyNumber
    };
    this.setState({ isDocs: false });
    let response = await createAPIRequest('GET', Config.GET_DOCUMENTS, {}, params);
    if (response) {
      this.documentList = response;
      let AddDocs = this.state.tableData
      const uploadedDoc = this.documentList.DocumentDetails

      for (let index = 0; index < AddDocs.length; index++) {
        const doc = uploadedDoc.find(addDoc => addDoc.DocumentTypeID === AddDocs[index].DocumentTypeID)
        if (doc) {
          AddDocs[index] = {
            ...AddDocs[index], ...doc, ...{
              fileName: doc.DocumentName
            }
          }
        }
      }

      uploadedDoc.forEach((upDoc, index) => {
        this.getProxyDocumentContents(upDoc, AddDocs);
      })
    }
  }

  async getProxyDocumentContents (upDoc, AddDocs) {
    let imgType = ["image/jpeg", "image/png", "image/jpg"];
    let fileExt;
    var fileName = upDoc.DocumentName;
    fileExt = fileName.split(".").pop();
    fileExt = fileExt.toLowerCase();

    var params = {
      DocumentID: upDoc.AlfrescoID
      // ApplicationID: this.uploadDetails.ApplicationID
    }
    let response = await createAPIRequest('GET', Config.GET_DOCUMENT_CONTENT, {}, params);
    if (response) {
      let contentDocument = response;
      if (imgType.includes(this.mimeTypes[fileExt])) { // image source
        let baseUrl = this.mimeTypes[fileExt] + ";base64," + contentDocument.DocumentDetails[0].DocumentContent;
        let fileurl = this.b64toBlob(baseUrl);
        AddDocs.push({
          ...upDoc, ...{
            DocumentTypeAr: upDoc.DocumentTypeAr,
            DocumentTypeEn: upDoc.DocumentTypeEnglish, //"Copy of Passport",
            fileName: upDoc.DocumentName,
            fileUrl: fileurl,
            filecontent: contentDocument.DocumentDetails[0].DocumentContent,
            disableDelete: true
          }
        })
        this.setState({ tableData: AddDocs, isLoad: true });
        this.getDocumentList();
      } else {
        AddDocs.push({
          ...upDoc, ...{
            DocumentTypeAr: upDoc.DocumentTypeAr,
            DocumentTypeEn: upDoc.DocumentTypeEnglish, //"Copy of Passport",
            fileName: upDoc.DocumentName,
            fileUrl: this.mimeTypes[fileExt] + ";base64," + contentDocument.DocumentDetails[0].DocumentContent,
            filecontent: contentDocument.DocumentDetails[0].DocumentContent,
            disableDelete: true
          }
        })
        this.setState({ tableData: AddDocs, isLoad: true });
        this.getDocumentList();
      }
    }
  }

  navWizard() {
    const {tableData} = this.state;
    if (this.loadUploadDoc) {
      console.log("1")
      if (this.props.hasOwnProperty("eServiceData") && this.props.eServiceData.hasOwnProperty("previewJumpStep")) {
        console.log("2")
        for (let i = 0; i < tableData.length; i++) {
          if(tableData[i].isMandatory === 'Y' && (tableData[i].fileName === undefined || tableData[i].fileName === "" || tableData[i].fileName === null)){  
            console.log("3")
            this.setState({ errorFlag: true });
            return;
          }
        }
        this.props.jumpToStep(this.props.eServiceData.previewJumpStep);
      } else if (this.props.hasOwnProperty("eServiceData") && this.props.eServiceData.hasOwnProperty("nextStep")) {
        console.log("4")
        for (let i = 0; i < tableData.length; i++) {
          if(tableData[i].isMandatory === 'Y' && (tableData[i].fileName === undefined || tableData[i].fileName === "" || tableData[i].fileName === null)){  
            console.log("new")
            this.setState({ errorFlag: true });
            return;
          }
        }
        this.props.jumpToStep(this.props.eServiceData.nextStep);
      }
    } else {
      console.log("5")
      if (this.props.hasOwnProperty("eServiceData") && this.props.eServiceData.hasOwnProperty("nextStep")) {
        console.log("6")
        for (let i = 0; i < tableData.length; i++) {
          if(tableData[i].isMandatory === 'Y' && (tableData[i].fileName === undefined || tableData[i].fileName === "" || tableData[i].fileName === null)){  
            console.log("new")
            this.setState({ errorFlag: true });
            return;
          }
        }
        this.props.jumpToStep(this.props.eServiceData.nextStep);
      }
    }
  }

  handleBackClick() {
    if (this.props.hasOwnProperty("eServiceData") && this.props.eServiceData.hasOwnProperty("previousStep")) {
      this.props.jumpToStep(this.props.eServiceData.previousStep);
    } else if (this.state.isProxyLogin) {
      this.props.history.push('/proxy/search-applicant');
    }
  }

  handleCloseDialog() {
    this.setState({ ...this.state, fileExt: "", fileUrl: "", openDialog: false });
  };

  async getUploadedDocList() {
    if (this.props.eServiceData?.uploadMultipleApplication && this.props.eServiceData.uploadMultipleApplication && store.getState().appInfo?.storeApplicationValue) {
      this.setState({ hidePrevBtn: true });
      store.getState().appInfo.storeApplicationValue.forEach(cur => {
        this.getUploadedDocData(cur.ApplicationID)
      });
    } else {
      this.getUploadedDocData(this.uploadDetails.ApplicationID)
    }
  }

  async getUploadedDocData(ApplicationID) {
    let params = {
      ApplicationID: ApplicationID,
      ServiceID: this.uploadDetails.ServiceID,
      DocumentGroupID: 3
    };
    this.setState({ isDocs: false });
    let response = await createAPIRequest('GET', Config.GET_DOCUMENTS, {}, params);
    if (response) {
      if (this.props.eServiceData?.uploadMultipleApplication && this.props.eServiceData.uploadMultipleApplication && store.getState().appInfo?.storeApplicationValue) {
        this.MultipleApplciationData.push(response);
      }
      this.documentList = response;
      let AddDocs = this.state.tableData
      const uploadedDoc = this.documentList.DocumentDetails
      for (let index = 0; index < AddDocs.length; index++) {
        const doc = uploadedDoc.find(addDoc => addDoc.DocumentTypeID === AddDocs[index].DocumentTypeID)
        if (doc) {
          AddDocs[index] = {
            ...AddDocs[index], ...doc, ...{
              fileName: doc.DocumentName,
            }
          }
        }
      }

      uploadedDoc.forEach(upDoc => {
        if (!AddDocs.find(addDoc => addDoc.DocumentTypeID === upDoc.DocumentTypeID)) {
          AddDocs.push({
            ...upDoc, ...{
              DocumentTypeAr: upDoc.DocumentTypeAr,
              DocumentTypeEn: upDoc.DocumentTypeEnglish, //"Copy of Passport",
              fileName: upDoc.DocumentName,
            }
          })
        }
      })

      this.setState({ tableData: AddDocs, isDocs: true });
    } else {
      this.loadUploadDoc = false
      this.getDocumentList()
    }
  }

  async getDocumentList() {
    let params, queryString;
    let IsMortgaged = "N";
    if (this.uploadDetails.hasOwnProperty("ServiceSubID") && this.uploadDetails.ServiceSubID.length > 0) {
      params = this.uploadDetails.ServiceSubID
    } else {
      params = this.props.eServiceData.ServiceSubID
    }

    if (this.uploadDetails.hasOwnProperty("IsMortgaged") && this.uploadDetails.IsMortgaged) {
      IsMortgaged = "Y";
      queryString = "ServiceSubID=" + params + "&IsMortgageMark=" + IsMortgaged;
    } else if (this.uploadDetails.hasOwnProperty("IsProxyUser") && this.uploadDetails.IsProxyUser) {
      IsMortgaged = "Y";
      queryString = "ServiceSubID=" + params + "&IsProxyUser=" + IsMortgaged;
    } else if (store.getState().proxyUserDetails.hasOwnProperty("ProxyLoginDetails")) {
      IsMortgaged = "Y";
      queryString = "ServiceSubID=" + params + "&IsProxyUser=" + IsMortgaged;
    } else {
      queryString = "ServiceSubID=" + params;
    }
    let response = await createAPIRequest("GET", Config.UPLOADDOCUMENTLIST, {}, queryString);
    if (response) {
      if (this.state.tableData.length > 0) {
        let uplddocs = this.state.tableData;
        this.setState({ tableData: [...uplddocs, ...response.ApplicableDocDetails], isLoad: true });
        this.setState({ count: (this.state.count + this.state.tableData.length) + 1 });
      } else {
        this.setState({ tableData: [...response.ApplicableDocDetails], isLoad: true });
        this.setState({ count: (this.state.count + this.state.tableData.length) + 1 });
      }
    } else {
      console.log("get document list :: error");
    }
  }

  async getAddDocumentList() {
    var params = {
      "LookupInput": [
        {
          "LookupType": "DocumentType",
          "KeyFields": [
            {
              "Name": "DOCUMENT_TYPE_ID",
              "Value": "17"
            }
          ]
        }
      ]
    };
    let response = await createAPIRequest("POST", Config.GET_UTILITY_LOOKUP, params);
    if (response) {
      this.setState({ documentType: [...response.LookupDataFields], isLoad: true, allDocument: true });
    } else {
      console.log("lookup::error");
    }
  }
  uploadFiles_standardDocs(){
    if(this.props?.eServiceData && this.props?.eServiceData?.standardContract){
      this.deleteStandardContract();
    } else {
      this.uploadFiles();
    }  
  }

  async uploadFiles() {
    var items = this.state.tableData;
    var addItems = this.state.addTableData;
    if (items.length > 0 || addItems.length > 0) {
      var fileArr = [];
      var fileContent = "";//used to split  data:text/plain;base64, & file content 
      if (!this.loadUploadDoc) {
        for (let i = 0; i < items.length; i++) {
          if (items[i].fileName !== undefined && items[i].fileUrl !== undefined && items[i].fileUrl !== "") {
            fileContent = items[i].fileUrl.split(',')[1];
            fileArr.push({ DocumentTypeID: items[i].DocumentTypeID, fileName: items[i].fileName, filecontent: fileContent });
          }
        }
        for (let i = 0; i < addItems.length; i++) {
          if (addItems[i].fileName !== undefined && addItems[i].fileUrl !== undefined && addItems[i].fileUrl !== "") {
            fileContent = addItems[i].fileUrl.split(',')[1];
            fileArr.push({ DocumentTypeID: addItems[i].documentID, fileName: addItems[i].fileName, filecontent: fileContent });
          }
        }
        for (let j = 0; j < items.length; j++) {
          if (items[j].isMandatory === 'Y' && (items[j].fileName === undefined || items[j].fileName === "" || items[j].fileName === null)) {
            this.setState({ errorFlag: true });
            return;
          }
          this.setState({ errorFlag: false });
        }
      } else if (this.loadUploadDoc) {
        for (let i = 0; i < items.length; i++) {
          if (items[i].hasOwnProperty("fileName") && items[i].hasOwnProperty("fileUrl") && items[i].fileName !== undefined) {
            fileContent = items[i].fileUrl.split(',')[1];
            fileArr.push({ DocumentTypeID: items[i].DocumentTypeID, fileName: items[i].fileName, filecontent: fileContent, ServiceSubID: items[i].ServiceSubID });
          }
        }

        for (let i = 0; i < items.length; i++) {
          if (items[i].isMandatory === 'Y' && (items[i].fileName === undefined || items[i].fileName === "" || items[i].fileName === null)) {
            this.setState({ errorFlag: true });
            return;
          }
        }

        for (let i = 0; i < addItems.length; i++) {
          if (addItems[i].fileName !== undefined) {
            fileContent = addItems[i].fileUrl.split(',')[1];
            fileArr.push({ DocumentTypeID: addItems[i].documentID, fileName: addItems[i].fileName, filecontent: fileContent });
          }
        }

      } else {
        for (let i = 0; i < addItems.length; i++) {
          if (addItems[i].hasOwnProperty("fileName") && addItems[i].hasOwnProperty("documentID") && addItems[i].fileName !== undefined) {
            fileContent = addItems[i].fileUrl.split(',')[1];
            fileArr.push({ DocumentTypeID: addItems[i].documentID, fileName: addItems[i].fileName, filecontent: fileContent, ServiceSubID: addItems[i].ServiceSubID });
          }
        }

        for (let i = 0; i < addItems.length; i++) {
          if (!addItems[i].hasOwnProperty("fileName") && !addItems[i].hasOwnProperty("documentID") && !addItems[i].documentID !== "" && !addItems[i].fileName !== "") {
            this.setState({ errorFlag: true });
            return;
          }
        }
      }

      this.uploadFilesList = fileArr;
      if (fileArr.length > 0) {
        this.setState({ uploadProgress: {}, uploading: true });
        const promises = [];
        const fileData = (file) => {
          if (this.props.eServiceData?.uploadMultipleApplication && this.props.eServiceData.uploadMultipleApplication && store.getState().appInfo?.storeApplicationValue) {
            this.getMultipleApplications(file)
          } else {
            promises.push(this.sendRequestCall(file));
          }
        }
        fileArr.forEach(fileData);
        this.setState({ responseEmpty: true });
        try {
          await Promise.all(promises);
          this.setState({ successfullUploaded: true, uploading: false });
        } catch (e) {
          this.setState({ successfullUploaded: true, uploading: false });
        }
        this.props.setDocs_Details({ ...store.getState().docs_upload_details, isDocsUploaded: true });
      } else {
        this.navWizard();
      }
    } else {
      this.navWizard();
    }
  }

  getMultipleApplications(file) {
    const promises = [];
    store.getState().appInfo.storeApplicationValue.forEach(cur => {
      promises.push(this.sendRequestCall(file, cur.ApplicationID));
    });
  }

  async sendRequestCall(file, ApplicationID) {
    const formData = new FormData();
    let encType = 0;
    var loginData = store.getState().pki_details.hasOwnProperty("OrgUserValidator") ? store.getState().pki_details.OrgUserValidator : store.getState().pki_details;
    var documentGroupID = this.props.hasOwnProperty("eServiceData") && this.props.eServiceData.hasOwnProperty("DocumentGroupID") ? this.props.eServiceData.DocumentGroupID : 3;
    let fileUrl = Config.FILE_UPLOAD;
    var match = fileUrl.match(/:\/\/(www[0-9]?\.)?(.[^/:]+:(\d*))/i);
    if (match[3] === process.env.REACT_APP_ENV_PORT) {
      encType = 1;
      formData.append('filename', btoa(Utils.bwEncryptHeaderAuthKey(file.fileName)));
      formData.append('content', btoa(Utils.bwEncryptHeaderAuthKey(file.filecontent))); // btoa(Utils.bwEncryptHeaderAuthKey(
      formData.append('DocumentTypeID', btoa(Utils.bwEncryptHeaderAuthKey(String(file.DocumentTypeID))));
      if (ApplicationID && this.props.eServiceData?.uploadMultipleApplication && this.props.eServiceData.uploadMultipleApplication) {
        formData.append('ApplicationID', btoa(Utils.bwEncryptHeaderAuthKey(ApplicationID)));
        formData.append('InvolvedPartyUniqueID', btoa(Utils.bwEncryptHeaderAuthKey(loginData.CivilNumber)));
      } else {
        formData.append('ApplicationID', btoa(Utils.bwEncryptHeaderAuthKey(this.uploadDetails.ApplicationID)));
        formData.append('InvolvedPartyUniqueID', btoa(Utils.bwEncryptHeaderAuthKey(this.uploadDetails.InvolvedPartyUniqueID)));
      }
      formData.append('ServiceSubID', btoa(Utils.bwEncryptHeaderAuthKey(this.uploadDetails.ServiceSubID)));
      formData.append('ServiceID', btoa(Utils.bwEncryptHeaderAuthKey(this.uploadDetails.ServiceID)));
      formData.append('DocumentGroupID', btoa(Utils.bwEncryptHeaderAuthKey(String(documentGroupID))));
      if (this.props.ProcessingPartyID !== undefined) {
        formData.append('ReferenceID', btoa(Utils.bwEncryptHeaderAuthKey(this.props.ProcessingPartyID)));
      } else if (this.uploadDetails.ReferenceID !== undefined) {
        formData.append('ReferenceID', btoa(Utils.bwEncryptHeaderAuthKey(this.uploadDetails.ReferenceID)));
      }
      formData.append('CreatedBy', btoa(Utils.bwEncryptHeaderAuthKey(Utils.CreatedUserDetails().CreatedUserID)));
      formData.append('UpdatedBy', btoa(Utils.bwEncryptHeaderAuthKey(Utils.CreatedUserDetails().CreatedUserID)));
      if (this.uploadDetails.hasOwnProperty("DocumentDeleteList")) {
        this.uploadDetails.DocumentDeleteList.forEach(function (docvalue) {
          if (docvalue.DocumentTypeID === file.DocumentTypeID) {
            formData.append('AlfrescoID', btoa(Utils.bwEncryptHeaderAuthKey(docvalue.DocumentID)));
          }
        })
      }
    } else {
      formData.append("filename", file.fileName);
      formData.append("content", file.filecontent);
      formData.append("DocumentTypeID", file.DocumentTypeID);
      if (ApplicationID && this.props.eServiceData?.uploadMultipleApplication && this.props.eServiceData.uploadMultipleApplication) {
        formData.append("ApplicationID", ApplicationID);
        formData.append("InvolvedPartyUniqueID", loginData.CivilNumber);
      } else {
        formData.append("ApplicationID", this.uploadDetails.ApplicationID);
        formData.append("InvolvedPartyUniqueID", this.uploadDetails.InvolvedPartyUniqueID);
      }
      formData.append("ServiceSubID", this.uploadDetails.ServiceSubID);
      formData.append("ServiceID", this.uploadDetails.ServiceID);
      formData.append("DocumentGroupID", documentGroupID);
      if (this.props.ProcessingPartyID !== undefined) {
        formData.append("ReferenceID", this.props.ProcessingPartyID);
      } else if (this.uploadDetails.ReferenceID !== undefined) {
        formData.append('ReferenceID', btoa(Utils.bwEncryptHeaderAuthKey(this.uploadDetails.ReferenceID)));
      }
      formData.append("CreatedBy", Utils.CreatedUserDetails().CreatedUserID);
      formData.append("UpdatedBy", Utils.CreatedUserDetails().CreatedUserID);
      if (this.uploadDetails.hasOwnProperty("DocumentDeleteList")) {
        this.uploadDetails.DocumentDeleteList.forEach(function (docvalue) {
          if (docvalue.DocumentTypeID === file.DocumentTypeID) {
            formData.append("AlfrescoID", docvalue.DocumentID);
          }
        })
      }
    }

    for (var key of formData.entries()) {
      console.log("query", key[0] + ', ' + key[1]);
    }

    var apiPath = Config.FILE_UPLOAD;
    var self = this;
    let response = await createAPIRequestFileUpload('post', apiPath, formData, encType);
    if (response) {
      if (response.hasOwnProperty("DocumentID")) {
        this.uploadFilesLength = this.uploadFilesLength + 1;
        if (ApplicationID && this.props.eServiceData?.uploadMultipleApplication && this.props.eServiceData.uploadMultipleApplication) {
          self.ApplicationCount++;
          if (self.ApplicationCount === store.getState().appInfo.storeApplicationValue.length) {
            self.props.jumpToStep(self.props.eServiceData.nextStep);
          }
        } else if (this.uploadFilesList.length === this.uploadFilesLength) {
          this.sleep(1000).then(() => {
            self.setState({ responseEmpty: false });
            if (self.props.hasOwnProperty("eServiceData")) {
              if (self.loadUploadDoc ) {
                if (self.props.hasOwnProperty("eServiceData") && self.props.eServiceData.hasOwnProperty("previewJumpStep")){
                  self.props.jumpToStep(self.props.eServiceData.previewJumpStep); 
                } else {
                  self.props.jumpToStep(self.props.eServiceData.nextStep);
                } 
              } else {
                self.props.jumpToStep(self.props.eServiceData.nextStep);
              } 
            } else if (store.getState().docs_upload_details.hasOwnProperty("proxyDetails")) {
              Swal.fire({
                title: translateLabel("TITLE_SUCCESS"),
                text: translateLabel("Proxy Registered successfully"),
                icon: "success",
                // confirmButtonColor: '#056ca2',
                confirmButtonText: translateLabel('OK')
              }).then(() => {
                if (this.state.isProxyLogin) {
                  this.props.history.push('/home');
                }
              });
            }
          });
        } else {
          this.setState({ responseEmpty: true });
        }
      }
    } else {
      console.log("file.upload::error");
    }
  }

  sleep(time) {
    return new Promise((resolve) => setTimeout(resolve, time));
  }

  fileListToArray(list) {
    const array = [];
    for (let i = 0; i < list.length; i++) {
      array.push(list.item(i));
    }
    return array;
  }

  onChange (e, idx) {
    const validator = Utils.fileValidator(e.target.files[0])
    if (!validator.status) {
      alert(validator.msg);
    } else {
      let fileName = e.target.files[0].name;
      const rows = [...this.state.tableData];
      const files = e.target.files;
      const array = this.fileListToArray(files);
      this.setState(prevState => ({
        files: prevState.files.concat(array)
      }));

      let reader = new FileReader();
      let file = e.target.files[0];
      this.setState({ fileNametxt: file });
      let hideSkipStep = rows.find((item)=> item.isMandatory === "Y");
      if(hideSkipStep){
        this.setState({hideSkipStepBtn :true});
      }
      reader.onloadend = () => {
        rows[idx] = {
          ...rows[idx],
          fileName: fileName,
          file: file,
          fileUrl: reader.result
        };

        this.setState({
          tableData: [...rows]
        });
      }
      reader.readAsDataURL(file);
    }
  };

  onAddChange (e, idx) {
    const validator = Utils.fileValidator(e.target.files[0])
    if (!validator.status) {
      alert(validator.msg);
    } else {
      var addItems = this.state.addTableData;
      let fileName = e.target.files[0].name;
      const rows = [...this.state.addTableData];
      let reader = new FileReader();
      let file = e.target.files[0];
      this.setState({ fileNametxt: file });
      const files = e.target.files;
      const array = this.fileListToArray(files);
      this.setState(prevState => ({
        files: prevState.files.concat(array)
      }));

      for (let i = 0; i < addItems.length; i++) {
        if (!addItems[i].hasOwnProperty("fileName") && !addItems[i].hasOwnProperty("documentID") && !addItems[i].documentID !== "" && !addItems[i].fileName !== "") {
          this.setState({ errorFlag: true });
          return;
        }
      }

      reader.onloadend = () => {
        rows[idx] = {
          ...rows[idx],
          fileName: fileName,
          file: file,
          fileUrl: reader.result
        };

        this.setState({
          addTableData: [...rows]
        });
      }
      reader.readAsDataURL(file);
      var array1 = this.state.documentType;
      this.setState({ documentType: [...array1] });
    }
  };

  AddUploadClick() {
    var addRow = { "DocumentTypeID": "" };
    this.setState({ addTableData: [...this.state.addTableData, addRow], enableAddTable: true, btnValidation: false });
  }
  
  async cleadUploaded(e, idx) {
    this.setState({ btnValidation: false });
    const rows = [...this.state.tableData];
    if (rows[idx] && rows[idx].AlfrescoID && this.props.eServiceData?.uploadMultipleApplication && this.props.eServiceData.uploadMultipleApplication && store.getState().appInfo?.storeApplicationValue && this.MultipleApplciationData.length > 0) {
      this.MultipleApplciationData.forEach(current => {
        current.DocumentDetails.forEach(cur => {
          if (rows[idx].DocumentTypeID === cur.DocumentTypeID) {
            this.clearUploadClick(e, idx, current.ApplicationID, cur.AlfrescoID);
          }
        });
      });
    } else {
      this.clearUploadClick(e, idx, this.uploadDetails.ApplicationID)
    }
  }
  
  async clearUploadClick(e, idx, ApplicationID, AlfrescoID) {
    this.setState({ btnValidation: false });
    const rows = [...this.state.tableData];
    if (rows[idx] && rows[idx].AlfrescoID) {
      let postData;
      postData = {
        ApplicationID: ApplicationID ? String(ApplicationID) : String(this.uploadDetails?.ApplicationID),
        DocumentTypeID: rows[idx].DocumentTypeID,
        DocumentID: AlfrescoID ? AlfrescoID : rows[idx].AlfrescoID
      };
      let response = await sendAPI('PUT', Config.DELETE_DOCUMENTS, postData, {});
      if (response) {

        this.setState({ btnValidation: false });
        rows[idx] = {
          DocumentTypeAr: rows[idx].DocumentTypeAr,
          DocumentTypeEn: rows[idx].DocumentTypeEn, //"Copy of Passport",
          DocumentTypeID: rows[idx].DocumentTypeID, //"2",
          ServiceSubID: rows[idx].ServiceSubID, //"RN01B",
          isMandatory: rows[idx].isMandatory,//"Y"
          fileName: ''
        };

        this.setState({
          tableData: [...rows]
        });
        this.setState({ fileNametxt: '' });
      } else {
        console.log("axios:Delete_error");
      }
    } else {
      this.setState({ btnValidation: false });
      const rows = [...this.state.tableData];
      rows[idx] = {
        DocumentTypeAr: rows[idx].DocumentTypeAr,
        DocumentTypeEn: rows[idx].DocumentTypeEn, //"Copy of Passport",
        DocumentTypeID: rows[idx].DocumentTypeID, //"2",
        ServiceSubID: rows[idx].ServiceSubID, //"RN01B",
        isMandatory: rows[idx].isMandatory,//"Y"
        fileName: ''
      };

      this.setState({
        tableData: [...rows]
      });
      this.setState({ fileNametxt: '' });
    }
  };

  deleteUploadClick(event, idx) {
    this.setState({ btnValidation: false });
    const rows = [...this.state.addTableData];
    rows.splice(idx, 1);
    this.setState({ addTableData: [...rows] });
  }

  async deleteFiles(event, idx, row) {
    if (this.props.eServiceData?.uploadMultipleApplication && this.props.eServiceData.uploadMultipleApplication && store.getState().appInfo?.storeApplicationValue) {
      store.getState().appInfo.storeApplicationValue.forEach((cur, indx) => {
        this.deleteUploadedFiles(event, idx, row, cur.ApplicationID)
      });
    } else {
      this.deleteUploadedFiles(event, idx, row, this.uploadDetails.ApplicationID)
    }
  }

  async deleteUploadedFiles(event, idx, row, ApplicationID) {
    this.setState({ btnValidation: false });
    if (row) {
      let postData = {
        ApplicationID: String(ApplicationID),
        DocumentTypeID: row.DocumentTypeID,
        DocumentID: row.AlfrescoID
      };
      let response = await sendAPI('PUT', Config.DELETE_DOCUMENTS, postData, {});
      if (response) {
        this.getUploadedDocList();
      } else {
        console.log("axios:Delete_error");
      }
    }
  }

  handleChange(e, idx) {
    this.setState({ btnValidation: false });
    let fileID = e.target.value;
    const rows = [...this.state.addTableData];
    rows[idx] = {
      ...rows[idx],
      documentID: fileID,
    };
    this.setState({
      addTableData: [...rows]
    });
  }

  b64toBlob(dataURI) {
    var byteString = atob(dataURI.split(',')[1]);
    var ab = new ArrayBuffer(byteString.length);
    var ia = new Uint8Array(ab);
    for (var i = 0; i < byteString.length; i++) {
      ia[i] = byteString.charCodeAt(i);
    }
    return URL.createObjectURL(new Blob([ab], { type: 'image/jpeg' }));
  }

  async getDocumentContents(row, isUpload) {
    let fileExt;
    let imgType = ["image/jpeg", "image/png", "image/jpg"];
    if (!isUpload) { // temp prevew
      fileExt = row.file.name.split(".").pop();
      fileExt = fileExt.toLowerCase();
      const fileURL = URL.createObjectURL(row.file);
      if (imgType.includes(row.file.type)) { // image source
        this.setState({ ...this.state, fileExt: fileExt, fileUrl: fileURL, openDialog: true, isImgSource: true });
      } else { // other files
        this.setState({ ...this.state, fileExt: fileExt, fileUrl: row.fileUrl, openDialog: true, isImgSource: false });
      }
    } else {
      var fileName = row.DocumentName;
      fileExt = fileName.split(".").pop();
      fileExt = fileExt.toLowerCase();
      let params;
      if (this.props.eServiceData?.uploadMultipleApplication && this.props.eServiceData.uploadMultipleApplication && store.getState().appInfo?.storeApplicationValue) {
        params = {
          DocumentID: row.AlfrescoID,
          ApplicationID: store.getState().appInfo.storeApplicationValue[0].ApplicationID
        }
      } else {
        params = {
          DocumentID: row.AlfrescoID,
          ApplicationID: this.uploadDetails.ApplicationID
        }
      }

      let response = await createAPIRequest('GET', Config.GET_DOCUMENT_CONTENT, {}, params);
      if (response) {
        let contentDocument = response;
        if (imgType.includes(this.mimeTypes[fileExt])) { // image source
          let baseUrl = this.mimeTypes[fileExt] + ";base64," + contentDocument.DocumentDetails[0].DocumentContent;
          const fileURL = this.b64toBlob(baseUrl);
          this.setState({ ...this.state, fileExt: fileExt, fileUrl: fileURL, openDialog: true, isImgSource: true });
        } else {
          this.setState({ ...this.state, fileExt: fileExt, fileUrl: this.mimeTypes[fileExt] + ";base64," + contentDocument.DocumentDetails[0].DocumentContent, openDialog: true, isImgSource: false });
        }
      } else {
        console.log("axios:get_documents_error");
      }
    }
  }

  getAddRowsData() {
    var items = this.state.addTableData;
    return items.map((row, index) => {
      return <table key={index + 1} className="table">
        <thead>
        </thead>
        <tbody>
          <tr>
          <td style={{width:"50%"}}>
               <div className={this.props.lang === Config.LANG.AR ? "text-right form-group": "text-left form-group"}>
                <img src={Img} alt="doc" style={{ width: "40px" }} className={row.hasOwnProperty("fileName") && row.fileName !== '' ? "show":"hidden"}  />
                <select id="selectBox" className="fileUploadSelectWidth" disabled={row.hasOwnProperty("fileName") && row.fileName !== '' ? true : false} onChange={(e) => this.handleChange(e, index)}>
                  {this.state.selectDefault ? <option className="fileUploadSelectWidth" data-toggle="tooltip" data-container="#tooltip_container">{this.state.selectDefault}</option> : ''}
                  {this.state.documentType.map((doc, index) => <option key={index + 1} value={doc.DocumentTypeID} title={this.props.i18n.language === Config.LANG.AR ? doc.DocumentTypeArabic : doc.DocumentTypeEnglish}>{this.props.i18n.language === Config.LANG.AR ? doc.DocumentTypeArabic : doc.DocumentTypeEnglish}</option>)}
                </select>
                {(this.state.errorFlag === true && (row.fileName === undefined || row.fileName === "" || row.fileName === null)) ? <small className="errorDoc">{translateLabel("PLS_UPLOAD_DOC_TYPE")}</small> : <small></small>}
              </div> 
            </td>
            <td className="td-center addTDupload col3"><label className="image-upload addUploadLable"><img alt="filename" src={row.hasOwnProperty("fileName") && row.fileName !== '' ? Complete : Upload} />
              {row.hasOwnProperty("fileName") && row.fileName !== '' ? '' : <input type="file" accept={Config.DOCUMENT_UPLOAD_FILE_EXTENTION} onChange={(e) => this.onAddChange(e, index)} />}</label></td>
            <td className="col4 td-center"><a href onClick={() => row.hasOwnProperty("fileName") && row.fileName !== '' ? this.previewDocument(row) : ""}><img src={FileImage} alt="preview" /></a></td>
            <td className="addTDupload col5 td-center"><a href><img src={Delete} alt="delete" onClick={(e) => this.deleteUploadClick(e, index)} /></a></td>
            {row.hasOwnProperty("fileName") && row.fileName !== '' ? <td id="Filename" className={this.props.lang === Config.LANG.AR ? "text-right col6" : "text-left col6"}>{row.fileName}</td> : <td></td>}
          </tr>
        </tbody>
      </table>
    })
  }

  getAddRowsDataEdit() {
    var items = this.state.addTableData;
    return items.map((row, index) => {
      return <table key={index + 1} className="table">
        <tbody>
          <tr>
            <td className="col2">
              <div className="form-group">
                <select id="selectBox" className="fileUploadSelectWidth" disabled={row.hasOwnProperty("fileName") && row.fileName !== '' ? true : false} onChange={(e) => this.handleChange(e, index)}>
                  {this.state.selectDefault ? <option className="fileUploadSelectWidth" data-toggle="tooltip" data-container="#tooltip_container">{this.state.selectDefault}</option> : ''}
                  {this.state.documentType.map((doc, index) => <option key={index + 1} value={doc.DocumentTypeID} title={this.props.i18n.language === Config.LANG.AR ? doc.DocumentTypeArabic : doc.DocumentTypeEnglish}>{this.props.i18n.language === Config.LANG.AR ? doc.DocumentTypeArabic : doc.DocumentTypeEnglish}</option>)}
                </select>
                {(this.state.errorFlag === true && (row.fileName === undefined || row.fileName === "" || row.fileName === null)) ? <small className="errorDoc">{translateLabel("PLS_UPLOAD_DOC_TYPE")}</small> : <small></small>}
              </div>
            </td>
            <td className="addTDupload col3 td-center"><label className="image-upload addUploadLable"><img alt="filename" src={row.hasOwnProperty("fileName") && row.fileName !== '' ? Complete : Upload} />
              {row.hasOwnProperty("fileName") && row.fileName !== '' ? '' : <input type="file" accept={Config.DOCUMENT_UPLOAD_FILE_EXTENTION} onChange={(e) => this.onAddChange(e, index)} />}</label></td>
            <td className="col4 td-center"><a href onClick={() => row.hasOwnProperty("fileName") && row.fileName !== '' ? this.previewDocument(row) : ""}><img src={FileImage} alt="preview" /></a></td>
            <td className="addTDDelete col5 td-center"><a href><img src={Delete} alt="delete" onClick={(e) => this.deleteUploadClick(e, index)} /></a></td>
            {row.hasOwnProperty("fileName") && row.fileName !== '' ? <td id="Filename" style={{ paddingLeft: "14px" }} className="col6">{row.fileName}</td> : <td></td>}
          </tr>
        </tbody>
      </table>
    })
  }

  previewDocument(row) {
    let imgType = ["image/jpeg", "image/png", "image/jpg"];
    let imgPanel;

    if (row.file) {
      const fileURL = URL.createObjectURL(row.file);
      if (imgType.includes(row.file.type)) {
        imgPanel = <ReactPanZoom image="https://drscdn.500px.org/photo/105738331/q%3D80_m%3D2000/v2?webp=true&sig=538a4f76f4966c84acb01426bb4a4a5e4a85b72a2c3bd64973d3a369f9653007" alt="document image" />
        let pdfWindow = window.open("", "mypdf", "width=700px,height=600px");
        pdfWindow.document.body.innerHTML = "<div><p>test</p><img src='" + fileURL + "' />" + imgPanel.toString() + "</div>";
      } else {
        window.open(fileURL, "mypdf", "width=700px,height=600px");
      }
    } else {
      alert("Please upload document")
    }
  }

  async getDownloadContents(row, event) {
    let params;
    if (this.props.eServiceData?.uploadMultipleApplication && this.props.eServiceData.uploadMultipleApplication && store.getState().appInfo?.storeApplicationValue) {
      params = {
        DocumentID: row.AlfrescoID,
        ApplicationID: store.getState().appInfo.storeApplicationValue[0].ApplicationID
      }
    } else {
      params = {
        DocumentID: row.AlfrescoID,
        ApplicationID: this.uploadDetails.ApplicationID
      }
    }

    let response = await createAPIRequest('GET', Config.GET_DOCUMENT_CONTENT, {}, params);
    if (response) {
      let contentDocument = response;
      event.preventDefault();
      let pdfWindow = window.open("", "mypdf", "width=700px,height=600px")
      pdfWindow && pdfWindow.document.write(
        "<iframe width='700px' height='600px' src='data:application/pdf;base64, " +
        encodeURI(contentDocument.DocumentDetails[0].DocumentContent) + "'></iframe>"
      )
    } else {
      console.log("axios:dowload_content_error");
    }
  }

  previewDocContent(content, extension) {
    let prePath = "";
    switch (extension) {
      case 'pdf':
        prePath = "application/pdf";
        break;
      case 'png':
        prePath = "image/png";
        break;
      case 'jpg':
      case 'jpeg':
        prePath = "image/jpg";
        break;
      default:
        prePath = "application/pdf";
        break;
    }

    let pdfWindow = window.open("", "mypdfd", "width=700px,height=600px")
    pdfWindow.document.write("<iframe width='100%' height='100%' src='data:" + prePath + ";base64, " + encodeURI(content.DocumentContent) + "'></iframe>")
  }

  getRowsData() {
    var items = this.state.tableData;
    return items.map((row, index) => {
      return <tr key={"row-" + index}>
        <td className={this.props.i18n.language === Config.LANG.AR ? "text-right":"text-left"}><img src={Img} alt="doc" style={{ width: "40px" }} disabled />{this.props.i18n.language === Config.LANG.AR ? row.DocumentTypeAr : row.DocumentTypeEn}{row.isMandatory === "Y" ? <span className="error"> *</span> : ""}{(this.state.errorFlag === true && row.isMandatory === "Y" && (row.fileName === undefined || row.fileName === "" || row.fileName === null)) ? <small className="errorDoc">{translateLabel("PLS_UPLOAD_THE_REQ_DOC")}</small> : <small></small>}</td>
        <td className="td-center"><label className="image-upload uploadLable"><img alt="getfile" src={row.hasOwnProperty("fileName") && row.fileName !== '' ? Complete : Upload} />
          {row.hasOwnProperty("fileName") && row.fileName !== '' ? '' : <input type="file" accept={Config.DOCUMENT_UPLOAD_FILE_EXTENTION} onChange={(e) => this.onChange(e, index)} />}</label></td>
        <td className="td-center"><a href onClick={() => row.hasOwnProperty("fileName") && row.fileName !== '' ? this.getDocumentContents(row, row.AlfrescoID ? true : false) : ""}><img src={FileImage} alt="preview" /></a></td>
        <td className="td-center"><a href><img src={Delete} alt="delete" onClick={(e) => row.hasOwnProperty("disableDelete") && row.disableDelete ? "" : this.clearUploadClick(e, index)} /></a></td>
        {row.hasOwnProperty("fileName") && row.fileName !== "" ? <td style={{width:"20%"}} className={this.props.i18n.language === Config.LANG.AR ? "text-right" : "text-left"} id="Filename">{row.fileName}</td> : <td style={{width:"20%"}}></td>}
      </tr>
    })
  }

  getDocDetailsRowData() {
    if (this.loadUploadDoc) {
      if (this.state.isDocs) {
        var items = this.documentList.DocumentDetails;
        return items.map((row, index) => {
          return <tr key={"row-" + index}>
            <td className={this.props.i18n.language === Config.LANG.AR ? "text-right" : "text-left"}><img src={Img} alt="doc" style={{ width: "40px" }} disabled />{this.props.i18n.language === Config.LANG.AR ? row.DocumentTypeArabic : row.DocumentTypeEnglish}</td>
            <td><Moment format="DD/MM/YYYY HH:mm">{row.CreatedTimeStamp}</Moment></td>
            <td className="table-col-center"><a href onClick={() => this.getDocumentContents(row, true)}><img src={FileImage} alt="preview" /></a></td>
            <td className="table-col-center" style={{ paddingLeft: "20px" }}><a href><img src={Delete} alt="delete" onClick={(e) => this.deleteFiles(e, index, row)} /></a></td>
            {row.hasOwnProperty("DocumentName") && row.DocumentName !== "" ? <td className="uploadTD-Left" id="Filename" style={{ paddingLeft: "28px" }}>{row.DocumentName}</td> : <td></td>}
          </tr>
        })
      }
    }
  }

  render() {
    if([Config.SERVICE_SUB_CODE.RN01A,Config.SERVICE_SUB_CODE.RN01B].includes(this.props.eServiceData.ServiceSubID) && !this._isMounted){
      window.scrollTo(0, 0);
    }
    this.breadCrumbData = [{ TITLE: translateLabel('HOME'), URI: Config.BREADCRUMBS_URI[""] }, { TITLE: translateLabel('Proxy User'), URI: Config.BREADCRUMBS_URI[""] }];

    var imgLoadingDiv = <div>
      <img src={loadingImg} alt="loadimg" />
    </div>;

    return (
      <div>
        <Dialog key="dialog-header" maxWidth="md" fullWidth onClose={() => { this.handleCloseDialog() }} aria-labelledby="max-width-dialog-title" open={this.state.openDialog}>
          <DialogTitle key="dialog-title" id="customized-dialog-title" style={{ display: this.props.i18n.language === Config.LANG.AR ? "flex" : "" }} onClose={() => { this.handleCloseDialog() }}>
            {translateLabel("File Preview")}
          </DialogTitle>
          <DialogContent key="dialog-content">
            <div className="dialog-container" style = {{overflow:'overlay'}}>
              {(() => {
                if (this.state.isImgSource) {
                  return (<ReactPanZoom image={this.state.fileUrl} alt="document image" />)
                } else {
                  return (
                    <FileViewer key="file-viewer"
                      fileType={this.state.fileExt}
                      filePath={"data:" + this.state.fileUrl}
                    />
                  )
                }
              })()}
            </div>
          </DialogContent>
          {/* <DialogActions key="dialog-act" className={ this.props.i18n.language === Config.LANG.AR ? "row-rverse" : "" }>
            <Button key="dialog-close" onClick={() => { this.handleCloseDialog() }} className = "formbtn-primary"
                  variant="formbtn-primary">
              {translateLabel("CLOSE")}
            </Button>
          </DialogActions> */}
        </Dialog>

        <div className="container header-btitle" style={{ display: this.state.isProxyLogin ? "block" : "none" }}>
        </div>
        <div className="container fileuploadDev fileupload-xs">
          <div>
            <h4 className="wizard-form-title" style={{ marginBottom: "-30px", marginTop: "0px" }}>{translateLabel('UPLOAD_DOCUMENT')}</h4>
            <div className="col-12 col-lg-12 col-md-12 col-sm-12 zeroSidePadding">
              <div className="table-responsive-xl table-hover mh-table" style={{ paddingTop: "0px" }}>
                <div>
                  <div className="addbtnDiv text-right">
                    <button className = "formbtn-primary" style={this.props.i18n.language === Config.LANG.AR ? { float: "left" } : { float: "right" }} disabled={this.state.documentType.length === 0} type="button" onClick={() => { this.AddUploadClick() }}><i className="fa fa-plus" aria-hidden="true"></i> {translateLabel('ADD_DOCUMENT')}</button>
                  </div>
                  <table className="table">
                    <thead>
                      <tr>
                        <th scope="col" className={this.props.i18n.language === Config.LANG.AR ? "text-right":"text-left"}>{translateLabel('DOCUMNET_TYPE')}</th>
                        <th scope="col" className="col3 text-center">{translateLabel('UPLOAD')}</th>
                        <th scope="col" className="col4 text-center">{translateLabel('PREVIEW')}</th>
                        <th scope="col" className="col5 text-center">{translateLabel('CLEAR')}</th>
                        <th className={ this.props.i18n.language === Config.LANG.AR ? "text-right":"text-left"}>{translateLabel('FILE_NAME')}</th>
                      </tr>
                    </thead>
                    <tbody>
                      {this.getRowsData()}
                    </tbody>
                  </table>
                  <div>
                    {this.getAddRowsData()}
                  </div>
                </div>
              </div>
            </div>
            <div className="container form-list sample-field"></div>
            <div>
              <div className="container" style={{ marginTop: "65px", marginLeft: "70px" }}>
                <div className='col-12 col-md-12'>
                  <div className="row justify-content-md-center mt-3" style={{ marginBottom: "20px" }}>
                    <div className={this.props.i18n.language === Config.LANG.AR ? "col-5 col-lg-2 textRight" : "col-5 col-lg-1 textLeft"} style={{ display: this.state.hidePrevBtn ? "none" : "block" }}>
                      <button onClick={this.handleBackClick} className = "formbtn-primary">{translateLabel('BUTTON_BACK')}</button>
                    </div>
                    <div className="col-4 col-lg-1 dpflexmargin">
                      <button className = "formbtn-primary" type="button" disabled={this.state.isLoad === false ? true : false} onClick={this.uploadFiles_standardDocs}>{translateLabel('Next')}</button>
                    </div>
                    {(this.props.hasOwnProperty("eServiceData") && this.props.eServiceData.hasOwnProperty("skipStep")) || this.loadUploadDoc ? (
                      <div className={this.state.hideSkipStepBtn === false ? "col-4 col-lg-2 dpflex dpflexmargin" :"hidden"}>
                        <div><button className = "formbtn-primary" type="button" onClick={this.navWizard}> {translateLabel('SKIP_STEP')} </button></div>
                      </div>
                    ) : (" ")
                    }
                  </div>
                </div>
              </div>
              <br />
              <div className="loader-container">
                {this.state.responseEmpty ? (
                  <div>
                    {imgLoadingDiv}
                  </div>
                ) : (
                  <div>

                  </div>
                )}
              </div>
            </div>
            <br />
          </div>
        </div>
      </div>
    );
  }
}

const mapStateToProps = state => ({
  docs_upload_details: state.docs_upload_details
});

const mapDispatchToProps = {
  setDocs_Details
};

export default withNamespaces()(connect(mapStateToProps, mapDispatchToProps)(FileUpload));
