import { Button, Card, Col, DatePicker, Form, FormInstance, Input, InputNumber, Radio, Row, Select, Tag, Typography, Upload, UploadProps } from 'antd'
import React, { useEffect, useState } from 'react';
import { CountryService, CurrencyService, CustomersService, DeliveryTermsService, DestinationService, EndCustomerService, EndCustomersService, HrmsEmpDetService, PaymentTermsService,UnitcodeService, ShippingTermsService, BankDetailsService, NotifyPartyService } from '@gtpl/shared-services/masters';
import { EmployeeService } from '@gtpl/shared-services/attendance';
import { AlertMessages } from '@gtpl/shared-utils/alert-messages';
import { CompanyReq, CountriesDropDownData, CountryDto, CountryRequest, CurrencyDto, CusAddressInfo, CustomerDto, CustomersDropDownData, DeliveryTermsDropDownDto, DestinationDropDownData, DestinationDto, EndCustomerDto, EndCustomerRequest, EndCustomersDropDownData, HrmsEmployeeDetailsDto, NotifyPartyDropDownDto, PaymentTermsDropDownDto, PlantsDropDown, ShippingTermsDropDownDto, ShippingTermsDto } from '@gtpl/shared-models/masters';
import { EmployeeDto, RolesList } from '@gtpl/shared-models/gtpl';
import { UploadOutlined, PlusOutlined, InboxOutlined } from '@ant-design/icons';
import moment from 'moment';
import { CategoriesInput, PortOfEntryInput, ProcessTypeInput,soTypesInput,SoInvoiceDetailsInfo, JobTypes } from '@gtpl/shared-models/sale-management';
import { EmployeeRolesEnum, GlobalStatus, GlobalVariableValues, JobTypeEnum, JobTypesEnum, SoProcessTypesEnum, SoStatusEnum, SoTypesEnum, StatusEnum } from '@gtpl/shared-models/common-models';
import { formatMessage } from '@formatjs/intl';
import {EnquiriesService} from '@gtpl/shared-services/enquiry-management'
import {EnquiryIdreq} from '@gtpl/shared-models/enquiry-management'


const { Option } = Select;
const { TextArea } = Input;

const onSearch = () => {

}

export interface ICustomerDetailsFormProps {
  intialData: SoInvoiceDetailsInfo;
  brandDetails: (brandDetails: any) => void;
  categoryValue:(categoryValue:string)=>void;
  form:FormInstance<any>
  soStatus:string
  uploadFileList:(uploadFiles:any[])=>void
  currency:(currencyName:string)=>void
  uploadedFile:string;
  soProcessType:any;
  soType:any;
  jobType:string;
  isSubContract:string;
  enquiryId : number;
  country :(countryId : number) => void;
}

const CustomerDetailsForm = (props: ICustomerDetailsFormProps) => {
  let portOfEntries = PortOfEntryInput;
  let categories = CategoriesInput;
  let jobTypes = JobTypes;

  let [initialData, setinitialData] = useState(props.intialData);
  const [customersData, setcustomersData] = useState<CustomerDto[]>([]);
  const [factoriesData, setFactoriesData] = useState<PlantsDropDown[]>([]);
  const [processingFactoriesData, setProcessingFactoriesData] = useState<PlantsDropDown[]>([]);

  const [selectedCustomer, setSelectedCustomer] = useState<CustomersDropDownData>(undefined)
  const [endcustomersData, setendcustomersData] = useState<EndCustomerDto[]>([]);
  const [countriesData, setcountriesData] = useState<CountryDto[]>([]);
  const [destinationData, setdestinationData] = useState<DestinationDto[]>([]);
  // const [factoriesData, setFactoriesData] = useState<any[]>([{id:1,value:'Unit1'},{id:2,value:'Unit2'},{id:3,value:'Kakinada'}]);
  const [employeeData, setEmployeeData] = useState<HrmsEmployeeDetailsDto[]>([]);
  const [deliveryTerms, setDeliveryTerms] = useState<DeliveryTermsDropDownDto[]>([]);
  const [shippingTerms, setShippingTerms] = useState<ShippingTermsDropDownDto[]>([]);
  const [paymentTerms, setPaymentTerms] = useState<PaymentTermsDropDownDto[]>([]);
  const [currency, setCurrency] = useState<CurrencyDto[]>([]);
  const [updateDisableField, setUpdateDisableField] = useState<boolean>(false);
  const [isProcessingUnitDisable, setIsProcessingUnitDisable] = useState<boolean>(false);
  const [isManufacturingUnitDisable, setIsManufacturingUnitDisable] = useState<boolean>(false);
  const [customerHidden, setCustomerHidden] = useState<boolean>(false);
  const [subPoDisable, setsubPoDisable] = useState<boolean>(false);
  const [uploadedFileName, setUploadedFileName] = useState<string>('');
  const [soType, setSoType] = useState<string>('');
  const [sotypeDisable, setSotypeDisable] = useState<boolean>(false);
  const [etdValidationState, setEtdValidationState] = useState<boolean>(true);
  const [etaValidationState, setEtaValidationState] = useState<boolean>(true);
  const [saletypeDisable, setSaletypeDisable] = useState<boolean>(false);
  const [customerAddress, setCustomerAddress] = useState<CusAddressInfo[]>(undefined);
  const [endCustomerAddress, setEndCustomerAddress] = useState<CusAddressInfo[]>(undefined);
const [filelist, setFilelist] = useState([]);
const [enqNum,setEnqNum]= useState(null)
  const [enqInfofieldDisable,setEnqInfoFieldDisable] = useState<boolean>(false)
  const [poNumberDisable,setPoNumberDisable] = useState<boolean>(false)
  const [frozenWeightRequired,setFrozenWeightRequired] = useState<boolean>(true)
// let soType

const notifyPartyService = new NotifyPartyService();
const [notifyPartyDropDown, setNotifyPartyDropDown] = useState<NotifyPartyDropDownDto[]>([]);
const [portOfDishargeData, setPortOfDishargeData] = useState<DestinationDto[]>([]);


  const bankDetailsService = new BankDetailsService()
  const[bankDetails,setBankDetails] = useState<any[]>([])
  const [disableByshipmentMode,setDisbaleByShipmentMode] = useState<boolean>(false)
  
const role = JSON.parse(localStorage.getItem('role'));
const user = JSON.parse(localStorage.getItem('username'));
// console.log(user);
useEffect(()=>{
  if(props.enquiryId == undefined){
    if(role === EmployeeRolesEnum.ADMIN || role === EmployeeRolesEnum.HO_SALES_MANAGER || role === EmployeeRolesEnum.SR_SALES_MANAGER || role === EmployeeRolesEnum.ASSISTANT_SALES_MANAGER || role === EmployeeRolesEnum.PLANT_SALES_MANAGER){
      setSoType('MTO');
    form.setFieldsValue({soProcessType:'MTO'});
      setSotypeDisable(false)
    }else{
      setSoType('MTS');
    form.setFieldsValue({soProcessType:'MTS'});
      setSotypeDisable(true)
  }

  }
  getAllMainPlants();
},[role])
// console.log(role)




  const form = props.form;

  const customersService = new CustomersService();
  const currencyService = new CurrencyService();
  const endcustomerservice = new EndCustomersService();
  const countriesservice = new CountryService();
  const destinationservice = new DestinationService();
  // const employeeService = new EmployeeService();HrmsEmpDetService
  const employeeService = new HrmsEmpDetService();
  const deliveryTermsService = new DeliveryTermsService();
  const shippingTermsService = new ShippingTermsService();
  const paymentTermsService = new PaymentTermsService();
  const unitService = new UnitcodeService();

  useEffect(()=>{
    if(!props.intialData && props.enquiryId == undefined){
      hideCustomerDetails(soType)
      setEtaValidationState(false)
    }

  },[customersData,endcustomersData,countriesData,deliveryTerms,paymentTerms,shippingTerms,currency])

  useEffect(()=>{
    if(props.jobType == JobTypesEnum.SUB_JOB){
      // console.log(props.jobType)
      setsubPoDisable(true)
    }
  },[props.jobType])



  useEffect(() => {
    getCustomersData();
    getPlantsData((props.isSubContract == 'YES')?("yes"):"NO");
    getEndCustomersData();
    getAllFinalCountries();
    getSalesPersonsData();
    getAllDeliveryterms();
    // getFinalDestinationData();
    getAllShippingTerms();
    getAllPaymentTerms();
    getCurrencyData();
    getAllNotifyParty()
    getPortofDischargeData()
    if(soType){
      form.setFieldsValue({soProcessType:soType});
      form.setFieldsValue({soType:SoTypesEnum.DISPATCH});
      
      // hideCustomerDetails(soType)
    }
    if(props.enquiryId == undefined){

      form.setFieldsValue({jobType:'Main Job'})
    }
    console.log(props.intialData,'test-proforma-inv-19test-proforma-inv-19test-proforma-inv-19');
    
    if(props.intialData){
      if(props.intialData.poNumber != undefined && props.intialData.poNumber != null && props.intialData.poNumber != '' && props.jobType != 'Clone'){
        setPoNumberDisable(true)
      }else{
        setPoNumberDisable(false)
      }
    setEnqInfoFieldDisable(true)

      // console.log(props.intialData)

      if(props.soType == SoTypesEnum.STOCK){
        setEtdValidationState(false);
        setEtaValidationState(false)
      }else{
        setEtdValidationState(true);
        setEtaValidationState(true)
      }
      if(props.jobType != 'Clone' && props.soStatus != SoStatusEnum.OPEN && props.jobType != JobTypesEnum.SUB_JOB){
        setIsProcessingUnitDisable(true)
      }else{
        setIsProcessingUnitDisable(false)
      }
      if((props.jobType != 'Clone' && props.soStatus != SoStatusEnum.OPEN) || (props.jobType == JobTypesEnum.SUB_JOB) ){
        setIsManufacturingUnitDisable(true)
      }else {
        setIsManufacturingUnitDisable(false)
      }

      // console.log(props.intialData)
      // console.log(props.soType)
      // setCustomerHidden(true);
      if(props.uploadedFile){
        // console.log(props.uploadedFile);
        let fileNameSplit = props.uploadedFile.split('/');
        const fileName = props.uploadedFile.split('/')[2];
        if(!fileName){
           fileNameSplit = props.uploadedFile.split('\\');
        }
        setUploadedFileName(fileNameSplit[2]);
        // console.log(fileName)
        // form.setFieldsValue({fileUpload:props.uploadedFile})  
      }

      if(props.soStatus == SoStatusEnum.IN_PROGRESS){
        setUpdateDisableField(true);
      }
      getAddress(props.intialData.endCustomerId)
      customerOnchange(props.intialData.customerId)
      countryOnchange(props.intialData.country)
      // props.intialData.invoiceDate=moment('2021-03-02').format('YYYY-MM-DD')
      props.intialData.invoiceDate=moment(props.intialData.invoiceDate, 'YYYY-MM-DD');
      if(props.intialData.edaDate){
        props.intialData.edaDate=moment(props.intialData.edaDate, 'YYYY-MM-DD');
      }
      if( props.intialData.edlDate){
        props.intialData.edlDate=moment(props.intialData.actualEdldate, 'YYYY-MM-DD');
      }
      if(props.intialData.proformaInvoiceDate){
        props.intialData.proformaInvoiceDate = moment(props.intialData.proformaInvoiceDate, 'YYYY-MM-DD')
      }
      
      props.form.setFieldsValue(props.intialData)
      form.setFieldsValue({soType:props.soType})
      if(props.jobType == JobTypesEnum.SUB_JOB){
        form.setFieldsValue({jobType:'Sub Job'})
        form.setFieldsValue({processingUnit:undefined})
      }
    }
  }, []);


  //filling enquiry details as default values 
  const enquiryService = new EnquiriesService()
  const [enquiryInfo,setEnquiryInfo] = useState<any[]>([])

  useEffect(() => {
    if(props.enquiryId != undefined){
      getByEnquiryId(props.enquiryId)
    }
  },[props.enquiryId])

  useEffect(()=>{
    if(enquiryInfo.length > 0 && !props.intialData){
      if(enquiryInfo[0].countryId == GlobalVariableValues.countryIdForFrozenWeigth){
        setFrozenWeightRequired(false)
      }
      form.setFieldsValue({
        customerId: enquiryInfo[0].agentId,
        endCustomerId : enquiryInfo[0].buyerId,
        salePersonId : enquiryInfo[0].salePersonId,
        cusAddress: enquiryInfo[0].agentAddress,
        delAddress: enquiryInfo[0].buyerAddress,
        country : enquiryInfo[0].countryId,
        destination: enquiryInfo[0].destinationId,
        edlDate : enquiryInfo[0].etd ? moment(enquiryInfo[0].etd) : undefined,
        edaDate : enquiryInfo[0].eta ? moment(enquiryInfo[0].eta)  : undefined,
        deliveryTerms : enquiryInfo[0].deliveryTermsId,
        payTermId : enquiryInfo[0].paymentTermsId,
        shipmentTerms: enquiryInfo[0].shipmentTermsId,
        processingUnit : enquiryInfo[0].processingUnitId,
        unit : enquiryInfo[0].manufacturingUnitId,
        currency : enquiryInfo[0].currencyId,
        
      })
      getFinalDestinationData(enquiryInfo[0].countryId)
      if(role === EmployeeRolesEnum.ADMIN || role === EmployeeRolesEnum.HO_SALES_MANAGER || role === EmployeeRolesEnum.SR_SALES_MANAGER || role === EmployeeRolesEnum.ASSISTANT_SALES_MANAGER || role === EmployeeRolesEnum.PLANT_SALES_MANAGER){
        setSoType('MTO');
      form.setFieldsValue({soProcessType:'MTO'});
        setSotypeDisable(false)
      }else{
        setSoType('MTS');
      form.setFieldsValue({soProcessType:'MTS'});
        setSotypeDisable(true)
      }
    form.setFieldsValue({jobType:'Main Job'})
    form.setFieldsValue({soType:SoTypesEnum.DISPATCH})
    setEnqInfoFieldDisable(true)
    setEtaValidationState(false)
    const req = new CompanyReq(enquiryInfo[0].manufacturingUnitCompany)
    getBankDetails(req)
    form.setFieldsValue({'destinationChanged':false})
    }
  },[enquiryInfo])


  const getByEnquiryId = (enquiryId) => {
    const req = new EnquiryIdreq(enquiryId)
    enquiryService.getAllEnquiryDetailsById(req).then(res => {
      if(res.status){
        setEnquiryInfo(res.data)
        setEnqNum(res.data[0].enquiryNumber)
        getendCustomerAddress(res.data[0].buyerId)
      }
    })
  }

  

  

  const disabledDate = (current) => {
    // Can not select days before today and today
    return current && current < moment().endOf('day');
  }

  const getAllNotifyParty = () => {
    notifyPartyService.getAllNotifyPartyDropDown().then(res => {
      if (res.status) {
          setNotifyPartyDropDown(res.data);
      } else {
          if (res.intlCode) {
              AlertMessages.getErrorMessage(res.internalMessage);
          } else {
              AlertMessages.getErrorMessage(res.internalMessage);
          }
      }
    })
  }

  const getCustomersData = () => {
    customersService.getAllActiveCustomers().then((res) => {
      if (res.status) {
        setcustomersData(res.data);
        setcustomersData(res.data);
      } else {
        // if (res.intlCode) {
        //   AlertMessages.getErrorMessage(res.internalMessage);
        // } else {
        //   AlertMessages.getErrorMessage(res.internalMessage);
        // }
        setcustomersData([]);
      }
    }).catch((err) => {
      AlertMessages.getErrorMessage(err.message);
      setcustomersData([]);
    });
  }

  const getAllMainPlants = () => {
    unitService.getAllMainPlants().then((res) => {
      if (res.status) {
        // setFactoriesData(res.data);
        setProcessingFactoriesData(res.data);
      } else {
        // if (res.intlCode) {
        //   AlertMessages.getErrorMessage(res.internalMessage);
        // } else {
        //   AlertMessages.getErrorMessage(res.internalMessage);
        // }
        setProcessingFactoriesData([]);
      }
    }).catch((err) => {
      AlertMessages.getErrorMessage(err.message);
      setProcessingFactoriesData([]);
    });
  }
  const getPlantsData = (subContractorStatus:string) => {
    form.setFieldsValue({unit:null});
    setFactoriesData([]);
    if(subContractorStatus === "yes"){
      unitService.getAllSubContractorPlants().then((res) => {
        if (res.status) {
          // setFactoriesData(res.data);
          setFactoriesData(res.data);
        } else {
          // if (res.intlCode) {
          //   AlertMessages.getErrorMessage(res.internalMessage);
          // } else {
          //   AlertMessages.getErrorMessage(res.internalMessage);
          // }
          setFactoriesData([]);
        }
      }).catch((err) => {
        AlertMessages.getErrorMessage(err.message);
        setFactoriesData([]);
      });
    }
    else{
      unitService.getAllManufacturingPlants().then((res) => {
        if (res.status) {
          // setFactoriesData(res.data);
          setFactoriesData(res.data);
          if(props.intialData){
            const manufacturingUntiName = res.data.filter(e => {
              return (e.plantId == props.intialData.unit)
            })
            const req = new CompanyReq(manufacturingUntiName[0].company)
          getBankDetails(req)
          }
        } else {
          // if (res.intlCode) {
          //   AlertMessages.getErrorMessage(res.internalMessage);
          // } else {
          //   AlertMessages.getErrorMessage(res.internalMessage);
          // }
          setFactoriesData([]);
        }
      }).catch((err) => {
        AlertMessages.getErrorMessage(err.message);
        setFactoriesData([]);
      });
    }
  }


  const getCurrencyData = () => {
    currencyService.getAllActiveCurrencys().then((res) => {
      if (res.status) {
        setCurrency(res.data);
        // setCurrency(res.data);
      } else {
        // if (res.intlCode) {
        //   AlertMessages.getErrorMessage(res.internalMessage);
        // } else {
        //   AlertMessages.getErrorMessage(res.internalMessage);
        // }
        setCurrency([]);
      }
    }).catch((err) => {
      AlertMessages.getErrorMessage(err.message);
      setCurrency([]);
    });
  }
  const getEndCustomersData = () => {
    endcustomerservice.getAllActiveEndCustomers().then((res) => {
      if (res.status) {
        setendcustomersData(res.data);
      } else {
        // if (res.intlCode) {
        //   AlertMessages.getErrorMessage(res.internalMessage);
        // } else {
        //   AlertMessages.getErrorMessage(res.internalMessage);
        // }
        setendcustomersData([]);
      }
    }).catch((err) => {
      AlertMessages.getErrorMessage(err.message);
      setendcustomersData([]);
    });
  }
  const getAllFinalCountries = () => {
    countriesservice.getAllActiveCountries().then((res) => {
      if (res.status) {
        setcountriesData(res.data);
      } else {
        // if (res.intlCode) {
        //   AlertMessages.getErrorMessage(res.internalMessage);
        // } else {
        //   AlertMessages.getErrorMessage(res.internalMessage);
        // }
        setcountriesData([]);
      }
    }).catch((err) => {
      AlertMessages.getErrorMessage(err.message);
      setcountriesData([]);
    });
  }
  const getSalesPersonsData = () => {
    employeeService.getAllActiveEmployees().then((res) => {
      if (res.status) {
        setEmployeeData(res.data);
      } else {
        // if (res.intlCode) {
        //   AlertMessages.getErrorMessage(res.internalMessage);
        // } else {
        //   AlertMessages.getErrorMessage(res.internalMessage);
        // }
        setEmployeeData([]);
      }
    }).catch((err) => {
      AlertMessages.getErrorMessage(err.message);
      setEmployeeData([]);
    });
  }

  const getPortofDischargeData = () => {
    // destinationservice.getDestinationsByCountry(new CountryRequest(selectedCountry)).then((res) => {
    destinationservice.getAllActiveDestination().then((res) => {
        if (res.status) {
            setPortOfDishargeData(res.data);
        } else {
            // if (res.intlCode) {
            //   AlertMessages.getErrorMessage(res.internalMessage);
            // } else {
            //   AlertMessages.getErrorMessage(res.internalMessage);
            // }
            setPortOfDishargeData([]);
        }
    }).catch((err) => {
        AlertMessages.getErrorMessage(err.message);
        setPortOfDishargeData([]);
    });
  }


  const getFinalDestinationData = (selectedCountry) => {
    destinationservice.getDestinationsByCountry(new CountryRequest(selectedCountry)).then((res) => {
      if (res.status) {
        setdestinationData(res.data);
      } else {
        // if (res.intlCode) {
        //   AlertMessages.getErrorMessage(res.internalMessage);
        // } else {
        //   AlertMessages.getErrorMessage(res.internalMessage);
        // }
        setdestinationData([]);
      }
    }).catch((err) => {
      AlertMessages.getErrorMessage(err.message);
      setdestinationData([]);
    });
  }
  const getAllDeliveryterms = () => {
    deliveryTermsService.getAllDeliveryTermsDropDown().then((res) => {
      if (res.status) {
        setDeliveryTerms(res.data);
      } else {
        // if (res.intlCode) {
        //   AlertMessages.getErrorMessage(res.internalMessage);
        // } else {
        //   AlertMessages.getErrorMessage(res.internalMessage);
        // }
        setDeliveryTerms([]);
      }
    }).catch((err) => {
      AlertMessages.getErrorMessage(err.message);
      setDeliveryTerms([]);
    });
  }

  
  const getAllShippingTerms = () => {
    shippingTermsService.getAllShippingTermsDropDown().then((res) => {
      if (res.status) {
        setShippingTerms(res.data);
      } else {
        // if (res.intlCode) {
        //   AlertMessages.getErrorMessage(res.internalMessage);
        // } else {
        //   AlertMessages.getErrorMessage(res.internalMessage);
        // }
        setShippingTerms([]);
      }
    }).catch((err) => {
      AlertMessages.getErrorMessage(err.message);
      setShippingTerms([]);
    });
  }
  const getAllPaymentTerms = () => {
    paymentTermsService.getAllpaymentTermsDropDown().then((res) => {
      if (res.status) {
        setPaymentTerms(res.data);
      } else {
        // if (res.intlCode) {
        //   AlertMessages.getErrorMessage(res.internalMessage);
        // } else {
        //   AlertMessages.getErrorMessage(res.internalMessage);
        // }
        setPaymentTerms([]);
      }
    }).catch((err) => {
      AlertMessages.getErrorMessage(err.message);
      setPaymentTerms([]);
    });
  }

  // const customerOnchange = (selectedValue: string) => {
  //   const selectedCustomerData = customersData.find((cutomer) => cutomer.customerId == Number(selectedValue));
  //   setSelectedCustomer(selectedCustomerData);
  // }

  const clearCustomerDependentData = () => {
    form.setFieldsValue({ cusAddress: '' });
  }

  const endcustomerOnchange = (selectedValue: string) => {
    const selectedendCustomerData = endcustomersData.find((endcutomer) => endcutomer.endCustomerId == Number(selectedValue));
    form.setFieldsValue({ delAddress: selectedendCustomerData.endCustomerId });
  }
  const clearEndCustomerDependentData = () => {
    form.setFieldsValue({ delAddress: '' });
  }

  const countryOnchange = (selectedValue) => {
    props.country(selectedValue)
    getFinalDestinationData(selectedValue)
    if(selectedValue == GlobalVariableValues.countryIdForFrozenWeigth){
      setFrozenWeightRequired(false)
    }else{
      setFrozenWeightRequired(true)
    }
    

  }
  const destinationOnchange = (selectedValue: string) => {
    if(enquiryInfo.length > 0 ){
      if(selectedValue == enquiryInfo[0].destinationId){
        form.setFieldsValue({'destinationChanged':false})
      }else{
        form.setFieldsValue({'destinationChanged':true})
      }
    }
  }

  // const formProps = {
  //   initialValues: initialData.saleOrderId ? initialData : undefined
  // }

  // const customerOnchange=(value) =>{
  //   console.log(value.format('YYYY-MM'));
  //   setSelectedMonth(value.format('YYYY-MM'))
  // }
  const customerOnchange = (value) => {
    setCustomerAddress(undefined);
    getCustomerAddress(value);
  }

  const getAddress = (value) => {
    setEndCustomerAddress(undefined);
    getendCustomerAddress(value);
    getCountryAgainstEndCustomer(value)
  }

  const getCountryAgainstEndCustomer = (value) => {
    const req = new EndCustomerRequest(value,null)
    endcustomerservice.getCountryByEndCustomerId(req).then(res => {
      if(res.status){
        if(props.intialData == undefined){
          form.setFieldsValue({country:res.data[0].countryId})
          countryOnchange(res.data[0].countryId)
        }
      }
    })
  }

  const saveCategory = (val,row) => {
    props.categoryValue(val)
    // console.log(row)
  }

  const getendCustomerAddress = (value) => {
    endcustomerservice.getEndCustomerDataById({endCustomerId:value,isActive:true}).then((res) => {
      if (res.status) {
        setEndCustomerAddress(res.data.addressInfo);
        res.data.brandsInfo.push({'masterBrandId':38,'brandId':43,'brandName':'N/A'})
        props.brandDetails(res.data.brandsInfo);
      } else {
        // if (res.intlCode) {
        //   AlertMessages.getErrorMessage(res.internalMessage);
        // } else {
        //   AlertMessages.getErrorMessage(res.internalMessage);
        // }
        setEndCustomerAddress(undefined);
      }
    }).catch((err) => {
      AlertMessages.getErrorMessage(err.message);
      setEndCustomerAddress(undefined);
    });
  }

  const getCustomerAddress = (value) => {
    customersService.getCustomerDataById({custId:value}).then((res) => {
      if (res.status) {
        setCustomerAddress(res.data.cusAddressInfo);
      } else {
        // if (res.intlCode) {
        //   AlertMessages.getErrorMessage(res.internalMessage);
        // } else {
        //   AlertMessages.getErrorMessage(res.internalMessage);
        // }
        setCustomerAddress(undefined);
      }
    }).catch((err) => {
      AlertMessages.getErrorMessage(err.message);
      setCustomerAddress(undefined);
    });
  }

  const uploadFieldProps: UploadProps = {
    multiple: false,
    onRemove: file => {
      setFilelist([]);
      props.uploadFileList([])

    },
    beforeUpload: (file: any) => {
      if (!file.name.match(/\.(csv|xlsx|xls|pdf|zip)$/)) {
        AlertMessages.getErrorMessage("Only xlsx,csv,xls,pdf files are allowed!");
        return true;
      }
      var reader = new FileReader();
      reader.readAsArrayBuffer(file);
      reader.onload = data => {
        if (filelist.length == 1) {
          AlertMessages.getErrorMessage("You Cannot Upload More Than One File At A Time");
          return true;
        } else {
          setFilelist([...filelist, file]);
          props.uploadFileList([...filelist, file])
          return false;
        }
      }
    },
    progress: {
      strokeColor: {
        '0%': '#108ee9',
        '100%': '#87d068',
      },
      strokeWidth: 3,
      format: percent => `${parseFloat(percent.toFixed(2))}%`,
    },
    fileList: filelist
  };

  const storeCurrency = (val,rowData) => {
props.currency(val)
  }

  const hideCustomerDetails =  async (val) => {
    if(customersData.length > 0 && endcustomersData.length > 0 && countriesData.length > 0 && deliveryTerms.length > 0 && paymentTerms.length > 0 && shippingTerms.length > 0 && currency.length > 0){

      if(val == SoProcessTypesEnum.MTO || val == SoProcessTypesEnum.SAMPLES){
        // alert('MTO');
        setCustomerHidden(false)
        form.resetFields();
        form.setFieldsValue({soProcessType:val})
        form.setFieldsValue({soType:SoTypesEnum.DISPATCH})
        setSaletypeDisable(false)
  
      }else{
        // alert('MTS');
        form.setFieldsValue({soType:SoTypesEnum.STOCK})
        setCustomerHidden(true)
        setSaletypeDisable(true)
        await getFinalDestinationData(4)
        // console.log(destinationData)
  
        const customerNA = customersData.find(item => item.clientName == 'BMR');
        // await getCustomerAddress(customerNA.custId);
        // console.log(customerAddress);
        // form.setFieldsValue({customerId:customerNA.custId});
  
        const endcustomerNA = endcustomersData.find(item => item.endCustomerName == 'BMR');
        // console.log(endcustomerNA);
        await getendCustomerAddress(endcustomerNA.endCustomerId)
  
        // form.setFieldsValue({endCustomerId:endcustomerNA.endCustomerId});
  
        // const invDateNA = '2021-02-01';
        const cusPONA = 'N/A';
        const buyerPONA = 'N/A';
        const countryNA = countriesData.find(item => item.countryName == 'INDIA');
        const delTermsNA = deliveryTerms.find(item => item.deliveryTermsName == 'N/A');
        const payTermsNA = paymentTerms.find(item => item.paymentTermsName == 'N/A');
        const shipTermaNA = shippingTerms.find(item => item.shipmenttermName == 'N/A');
        const currencyNA = currency.find(item => item.currencyName == 'INR');
        form.setFieldsValue({customerId:customerNA.custId});
        form.setFieldsValue({edlDate:moment()});
        form.setFieldsValue({edaDate:moment().add(15, "days")});
        form.setFieldsValue({endCustomerId:endcustomerNA.endCustomerId});
        form.setFieldsValue({poNumber:cusPONA});
        form.setFieldsValue({buyerPoNumber:buyerPONA});
        form.setFieldsValue({cusAddress:'ISKAPALLI VILLAGE,ALLUR MANDAL,PSR NELLORE DISTRIC,524324'});
        form.setFieldsValue({delAddress:'ISKAPALLI VILLAGE,ALLUR MANDAL,PSR NELLORE DISTRIC,524324'});
        form.setFieldsValue({buyerAddress:'ISKAPALLI VILLAGE,ALLUR MANDAL,PSR NELLORE DISTRIC,524324'});
        form.setFieldsValue({country:countryNA.countryId});
        form.setFieldsValue({destination:GlobalVariableValues.destinationId});
        form.setFieldsValue({deliveryTerms:delTermsNA.deliveryTermsId});
        form.setFieldsValue({payTermId:payTermsNA.paymentTermsId});
        form.setFieldsValue({shipmentTerms:shipTermaNA.shiptermId});
        form.setFieldsValue({currency:currencyNA.currencyId});
        // console.log(form.getFieldsValue())
        setCustomerHidden(true)
  
      }
    }
  }

  const handleSubContractor = (val) => {

    // console.log(val);
    getPlantsData(val);
  }
  const soTypeOnChange =(val) => {
    // console.log(val);
    if(val == SoTypesEnum.DISPATCH){
      setEtdValidationState(true);
      setEtaValidationState(true)
    }else{
      setEtdValidationState(false);
      setEtaValidationState(false)
    }

  }
  
  const onPoNumberChange = (e) => {
    form.setFieldsValue({buyerPoNumber:e.target.value})
  }
  const onManufacturingUnitChange = (e,option) => {
    const req = new CompanyReq(option?.company)
    getBankDetails(req)
  }

  const getBankDetails = (req) => {
    bankDetailsService.getBankDetailsByCompany(req).then(res=>{
      if(res.status){
        setBankDetails(res.data)
      }
    })
  }

  const onShipmentModeChange = (e) => {
    if(e.target.value == 'single'){
      setDisbaleByShipmentMode(false)
    }else{
      setDisbaleByShipmentMode(true)
    }
  }
  return (
    <>
    <Card title={<span style={{ color: 'white' }}>Customer Details</span>} style={{ textAlign: 'center' }} headStyle={{ backgroundColor: '#69c0ff', border: 0 }}
    extra={
      <Tag
        icon={<InboxOutlined />}
        style={{
          backgroundColor: '#cceeff', 
          color: '#005580',     
          fontSize: '16px',
          padding: '6px 12px',
          borderRadius: '6px'
        }}
      >
        {enqNum}
      </Tag>
    }
    >
      <Form layout={"vertical"} form={form} autoComplete="off" >
      <Row gutter={24} >
{/* {console.log(localStorage.getItem('role'))} */}
    <Form.Item name='destinationChanged' hidden>
      <Input/>
    </Form.Item>
      <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 4 }} lg={{ span: 4 }} xl={{ span: 5 }}>
        <Form.Item label='Shipment Mode' name='shipmentMode' rules={[{required:true,message:'Shipment Mode is mandatory'}]} initialValue={props.jobType == 'Clone' ? 'multiple' : 'single'}>
          <Radio.Group defaultValue={props.jobType == 'Clone' ? 'multiple' : 'single'} disabled={props.jobType == 'Clone' ? false : true} onChange={onShipmentModeChange}>
            <Radio key='single' value='single'>Single</Radio>
            <Radio key='multiple' value='multiple'>Multiple</Radio>
          </Radio.Group>
        </Form.Item>
        </Col>
          <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 5, offset: 1}} lg={{ span: 5, offset: 1 }} xl={{ span: 5, offset: 1 }}>
            <Form.Item name="soProcessType" label="SO Process Type" rules={[{ required: true, message: 'Missing SO Process Type' }]}>
            <Select
                placeholder="Select SO Process Type"
                allowClear
                disabled={disableByshipmentMode ? true : props.jobType==JobTypesEnum.MAIN_JOB ? sotypeDisable : subPoDisable}
                onChange={hideCustomerDetails}

              >
                {ProcessTypeInput.map(dropData => {
                  return <Option value={dropData.value}>{dropData.name}</Option>
                })}
              </Select>
            </Form.Item>
          </Col>
          <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 5, offset: 1 }} lg={{ span: 5, offset: 1 }} xl={{ span: 5, offset: 1 }}>
            <Form.Item name="soType" label="SO Type" rules={[{ required: true, message: 'Missing SO Type' }]}>
            <Select
                placeholder="Select SO Type"
                allowClear
                disabled={disableByshipmentMode ? true : props.jobType==JobTypesEnum.MAIN_JOB ? saletypeDisable:subPoDisable}
                onChange={soTypeOnChange}

              >
                {soTypesInput.map(dropData => {
                  return <Option value={dropData.value}>{dropData.name}</Option>
                })}
              </Select>
            </Form.Item>
          </Col>
          <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 5, offset: 1 }} lg={{ span: 5, offset: 1 }} xl={{ span: 5, offset: 1 }}>
            <Form.Item initialValue={"Main Job"} name="jobType" label="Job Type" rules={[{ required: true, message: 'Missing Job Type' }]}>
            <Select
                showSearch
                defaultValue={props.jobType==JobTypesEnum.MAIN_JOB ?"Main Job":"Sub Job"}
                optionFilterProp="children"
                filterOption={(input, option) => option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                placeholder="Select Job Type"
                allowClear
                disabled
                // onChange={saveCategory}
                // disabled={updateDisableField}
              >
                {jobTypes.map(jobTypedropData => {
                  return <Option value={jobTypedropData.value}>{jobTypedropData.name}</Option>
                })}
              </Select>
            </Form.Item>
          </Col>
          
          </Row>
          {/* {console.log(soType)} */}
        <Row>
        <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 5 }} lg={{ span: 5 }} xl={{ span: 5 }}>
            <Form.Item initialValue={'NO'} name="isSubContract" label="Is Sub Contract" rules={[{ required: true, message: 'Missing sub contract' }]}>
            <Select
                placeholder="Select"
                allowClear
                disabled={disableByshipmentMode ? true : subPoDisable}
                onChange={handleSubContractor}
            >
                <Option value="yes">YES</Option>
                <Option value="no">NO</Option>

            </Select>
            </Form.Item>
          </Col>
          <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 5, offset: 1 }} lg={{ span: 5, offset: 1 }} xl={{ span: 5, offset: 1 }}>
            <Form.Item name="customerId" label="Customer" >
              <Select
                showSearch
                placeholder="Select customer"
                optionFilterProp="children"
                filterOption={(input, option) => option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                onChange={customerOnchange}
                onClear={clearCustomerDependentData}
                onSearch={onSearch}
                dropdownMatchSelectWidth={false}
                allowClear
                disabled = {disableByshipmentMode ? true :  props.jobType==JobTypesEnum.MAIN_JOB ? customerHidden:subPoDisable}
              >
                {customersData.map(dropData => {
                  return <Option value={dropData.custId}>{dropData.clientName}</Option>
                })}
              </Select>
            </Form.Item>
          </Col>


          <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 5, offset: 1 }} lg={{ span: 5, offset: 1 }} xl={{ span: 5, offset: 1 }}>
            <Form.Item name="endCustomerId"  label="Buyer Name" rules={[{ required: true, message: 'Missing end customer name' }]}>
              <Select
                showSearch
                optionFilterProp="children"
                filterOption={(input, option) => option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                placeholder="Select end customer"
                onChange={getAddress}
                onClear={clearEndCustomerDependentData}
                allowClear
                dropdownMatchSelectWidth={false}
                disabled = {disableByshipmentMode ? true :  props.jobType==JobTypesEnum.MAIN_JOB ? customerHidden:subPoDisable}
              >
                {/* temperory */}
                 {/* {endCustomers.map(dropData => {
                  return <Option value={dropData.value}>{dropData.name}</Option>
                })} */}
                {endcustomersData.map(dropData => {
                  return <Option value={dropData.endCustomerId}>{dropData.endCustomerName}</Option>
                })}
              </Select>
            </Form.Item>
          </Col>

          <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 5, offset: 1 }} lg={{ span: 5, offset: 1 }} xl={{ span: 5, offset: 1 }}>
            <Form.Item name="salePersonId"  label="Sale Person Name" rules={[{ required: true,message: 'Missing sale person' }]}>
              <Select
              showSearch
              optionFilterProp="children"
              filterOption={(input, option) => option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                placeholder="Select sale person"
                allowClear
                disabled={disableByshipmentMode ? true : subPoDisable}
              >
                {employeeData.map(dropData => {
                  return <Option value={dropData.employeeId}>{`${dropData.employeeName}`}</Option>
                })}
              </Select>
            </Form.Item>
          </Col>

         
        </Row>

        <Row>
        <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 5 }} lg={{ span: 5 }} xl={{ span: 5 }}>
            <Form.Item name="invoiceDate"  label="PO Date" rules={[{ required: true,message: 'Missing Invoice date' }]} initialValue={moment()}>
              <DatePicker disabled={disableByshipmentMode ? true : subPoDisable} onChange={() => { }}  style={{ width: '100%' }} />
            </Form.Item>
          </Col>
          <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 5, offset: 1 }} lg={{ span: 5, offset: 1 }} xl={{ span: 5, offset: 1 }}>
            <Form.Item name="poNumber"  label="Buyer PO" >
              <Input disabled = {disableByshipmentMode ? true : props.intialData ? poNumberDisable : props.jobType==JobTypesEnum.MAIN_JOB ? customerHidden:subPoDisable} onChange={onPoNumberChange}/>
            </Form.Item>
          </Col>

          <Col>
          <Form.Item name="buyerPoNumber"  label="Customer PO" style={{display:'none'}}>
              <Input disabled = {disableByshipmentMode ? true : props.jobType==JobTypesEnum.MAIN_JOB ? customerHidden : subPoDisable} hidden/>
            </Form.Item>
            
          </Col>
          <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 5, offset: 1 }} lg={{ span: 5, offset: 1 }} xl={{ span: 5, offset: 1 }}>
            <Form.Item name="proformaInvoiceDate"  label="Invoice Date" 
            // rules={[{ required: true,message: 'Missing Invoice date' }]} 
            initialValue={moment()}
            >
              <DatePicker   style={{ width: '100%' }} />
            </Form.Item>
          </Col>
          <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 5, offset: 1 }} lg={{ span: 5, offset: 1 }} xl={{ span: 5, offset: 1 }}>
          <Form.Item name="cusAddress"  label="Customer Address">
              <Select
              showSearch
              optionFilterProp="children"
              filterOption={(input, option) => option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                placeholder="Select customer address"
                // onChange={customerOnchange}
                // onClear={clearCustomerDependentData}
                allowClear
                dropdownMatchSelectWidth={false}
                disabled = {disableByshipmentMode ? true : props.jobType==JobTypesEnum.MAIN_JOB ? customerHidden : subPoDisable}

              >
                {customerAddress===undefined?'': customerAddress.map(dropData => {
                  return <Option value={dropData.addLineOne+ ',' + dropData.addLineTwo+ ',' +dropData.addLineThree+ ',' +dropData.addLineFour}>{dropData.addLineOne+ ',' + dropData.addLineTwo+ ',' +dropData.addLineThree+ ',' +dropData.addLineFour}</Option>
                })}
              </Select>
            </Form.Item>
            
          </Col>


     
        </Row>

        <Row>
        <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 5 }} lg={{ span: 5 }} xl={{ span: 5 }}>
        <Form.Item name="delAddress"  label="Delivery Address" rules={[{ required: true,message: 'Missing Delivery address' }]}>
            <Select
              showSearch
              optionFilterProp="children"
              filterOption={(input, option) => option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                placeholder="Select end customer address"
                // onChange={customerOnchange}
                // onClear={clearCustomerDependentData}
                dropdownMatchSelectWidth={false}
                allowClear
                disabled = {disableByshipmentMode ? true : props.jobType==JobTypesEnum.MAIN_JOB ? customerHidden : subPoDisable}
              >
                {endCustomerAddress===undefined?'': endCustomerAddress.map(dropData => {
                  return <Option value={dropData.addLineOne+ ',' + dropData.addLineTwo+ ',' +dropData.addLineThree+ ',' +dropData.addLineFour}>{dropData.addLineOne+ ',' + dropData.addLineTwo+ ',' +dropData.addLineThree+ ',' +dropData.addLineFour}</Option>
                })}
              </Select>
              {/* <Input /> */}
            </Form.Item>
          
            
          </Col>
          <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 5, offset: 1 }} lg={{ span: 5, offset: 1 }} xl={{ span: 5, offset: 1 }}>

          <Form.Item name="buyerAddress"  label="Buyer Address" rules={[{ required: true,message: 'Missing Buyer address' }]}>
            <Select
              showSearch
              optionFilterProp="children"
              filterOption={(input, option) => option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                placeholder="Select buyer address"
                // onChange={customerOnchange}
                // onClear={clearCustomerDependentData}
                dropdownMatchSelectWidth={false}
                allowClear
                disabled = {disableByshipmentMode ? true : props.jobType==JobTypesEnum.MAIN_JOB ? customerHidden : subPoDisable}
              >
                {endCustomerAddress===undefined?'': endCustomerAddress.map(dropData => {
                  return <Option value={dropData.addLineOne+ ',' + dropData.addLineTwo+ ',' +dropData.addLineThree+ ',' +dropData.addLineFour}>{dropData.addLineOne+ ',' + dropData.addLineTwo+ ',' +dropData.addLineThree+ ',' +dropData.addLineFour}</Option>
                })}
              </Select>
              {/* <Input /> */}
            </Form.Item>
          
            
          </Col>
        <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 5, offset: 1 }} lg={{ span: 5, offset: 1 }} xl={{ span: 5, offset: 1 }}>

          <Form.Item name="portOfEntry"  label="Port of Loading" rules={[{ required: true,message: 'Missing port of entry ' }]}>
              <Select
                showSearch
                optionFilterProp="children"
                filterOption={(input, option) => option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                placeholder="Select Port"
                // onChange={destinationOnchange}
                allowClear
                disabled={subPoDisable}
                dropdownMatchSelectWidth={false}
              >
                {portOfEntries.map(dropData => {
                  return <Option value={dropData.value}>{dropData.name}</Option>
                })}
              </Select>
            </Form.Item>
          
          </Col>
          <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 5, offset: 1 }} lg={{ span: 5, offset: 1 }} xl={{ span: 5, offset: 1 }}>
          <Form.Item name="country" label="Final Country" rules={[{ required: true,message: 'Missing country' }]}>
              <Select
                showSearch
                optionFilterProp="children"
                filterOption={(input, option) => option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                placeholder="Select Country"
                onChange={countryOnchange}
                allowClear
                disabled = {props.enquiryId > 0 && !props.intialData ? enqInfofieldDisable : props.jobType==JobTypesEnum.MAIN_JOB ? customerHidden : subPoDisable}
              >
                {countriesData.map(dropData => {
                  return <Option value={dropData.countryId}>{dropData.countryName}</Option>
                })}
              </Select>
            </Form.Item>
          
          </Col>



     
        </Row>

        <Row>
        <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 5 }} lg={{ span: 5 }} xl={{ span: 5 }}>
        <Form.Item name="destination"  label="Final Destination" rules={[{ required: true,message: 'Missing destination' }]}>
              <Select
                showSearch
                optionFilterProp="children"
                filterOption={(input, option) => option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                placeholder="Select Destination"
                onChange={destinationOnchange}
                allowClear
                dropdownMatchSelectWidth={false}
                disabled = { props.jobType==JobTypesEnum.MAIN_JOB ? customerHidden : subPoDisable}
              >
                {destinationData.map(dropData => {
                  return <Option value={dropData.destinationId}>{dropData.destinationName}</Option>
                })}
              </Select>
            </Form.Item>
            
          </Col>
            <Col  xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 5, offset: 1 }} lg={{ span: 5, offset: 1 }} xl={{ span: 5, offset: 1 }}>
          <Form.Item  name="edlDate" label="ETD" tooltip="Estimated Time Of Departure" rules={[{ required: etdValidationState,message: 'Missing ETD date' }]}>
              <DatePicker onChange={(date) => {
                console.log(form.getFieldValue('edaDate'),'eda',date)
                if(form.getFieldValue('edaDate')<date && form.getFieldValue('edaDate') != undefined){
                  AlertMessages.getErrorMessage('ETD must be less than ETA');form.setFieldsValue({edlDate:null})}
                  if(form.getFieldValue('invoiceDate')>date){
                    AlertMessages.getErrorMessage('ETD must be greater than Invoice date');form.setFieldsValue({edlDate:null})
                  }
                }} 
                style={{ width: '100%' }}
                disabled = {customerHidden} />
            </Form.Item>

          
            
          </Col>
                  <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 5, offset: 1 }} lg={{ span: 5, offset: 1 }} xl={{ span: 5, offset: 1 }}>
          <Form.Item name="edaDate" label="ETA"  tooltip="Estimated Time Of Arrival" rules={[{ required: etaValidationState,message: 'Missing ETA date' }]}>
              <DatePicker  onChange={(date) => {if(form.getFieldValue('edlDate')>date){AlertMessages.getErrorMessage('ETA must be greater than ETD ');form.setFieldsValue({edaDate:null})}}} 
              style={{ width: '100%' }}
              disabled = {customerHidden} 
              />
            </Form.Item>
            
          </Col>
          <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 5, offset: 1 }} lg={{ span: 5, offset: 1 }} xl={{ span: 5, offset: 1 }}>

          <Form.Item name="deliveryTerms"  label="Delivery Terms" rules={[{ required: true,message: 'Missing delivery terms' }]}>
              <Select
                showSearch
                optionFilterProp="children"
                filterOption={(input, option) => option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                placeholder="Select Delivery terms"
                allowClear
                dropdownMatchSelectWidth={false}
                disabled = { props.jobType==JobTypesEnum.MAIN_JOB ? customerHidden : subPoDisable}
              >
                {deliveryTerms.map(dropData => {
                  return <Option value={dropData.deliveryTermsId}>{dropData.deliveryTermsName}</Option>
                })}
              </Select>
            </Form.Item>
            
          </Col>



      
        </Row>
        <Row>
            <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 5 }} lg={{ span: 5 }} xl={{ span: 5 }}>
          <Form.Item name="payTermId"  label="Payment Terms" rules={[{ required: true ,message: 'Missing payment terms'}]}>
              <Select
                showSearch
                optionFilterProp="children"
                filterOption={(input, option) => option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                placeholder="Select Payment Terms"
                allowClear
                dropdownMatchSelectWidth={false}
                disabled = {props.jobType==JobTypesEnum.MAIN_JOB ? customerHidden : subPoDisable}
              >
                {paymentTerms.map(dropData => {
                  return <Option value={dropData.paymentTermsId}>{dropData.paymentTermsName}</Option>
                })}
              </Select>
            </Form.Item>
            
          </Col>
        <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 5, offset: 1 }} lg={{ span: 5, offset: 1 }} xl={{ span: 5, offset: 1 }}>
          <Form.Item name="shipmentTerms"  label="Shipment Terms" rules={[{ required: true,message: 'Missing shipment terms' }]} >
              <Select
                showSearch
                optionFilterProp="children"
                filterOption={(input, option) => option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                placeholder="Select Shipment terms"
                allowClear
                dropdownMatchSelectWidth={false}
                disabled = { props.jobType==JobTypesEnum.MAIN_JOB ? customerHidden : subPoDisable}
              >
                {shippingTerms.map(dropData => {
                  return <Option value={dropData.shiptermId}>{dropData.shipmenttermName}</Option>
                })}
              </Select>
            </Form.Item>
          
          </Col>
        <Col  xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 5, offset: 1 }} lg={{ span: 5, offset: 1 }} xl={{ span: 5, offset: 1 }}>
        <Form.Item name="processingUnit"   label="Processing Unit" rules={[{ required: true,message: 'Missing Unit' }]} >
              <Select
                showSearch
                optionFilterProp="children"
                filterOption={(input, option) => option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                placeholder="Select Processing Unit"
                allowClear
                dropdownMatchSelectWidth={false}
                disabled={disableByshipmentMode ? true : isProcessingUnitDisable}
              >
                {(props.jobType == JobTypesEnum.MAIN_JOB ||props.jobType == 'Clone') ? processingFactoriesData.map(dropData => {
                  return <Option value={dropData.plantId}>{dropData.plantCode}</Option>
                }) : processingFactoriesData.filter(item => item.plantId != props.intialData?.processingUnit).map(dropData => {
                  return <Option value={dropData.plantId}>{dropData.plantCode}</Option>
                })}
              </Select>
            </Form.Item>
          
        </Col>
        <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 5, offset: 1 }} lg={{ span: 5, offset: 1 }} xl={{ span: 5, offset: 1 }}>
        <Form.Item name="unit"   label="Export Unit" rules={[{ required: true,message: 'Missing Unit' }]} >
              <Select
                showSearch
                optionFilterProp="children"
                filterOption={(input, option) => option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                placeholder="Select Unit"
                allowClear
                dropdownMatchSelectWidth={false}
                disabled={disableByshipmentMode ? true : isManufacturingUnitDisable}
                onChange={onManufacturingUnitChange}
              >
                {factoriesData.map(dropData => {
                  return <Option value={dropData.plantId} key={dropData.plantId} company={dropData.company}>{dropData.plantName}</Option>
                })}
              </Select>
            </Form.Item>
          
          </Col>
     
          
        </Row>
        <Row>
          <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 4 }} lg={{ span: 4 }} xl={{ span: 5 }}>
        <Form.Item name="bankAccountId"   label="Bank Account" rules={[{ required: true,message: 'Missing Bank Account' }]} >
              <Select
                showSearch
                optionFilterProp="children"
                filterOption={(input, option) => option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                placeholder="Select Bank Account"
                allowClear
                dropdownMatchSelectWidth={false}
                disabled={disableByshipmentMode ? true : false}
              >
                {bankDetails.map(dropData => {
                  return <Option value={dropData.id} key={dropData.id}>{dropData.bankAccount}-{dropData.bankName}</Option>
                })}
              </Select>
            </Form.Item>
          
          </Col>
        <Col  xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 4, offset: 1 }} lg={{ span: 4, offset: 1 }} xl={{ span: 5, offset: 1 }}>
          <Form.Item name="currency"  label="Currency" rules={[{ required: true,message: 'Missing currency' }]} >
              <Select
                showSearch
                optionFilterProp="children"
                filterOption={(input, option) => option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                placeholder="Select Currency"
                allowClear
                onChange={storeCurrency}
                disabled={disableByshipmentMode ? true : props.jobType==JobTypesEnum.MAIN_JOB ? customerHidden : subPoDisable}
              >
                {currency.map(currencydropData => {
                  return <Option value={currencydropData.currencyId}>{currencydropData.currencyName}</Option>
                })}
              </Select>
            </Form.Item>
            
          </Col>
          
        <Col  xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 5, offset: 1 }} lg={{ span: 5, offset: 1 }} xl={{ span: 5, offset: 1 }}>
        <Form.Item name="portOfDischarge" label="Port Of Discharge" rules={[{ required: true, message: 'Missed Port of discharge' }]}>
            <Select
                showSearch
                optionFilterProp="children"
                filterOption={(input, option) => option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                placeholder="Select Port Of Discharge"
                // onChange={destinationOnchange}
                allowClear
                dropdownMatchSelectWidth={false}
            // disabled = {customerHidden}
            >
                {portOfDishargeData.map(dropData => {
                    return <Option value={dropData.destinationId}>{dropData.destinationName}</Option>
                })}
            </Select>
            {/* <Input /> */}

        </Form.Item>
        </Col>
        <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 4, offset: 1 }} lg={{ span: 4, offset: 1 }} xl={{ span: 5, offset: 1 }}>
        <Form.Item label="Notify Party" name='notifyParty'>
          <Select
              placeholder="Select Notify Party"
              allowClear
              showSearch
              optionFilterProp='children'
              aria-multiline
              disabled = {disableByshipmentMode ? true : false}
              dropdownMatchSelectWidth={false}
          >
              {notifyPartyDropDown.map(notifyPartydropData => {
                  return <Option key={notifyPartydropData.notifyPartyId} value={notifyPartydropData.notifyPartyId}>{notifyPartydropData.notifyPartyName}</Option>
              })}
          </Select>
          </Form.Item>
        </Col>
        <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 4 }} lg={{ span: 4 }} xl={{ span: 5 }}>
        <Form.Item label="Gross Weight"
          name={'grossWeight'}
          rules={[{ required: true, message: 'Missing Gross Weight' }]}
        >
          <InputNumber style = {{width:'100%'}} placeholder="Gross Weight"  min={0}/>
        </Form.Item>
        </Col>
        <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 4, offset: 1 }} lg={{ span: 4, offset: 1 }} xl={{ span: 5, offset: 1 }}>
        <Form.Item label="Frozen Weight"
          name={'frozenWeight'}
          rules={[{ required: frozenWeightRequired, message: 'Missing Frozen Weight' }]}
        >
          <InputNumber style = {{width:'100%'}} placeholder="Frozen Weight"  min={0}/>
        </Form.Item>
        </Col>
        <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 4, offset: 1 }} lg={{ span: 4, offset: 1 }} xl={{ span: 5, offset: 1 }}>
        <Form.Item label="Proforma Invoice Number"
          name={'proformaInvoiceNumber'}
          rules={[{ required: true, message: 'Missing Proforma Invoice Number' }]}
        >
          <Input style = {{width:'100%'}} placeholder="Proforma Invoice Number" disabled = {disableByshipmentMode ? true : props.intialData ? poNumberDisable : props.jobType==JobTypesEnum.MAIN_JOB ? customerHidden:subPoDisable}/>
        </Form.Item>
        </Col>
        <Col span={6}>
          <Form.Item name = "fileUpload" >

      <Upload {...uploadFieldProps}>
        <br/><Button style={{ color: "black", backgroundColor: "#7ec1ff" }} icon={<UploadOutlined />}>Upload Work Order & Code List</Button><p>{props.intialData ? uploadedFileName?`Uploaded File - ${uploadedFileName}`:'':''}</p><Typography.Text  type="secondary">
        (Supported formats xlsx,csv,xls,pdf,zip)
                </Typography.Text>
      </Upload>
      </Form.Item>

          </Col>
        </Row>

      </Form>
    </Card></>)
}
export default CustomerDetailsForm
