Untitled

mail@pastecode.io avatar
unknown
plain_text
19 days ago
65 kB
5
Indexable
Never
import DatePicker from '@Components/DatePicker';
import { FunnelNavigationStackScreenProps } from '@Components/navigations/StackScreenProps';
import { prospectDropdownFileCategoryApiUri,spkFileUpload,prospectProfileInfoApiUri, createSPKNew } from '@Constants/apiUri';
import { IsuzuRed } from '@Constants/colors';
import { setAccessibility } from '@Functions/AccessibilityLabel';
import { FetcherWithAuthorizationBearerHeader, FetcherWithPostAuthorizationBearerHeader } from '@Functions/SwrFetcher';
import { zodResolver } from '@hookform/resolvers/zod';
import { useQuery } from '@tanstack/react-query';
import React, { FC, useEffect, useState, useMemo, useCallback } from 'react';
import { Controller, useForm } from 'react-hook-form';
import { Image, Pressable, ScrollView, View, TextInput, KeyboardAvoidingView, Platform, Alert, Linking, useWindowDimensions, BackHandler, ViewProps, Dimensions } from 'react-native';
import { ActivityIndicator, Button, Snackbar, Modal } from 'react-native-paper';
import { typeRequiredCSGO, defineResolver } from "./CreateSPKStep4ScreenFormSchema"
import { MaterialCommunityIcons } from '@expo/vector-icons';
import IsuzuIdText from '@Components/IsuzuIdText';
import { OutlinedDropdownInput } from '@Components/OutlinedDropdownInput';
import { convertBackNumber, numberFormattersV2 } from '@Functions/NumberFormatters';
import * as DocumentPicker from 'expo-document-picker';
import { ALLOWED_PROSPECT_FILE_EXTENSIONS, ALLOWED_SPK_FILE_EXTENSIONS } from '@Constants/FileExtensions';
import { readAccessToken } from '@Functions/AccessToken';
import {HeaderStepSPK} from './HeaderStepSPK'
import { styles } from "./StyleCreateSPKStep1"
import {CreateSPK4Form, initialValue,DataFileCategory, dataDocumentCategories, DataDetailDocument, PLAT_MERAH, GOVERNMENT} from "./InterfaceCreateSPKStep4"
import  {CREATE_SPK_LABEL} from './LabelCreateSPKStep4'
import { FontAwesome5 } from '@expo/vector-icons'
import BottomSheet from '@Components/BottomSheet'
import { PreviewModalContent } from '@Components/navigations/Product/screens/SalesProgramComponents/previewContent/PreviewModalContent';
import { ProspectProfileInfo } from '@Interfaces/ProspectProfileInfo';
import * as ImagePicker from 'expo-image-picker';
import RenderIf from '@Functions/RenderIf';
import Constants from 'expo-constants';
import * as IntentLauncher from 'expo-intent-launcher';
import axios from 'axios';
import { HeaderBackButton } from '@react-navigation/elements';
import { useFocusEffect } from '@react-navigation/native';
import * as Sentry from 'sentry-expo';

const CreateSPKStep4Screen: FC<FunnelNavigationStackScreenProps<'CreateSPKStep4Screen'>> = ({ navigation, route }) => {
    const { createSPK, salesmanId, prospectId} =  route.params
    const [datePickerSPKDateVisible, setDatePickerSPKDateVisible] = useState<boolean>(false)
    const [datePickerDOEstimateVisible, setDatePickerDOEstimateVisible] = useState<boolean>(false)
    const [loadingUpdate, setLoadingUpdate] = useState<boolean>(false)
    const [showBottomSheetDocument, setShowBottomSheetDocument] = useState<boolean>(false)
    const [showBottomSheetDocumentCamera, setShowBottomSheetDocumentCamera] = useState<boolean>(false)
    const [selectedDetailDocument, setSelectedDetailDocument] = useState<DataDetailDocument>()
    const [showPreviewModal, setShowPreviewModal] = useState<boolean>(false)
    const [previewDocId, setPreviewDocId] = useState<string>("")
	const [previewDocMimeType, setPreviewDocMimeType] = useState<string>("")
    const [errorSnack, setErrorSnack] = useState<boolean>(false)
    const [errorSnackMessage, setErrorSnackMessage] = useState<string>('')
    const [successSnack, setSuccessSnack] = useState<boolean>(false)
    const [successSnackMessage, setSuccessSnackMessage] = useState<string>('')
    const [loadingSendSPK, setLoadingSendSPK] = useState<boolean>(false)
    const [selectedDocument, setSelectedDocument] = useState()

    const resolver = useMemo(() => {
        return zodResolver(defineResolver(createSPK?.detailCustomer?.title,createSPK?.detailPayment?.salesTypeCode))
    },[createSPK])

    const {
        control,
        formState: { errors },
        setError,
        clearErrors,
        handleSubmit,
        setValue,
        watch,
    } = useForm<CreateSPK4Form>({
        resolver: resolver,
        defaultValues: initialValue,
    });

    const {
        spkId,
        spkNumber,
        spkDate,
        spkStatus,
        inquiryNo,
        doEstimate,
        lkpp,
        total,
        detailDocument,
        plat,
        customerGroup
    } = watch();
    const onSubmit = async(data: CreateSPK4Form) => {
        setLoadingSendSPK(true)
        try {

            const dataReadyToSend = {
                "spkId": createSPK?.spkId,
                "opportunityId": createSPK?.detailOrder?.opportunityId,
                "spkNumber": spkNumber,
                "spkDate": spkDate,
                "spkStatus": spkStatus,
                "inquiryNo": inquiryNo,
                "doEstimate": doEstimate,
                "lkpp": lkpp,
                "total": total,
                "isDraft": false,
                "isCompany" : createSPK?.detailCustomer?.title === 'Company' ? true : false,
                "detailOrder": {
                    "isSPKDataSameWithPreviousSPKData" : createSPK?.detailOrder?.isSPKDataSameWithPreviousSPKData ? true : false,
                    "spkDetailOrderId": createSPK?.detailOrder?.spkDetailOrderId,
                    "opportunityId": createSPK?.detailOrder?.opportunityId,
                    "carModelId": createSPK?.detailOrder?.carModelId,
                    "carVariantId": createSPK?.detailOrder?.carVariantId,
                    "vin": createSPK?.detailOrder?.vin,
                    "carColorId": createSPK?.detailOrder?.carColorId,
                    "qty": createSPK?.detailOrder?.qty,
                    "lisencePlatTypeId": createSPK?.detailOrder?.lisencePlatTypeId,
                    "unitUsageLocationCode": createSPK?.detailOrder?.unitUsageLocationCode,
                    "unitUsageLocationName": createSPK?.detailOrder?.unitUsageLocationName,
                    "karoseriId": createSPK?.detailOrder?.karoseriId,
                    "isKaroseriSpkAstra": createSPK?.detailOrder?.isKaroseriSpkAstra,
                    "hasSKRB": createSPK?.detailOrder?.hasSKRB,
                    "isKaroseriMou": createSPK?.detailOrder?.isKaroseriMou,
                    "karoseriVendorId": createSPK?.detailOrder?.karoseriVendor,
                    "karoseriPrice": createSPK?.detailOrder?.karoseriPrice,
                    "isNeedDiscountApproval": createSPK?.detailOrder?.isNeedDiscountApproval,
                    "isNeedEscalation": createSPK?.detailOrder?.isNeedEscalation,
                    "totalDiscount": createSPK?.detailOrder?.totalDiscount,
                    "discountProgramId": createSPK?.detailOrder?.discountProgramId
                },
                "detailAccessories": createSPK?.detailAccessories,
                "detailCustomer": {
                    "customerId": createSPK?.detailCustomer?.customerId,
                    "customerName": createSPK?.detailCustomer?.customerName,
                    "customerPhoneNumber": createSPK?.detailCustomer?.ownerPhoneNumber,
                    "customerKtp": createSPK?.detailCustomer?.customerKtp,
                    "customerNpwp": createSPK?.detailCustomer?.customerNpwp,
                    "customerAddress": createSPK?.detailCustomer?.customerAddress,
                    "isBpkbSameWithCustData": createSPK?.detailCustomer?.isBpkbSameWithCustData,
                    "bpkbStnkOwner": createSPK?.detailCustomer?.bpkbStnkOwner,
                    "ownerKtp": createSPK?.detailCustomer?.ownerKtp,
                    "ownerNpwp": createSPK?.detailCustomer?.ownerNpwp,
                    "ownerAddress": createSPK?.detailCustomer?.ownerAddress,
                    "ownerCityCode": createSPK?.detailCustomer?.ownerCityCode,
                    "ownerCityName": createSPK?.detailCustomer?.ownerCityName,
                    "ownerProvinceCode": createSPK?.detailCustomer?.ownerProvinceCode,
                    "ownerProvinceName": createSPK?.detailCustomer?.ownerProvinceName,
                    "ownerMobilePhoneNumber": createSPK?.detailCustomer?.ownerPhoneNumber,
                    "ownerPhoneNumber": createSPK?.detailCustomer?.ownerPhoneNumber,
                    "ownerEmail": createSPK?.detailCustomer?.ownerEmail,
                    "ownerFaxNumber": createSPK?.detailCustomer?.ownerFaxNumber,
                    "unitUserName": createSPK?.detailCustomer?.unitUserName,
                    "unitUserAddress": createSPK?.detailCustomer?.unitUserAddress,
                    "unitUserPhoneNumber": createSPK?.detailCustomer?.unitUserPhoneNumber,
                    "ppnCode": createSPK?.detailCustomer?.ppnCode,
                    "isSameAsMainOrderInformation": createSPK?.detailCustomer?.isSameAsMainOrderInformation,
                    "isWapu": createSPK?.detailCustomer?.isWapu,
                    "isCustomerPriority": createSPK?.detailCustomer?.isCustomerPriority,
                    "hasTaxInvoice": createSPK?.detailCustomer?.hasTaxInvoice,
                },
                "detailPayment": {
                    "spkPaymentManagementId": createSPK?.detailPayment?.spkPaymentManagementId,
                    "bbnTypeId": createSPK?.detailPayment?.bbnTypeId,
                    "biroJasaId":createSPK?.detailPayment?.biroJasaId,
                    "bbnCityId":createSPK?.detailPayment?.bbnCityId,
                    "locoId":createSPK?.detailPayment?.locoId,
                    "salesTypeCode": createSPK?.detailPayment?.salesTypeCode,
                    "leasingProviderId":createSPK?.detailPayment?.leasingProviderId,
                    "tenorId":createSPK?.detailPayment?.tenorId,
                    "isValidTop": createSPK?.detailPayment?.isValidTop,
                    "top": createSPK?.detailPayment?.top,
                    "commissionFee": createSPK?.detailPayment?.commissionFee,
                    "isSameSkDepositValue": createSPK?.detailPayment?.isSameSkDepositValue,
                    "downpayment": createSPK?.detailPayment?.downpayment,
                    "deposit": createSPK?.detailPayment?.deposit,
                    "sendKaroseriAfterCompleted": createSPK?.detailPayment?.sendKaroseriAfterCompleted,
                    "sendCustomerAfterCompleted": createSPK?.detailPayment?.sendCustomerAfterCompleted,
                    "sendContractAfterValid": createSPK?.detailPayment?.sendContractAfterValid,
                    "isValidContractKaroseri": createSPK?.detailPayment?.isValidContractKaroseri,
                    "hasGuarantee": createSPK?.detailPayment?.hasGuarantee,
                    "hasCustomerContract": createSPK?.detailPayment?.hasCustomerContract,
                    "hasDipa": createSPK?.detailPayment?.hasDipa
                },
                "detailDocument": detailDocument
            }

            const responseJSON = await FetcherWithPostAuthorizationBearerHeader(createSPKNew,dataReadyToSend)
            navigation.reset({
                index: 2,
                routes: [
                    { name: "FunnelScreen" },
                    { name: "ProspectListScreen", params: { initialRouteName: "P2-SPK" } },
                    { name: "DetailProspectP3Screen", params : { prospectId, salesmanId} },
                ],
			});
            setLoadingSendSPK(false)
        } catch (error : any) {
            setLoadingSendSPK(false)
            setErrorSnack(true)
        
            if (axios.isAxiosError(error)) {
                setErrorSnackMessage(error.response.data.message)
                Sentry.Native.captureException(error);
            }
        }
    };

    const { data: dataFileCategories, isLoading : isLoadingDataFileCategories} = useQuery<DataFileCategory[]>({
        queryKey: ['prospectDropdownFileCategoryApiUri', createSPK?.detailOrder?.opportunityId],
        queryFn: async () => await FetcherWithAuthorizationBearerHeader(prospectDropdownFileCategoryApiUri)
    });

    const { data: dataProfileProspect, isLoading : isLoadingProfileProspect, isFetched : isFetchedProfileProspect } = useQuery<ProspectProfileInfo>({
        queryKey: ['dataProfileProspect', prospectId, salesmanId],
        queryFn: async () => await FetcherWithAuthorizationBearerHeader(prospectProfileInfoApiUri+"/"+prospectId+"/"+salesmanId),
    });

    const onConfirmSPKDate = (value: Date) => {
        setDatePickerSPKDateVisible(false);
        setValue('spkDate', value.toISOString());
    };

    const onConfirmDoEstimateDate = (value: Date) => {
        setDatePickerDOEstimateVisible(false);
        setValue('doEstimate', value.toISOString());
    }

    // handle navigate
    function navigateToSelectSPKNumber() {
        navigation.navigate('DropdownSPKNumberScreen', { createSPK, salesmanId, prospectId});
    }

    function navigateToSelectLKPP() {
        navigation.navigate('DropdownVinScreen',{ prospectId, salesmanId, fromScreen : "CreateSPKStep4Screen", createSPK : createSPK });
    }

    function navigateToBackStep(){
        const newSPK = appendValue();
        navigation.navigate("CreateSPKStep3Screen",{ salesmanId, prospectId, createSPK : newSPK })
    }

    function appendValue() {
        const newData = {doEstimate, detailDocument, lkpp, total, inquiryNo, spkNumber, spkStatus, spkId, spkDate}
		const newDataSPK = { ...createSPK, ...newData };
		return newDataSPK;
	}

    const goBackArrow = (onPress: () => boolean) => {
		return <HeaderBackButton style={{ marginLeft: '-1%' }} tintColor={IsuzuRed} onPress={onPress} />;
	};
   
	useFocusEffect(
		useCallback(() => {
			const backAction = () => {
				navigateToBackStep()
				return true;
			};
   
			navigation.setOptions({
				headerLeft: () => goBackArrow(backAction),
			});

			const backHandler = BackHandler.addEventListener(
                'hardwareBackPress',
                backAction
            );
   
            return () => backHandler.remove();
		}, [ appendValue ])
	);

    // set automated filled value
    useEffect(() => {
        if(createSPK?.spkDate){
            setValue('spkDate',createSPK?.spkDate)
        }
        if(createSPK?.spkStatus){
            setValue('spkStatus',createSPK?.spkStatus)
        }
        if(createSPK?.spkNumber){
            setValue('spkNumber',createSPK?.spkNumber)
        }
        if(createSPK?.lkpp){
            setValue('lkpp',createSPK?.lkpp)
        }
        if(createSPK?.total){
            setValue('total',createSPK?.total.toString())
        }
        if(createSPK?.doEstimate){
            setValue('doEstimate',createSPK?.doEstimate)
        }
        if(createSPK?.inquiryNo){
            setValue('inquiryNo',createSPK?.inquiryNo)
        }
        if(createSPK?.detailDocument){
            const dataDocuments = createSPK?.detailDocument
            setValue('detailDocument',dataDocuments)
            for (let i = 0; i < dataDocuments.length; i++) {
                setValueDocument(dataDocuments[i].documentCategoryId,dataDocuments[i].fileId)
            }
        }
        if(createSPK?.detailOrder?.lisencePlatTypeName){
            setValue('plat',createSPK?.detailOrder?.lisencePlatTypeName)
        }
    },[createSPK, createSPK?.detailOrder, createSPK?.detailCustomer])

    useEffect(() => {
        if(dataProfileProspect?.customerGroup){
            setValue('customerGroup',dataProfileProspect?.customerGroup)
        }
    },[isFetchedProfileProspect])

    useEffect(() => {
        if(customerGroup === GOVERNMENT && plat === PLAT_MERAH){
            setValue('requiredCSGOSection',typeRequiredCSGO.LKPPTOTALEKATALOG)    
        }
        if(customerGroup === GOVERNMENT && plat !== PLAT_MERAH){
            setValue('requiredCSGOSection',typeRequiredCSGO.LKPPTOTAL)    
        }
        if(customerGroup !== GOVERNMENT && plat === PLAT_MERAH){
            setValue('requiredCSGOSection',typeRequiredCSGO.EKATALOG)    
        }
        if(createSPK?.detailPayment?.salesTypeCode === 'GSO'){
            setValue('requiredCSGOSection',typeRequiredCSGO.LKPPTOTALEKATALOG)
        }
    },[plat,customerGroup])

     const setDeleteRequiredDocument = (id:number) => {
        //ktp
        if(id === 1){
            setValue('fileKTP',undefined)
        }
        //npwp bpkb
        if(id === 2){
            setValue('fileNPWPBPKB',undefined)
        }
        //npwp
        if(id === 3){
            setValue('fileNPWP',undefined)
        }
        //ktpbpkb
        if(id === 4){
            setValue('fileKTPBPKB',undefined)
        }
        //spk
        if(id === 7){
            setValue('fileSPK',undefined)
        }
        //e-lkpp
        if(id === 14){
            setValue('fileELKPP',undefined)
        }
        //NIB Perusahaan
        if(id === 16){
            setValue('fileNIBPerusahaan',undefined)
        }
        //SPJB
        if(id === 9){
            setValue('fileSPJB',undefined)
        }
    }

    const setValueDocument = (id:number,blobId:string) => {
        //ktp
        if(id === 1){
            setValue('fileKTP',blobId)
            clearErrors('fileKTP')
        }
        //npwp bpkb
        if(id === 2){
            setValue('fileNPWPBPKB',blobId)
            clearErrors('fileNPWPBPKB')
        }
        //npwp
        if(id === 3){
            setValue('fileNPWP',blobId)
            clearErrors('fileNPWP')
        }
        //ktpbpkb
        if(id === 4){
            setValue('fileKTPBPKB',blobId)
            clearErrors('fileKTPBPKB')
        }
        //spk
        if(id === 7){
            setValue('fileSPK',blobId)
            clearErrors('fileSPK')
        }
        //e-lkpp
        if(id === 14){
            setValue('fileELKPP',blobId)
            clearErrors('fileELKPP')
        }
        //NIB Perusahaan
        if(id === 16){
            setValue('fileNIBPerusahaan',blobId)
            clearErrors('fileNIBPerusahaan')
        }
        //SPJB
        if(id === 9){
            setValue('fileSPJB',blobId)
            clearErrors('fileSPJB')
        }
    }

    const onAttachFile = async (idCategory:number, nameCategory:string, indexFile:number|undefined = undefined) => {
        const exist = dataFileCategories?.find((item) => item.id === idCategory && item.name === nameCategory);
        if (exist) {
            const allowedType = idCategory === 14 ? ALLOWED_SPK_FILE_EXTENSIONS : ALLOWED_PROSPECT_FILE_EXTENSIONS
            const result = await DocumentPicker.getDocumentAsync({
                type: allowedType
            });

            if (!result.canceled) {
                const dataFile = result.assets?.[0]
                // Check if the format is jpg, jpeg, png, doc, xlsx, pdf
                if (dataFile.mimeType) {
                    const documentFormat = dataFile.mimeType;
                    if (!allowedType.includes(documentFormat)) {
                        setErrorSnack(true)
                        return setErrorSnackMessage('Format dokumen belum sesuai');
                    }
                }

                const maxSizeFileLKPP = 10000000 //10MB
                const maxSizeFileOthers = 5000000 //5MB
                // Check if the size is over 5 MB
                if ( idCategory !== 14 && dataFile.size && dataFile.size > maxSizeFileOthers) {
                    setErrorSnack(true)
                    return setErrorSnackMessage('Ukuran Maksimal: 5 MB');
                }

                if ( idCategory === 14 && dataFile.size && dataFile.size > maxSizeFileLKPP) {
                    setErrorSnack(true)
                    return setErrorSnackMessage('Ukuran Maksimal: 10 MB');
                }

                setLoadingUpdate(true);

                const token = await readAccessToken();
                if (!token) {
                    setLoadingUpdate(false);
                    setErrorSnack(true)
                    return setErrorSnackMessage('Data SPK gagal diperbarui');
                }

                const formData = new FormData();
                    formData.append('file', {
                        uri: dataFile.uri,
                        name: dataFile.name,
                        type: dataFile.mimeType,
                    } as never);

                try {
                    const response = await fetch(spkFileUpload,{
                            method: 'POST',
                            body: formData,
                            mode: 'cors',
                            headers: {
                                Accept: 'application/json',
                                Authorization: `Bearer ${token}`,
                                'Content-Type': 'multipart/form-data',
                            },
                        });

                    const resultJson = await response.json();
                    const checkingNPWPBPKB = detailDocument.find(x => x.documentCategoryId === 2)
                    const checkingKTPBPKB = detailDocument.find(x => x.documentCategoryId === 4)
                    const dataNew = [{
                                fileId: resultJson.fileId,
                                fileName: resultJson.fileName,
                                contentType: resultJson.contentType,
                                documentCategoryId: idCategory,
                                documentCategoryName: nameCategory,
                                spkDocumentId : '',
                                description: '',
                            }]
                    if(idCategory === 3 && !checkingNPWPBPKB && createSPK?.detailCustomer?.isBpkbSameWithCustData) {
                        dataNew.push({
                                fileId: resultJson.fileId,
                                fileName: resultJson.fileName,
                                contentType: resultJson.contentType,
                                documentCategoryId: 2,
                                documentCategoryName: 'NPWP BPKB/STNK',
                                spkDocumentId : '',
                                description: '',
                        })
                        setValueDocument(2,resultJson.fileId)
                    }
                    if(idCategory === 1 && !checkingKTPBPKB && createSPK?.detailCustomer?.isBpkbSameWithCustData && createSPK.detailCustomer.title !== 'Company'){
                        dataNew.push({
                                fileId: resultJson.fileId,
                                fileName: resultJson.fileName,
                                contentType: resultJson.contentType,
                                documentCategoryId: 4,
                                documentCategoryName: 'KTP BPKB/STNK',
                                spkDocumentId : '',
                                description: '',
                        })
                        setValueDocument(4,resultJson.fileId)
                    }
                    if (detailDocument) {
                            if(indexFile && indexFile > -1){
                                const selectedData = detailDocument[indexFile]
                                detailDocument[indexFile] = {
                                    fileId: resultJson.fileId,
                                    fileName: resultJson.fileName,
                                    contentType: resultJson.contentType,
                                    documentCategoryId: selectedData.documentCategoryId,
                                    documentCategoryName: selectedData.documentCategoryName,
                                    spkDocumentId : selectedData.spkDocumentId,
                                    description: selectedData.description,
                                }
                                setValue('detailDocument', detailDocument);
                            }else{
                                setValue('detailDocument', [
                                    ...detailDocument,
                                    ...dataNew,
                                ]);
                            }
                    } else {
                        setValue('detailDocument', dataNew);
                    }
                    setValueDocument(idCategory,resultJson.fileId)
                    setSuccessSnack(true)
                    setSuccessSnackMessage('Berhasil mengupload file')
                } catch (e){
                    console.log(e);
                    setLoadingUpdate(false);
                    setErrorSnack(true)
                    return setErrorSnackMessage('File Gagal di Upload');
                }
                setLoadingUpdate(false);
            }
            
        } else {
            setLoadingUpdate(false);
            setErrorSnack(true)
            return setErrorSnackMessage('Kategori dokumen tidak ditemukan');
        }
    };

    const onOpenCamera = async (idCategory:number, nameCategory:string, indexFile:number|undefined = undefined) => {
        const status = await ImagePicker.requestCameraPermissionsAsync()
            if (status.status !== ImagePicker.PermissionStatus.GRANTED) {

                Alert.alert(
                    'Camera Permission Denied',
                    "Maaf, fitur ini membutuhkan akses Kamera dalam perangkat!",
                    [
                        { text: 'Setting', onPress: () => {
                            if (Platform.OS === 'ios') {
                                Linking.openURL('app-settings:');
                            } else {
                                try {
                                    IntentLauncher.startActivityAsync(
                                        IntentLauncher.ActivityAction.APPLICATION_DETAILS_SETTINGS,
                                        { data: 'package:' + Constants.expoConfig?.android?.package }
                                    );
                                } catch (e) {
                                    console.log('errorrrrrrrr', e);
                                }
                    
                            }
                        }},
                        {
                            text: 'Cancel',
                            style: 'cancel',
                        },
                    ],
                    { cancelable: false }
                );
                return;
            }
        
        const exist = dataFileCategories?.find((item) => item.id === idCategory && item.name === nameCategory);
        if (exist) {
            setLoadingUpdate(true);
            try {    
                const result = await ImagePicker.launchCameraAsync({
                    mediaTypes: ImagePicker.MediaTypeOptions.Images,
                    allowsEditing: true,
                    // aspect: [4, 3],
                    quality: 1,
                });
    
                if (!result.canceled) {
                    const formData = new FormData();
                    formData.append('file', {
                        uri: result.assets[0].uri,
                        name: `image_${Date.now()}.jpg`,
                        type: 'image/jpeg',
                    } as never);
    
                    const token = await readAccessToken();
                    if (!token) {
                        setLoadingUpdate(false);
                        setErrorSnack(true)
                        return setErrorSnackMessage('Data SPK gagal diperbarui');
                    }
    
                    const response = await fetch(spkFileUpload,{
                        method: 'POST',
                        body: formData,
                        mode: 'cors',
                        headers: {
                            Accept: 'application/json',
                            Authorization: `Bearer ${token}`,
                            'Content-Type': 'multipart/form-data',
                        },
                    });
    
                    const resultJson = await response.json();
                    const dataNew = [{
                        fileId: resultJson.fileId,
                        fileName: resultJson.fileName,
                        contentType: resultJson.contentType,
                        documentCategoryId: idCategory,
                        documentCategoryName: nameCategory,
                        spkDocumentId : '',
                        description: '',
                    }]
    
                    if (detailDocument) {
                        if(indexFile && indexFile > -1){
                            const selectedData = detailDocument[indexFile]
                            detailDocument[indexFile] = {
                                fileId: resultJson.fileId,
                                fileName: resultJson.fileName,
                                contentType: resultJson.contentType,
                                documentCategoryId: selectedData.documentCategoryId,
                                documentCategoryName: selectedData.documentCategoryName,
                                spkDocumentId : selectedData.spkDocumentId,
                                description: selectedData.description,
                            }
                            setValue('detailDocument', detailDocument);
                        } else {
                            setValue('detailDocument', [
                                ...detailDocument,
                                ...dataNew,
                            ]);
                        }
                    } else {
                        setValue('detailDocument', dataNew);
                    }
                    setValueDocument(idCategory,resultJson.fileId)
                    setSuccessSnack(true)
                    setSuccessSnackMessage('Berhasil mengupload file')
                }
            } catch (e){
                console.log(e);
                setLoadingUpdate(false);
                setErrorSnack(true)
                return setErrorSnackMessage('File Gagal di Upload');
            }
            setLoadingUpdate(false);
        } else {
            setLoadingUpdate(false);
            setErrorSnack(true)
            return setErrorSnackMessage('Kategori dokumen tidak ditemukan');
        }
    };
    
    const onDeleteFile = async(deleteItem:DataDetailDocument|undefined) => {
        try {
            if (detailDocument && deleteItem) {
                const token = await readAccessToken();
                if (!token) {
                    throw new Error('Token tidak tersedia');
                }
                const index = detailDocument.findIndex(
                    (item) =>
                        item.fileId === deleteItem.fileId &&
                        item.fileName === deleteItem.fileName &&
                        item.contentType === deleteItem.contentType &&
                        item.documentCategoryId === deleteItem.documentCategoryId &&
                        item.documentCategoryName === deleteItem.documentCategoryName &&
                        item.spkDocumentId === deleteItem.spkDocumentId &&
                        item.description === deleteItem.description
                );
    
                if (index > -1) {
                    detailDocument.splice(index, 1);
                    setValue('detailDocument', detailDocument);
                    setShowBottomSheetDocument(false);
                    setDeleteRequiredDocument(deleteItem.documentCategoryId);
    
                    const response = await fetch(spkFileUpload + `/${deleteItem.fileId}`, {
                        method: 'DELETE',
                        mode: 'cors',
                        headers: {
                            Accept: 'application/json',
                            Authorization: `Bearer ${token}`,
                        },
                    });
    
                    if (!response.ok) {
                        throw new Error('Gagal menghapus file');
                    }
    
                    setSuccessSnack(true);
                    setSuccessSnackMessage('Berhasil menghapus file');
                } else {
                    throw new Error('Item tidak ditemukan');
                }
            } else {
                throw new Error('Detail document atau item untuk dihapus tidak tersedia');
            }
        } catch (error) {
            setErrorSnack(true);
            setErrorSnackMessage(error.message);
        }
    };

    const getUrlFile = async(itemId:string|undefined, mimeType : string|undefined) => {
        try {
            const resultJson = await FetcherWithAuthorizationBearerHeader(spkFileUpload+"/"+itemId)
            setShowBottomSheetDocument(false)
            setPreviewDocId(resultJson)
            setPreviewDocMimeType(mimeType)
            setShowPreviewModal(true)
        } catch (error) {
            console.log('errorGetFile',error)
        }
    }

    if (isLoadingDataFileCategories) {
		return (
			<View className="flex-1 items-center justify-center">
				<ActivityIndicator size="large" color={IsuzuRed} />
			</View>
		);
	}

    function checkingDocument(idDocument:number) {
        const checkingItem = detailDocument.filter((x) => x.documentCategoryId === idDocument)
        if(checkingItem) return checkingItem
        return undefined
    }

    function checkingDocumentUploaded(type:string, item:DataDetailDocument[], itemId:number, itemName:string){
       if(type === 'checklist'){
            if(item.length>0){
                // checking if document category is not Lainnya (13)
                if(itemId !== 13){
                    return (
                        <Image
                            className="self-center w-[18px] h-[18px]"
                            source={require('../../../../../../assets/icon-circle-checklist.png')}
                        />
                    )
                }
                if(item.length === 5){
                    return (
                        <Image
                            className="self-center w-[18px] h-[18px]"
                            source={require('../../../../../../assets/icon-circle-checklist.png')}
                        />
                    )
                }
            }
            return (
                <View className='border border-[#AAAFB6] w-[18px] h-[18px] rounded-full'></View>
            )
       }

       if(type === 'button'){
            if(item.length > 0){
                if(itemId !== 13){
                    return (
                        <Pressable 
                            onPress={() => {
                                setSelectedDetailDocument(item[0])
                                setShowBottomSheetDocument(true)
                            }} 
                            className='border border-[#ADB5BB] rounded-lg p-2.5'
                        >
                            <FontAwesome5 name="ellipsis-h" color="#242424" size={24}></FontAwesome5> 
                        </Pressable>
                    )
                }
                if(item.length === 5){
                    return null
                }else{
                    return (
                        <Pressable onPress={() => onAttachFile(itemId,itemName)} className='border border-[#ADB5BB] rounded-lg p-2.5'>
                            <Image
                                className="self-center w-[24px] h-[24px]"
                                source={require('../../../../../../assets/icon-upload-blue.png')}
                            />
                        </Pressable>
                    )
                }
            }
            return (
                <Pressable 
                    onPress={() => {
                        setSelectedDetailDocument(item[0])
                        setShowBottomSheetDocumentCamera(true)
                        setSelectedDocument(dataDocumentCategories.find((item) => item.id === itemId));
                    }} 
                    className='border border-[#ADB5BB] rounded-lg p-2.5' 
                    >
                    <Image
                        className="self-center w-[24px] h-[24px]"
                        source={require('../../../../../../assets/icon-upload-blue.png')}
                    />
                </Pressable>
            )
       }

       return (<View></View>)
    }

    function checkingFileCanBeView(itemExt:string|undefined) {
        if(itemExt) return ALLOWED_SPK_FILE_EXTENSIONS.includes(itemExt)
        return false
    }

    function renderBottomSheetDocument () {
        const findIndexFile = detailDocument.findIndex((e) => e.fileId === selectedDetailDocument?.fileId)
        return (
            <BottomSheet
                {...setAccessibility(CREATE_SPK_LABEL.BOTTOM_SHEET_DOKUMEN)}
                visible={showBottomSheetDocument}
                onDismiss={() => setShowBottomSheetDocument(false)}
                containerStyle={styles.bottomSheet}
                transparent
            >
                <View className="bg-[#E7E7E7] h-1.5 w-20 rounded-md mb-3.5" />
                {checkingFileCanBeView(selectedDetailDocument?.contentType) ? 
                <Pressable onPress={() => getUrlFile(selectedDetailDocument?.fileId, selectedDetailDocument?.contentType)} className='border-t border-[#EEEEEF] w-full pl-6 py-3'>
                    <View className='flex flex-row space-x-3.5 items-center'>
                        <FontAwesome5 name="eye" color="#000000" size={24}></FontAwesome5> 
                        <IsuzuIdText className='font-sm'>Lihat Dokumen</IsuzuIdText>
                    </View>
                </Pressable> : null }
                
                <Pressable 
                    className='border-t border-[#EEEEEF] w-full pl-6 py-3'
                    onPress={() => {
                        setShowBottomSheetDocumentCamera(true)
                        setShowBottomSheetDocument(false)
                    }}
                >
                    <View className='flex flex-row space-x-3.5 items-center'>
                        <FontAwesome5 name="pencil-alt" color="#FA5674" size={24}></FontAwesome5> 
                        <IsuzuIdText className='font-sm'>Ubah Dokumen</IsuzuIdText>
                    </View>
                </Pressable>
                <Pressable onPress={() => onDeleteFile(selectedDetailDocument)} className='border-t border-[#EEEEEF] w-full pl-6 py-3'>
                    <View className='flex flex-row space-x-3.5 items-center'>
                        <FontAwesome5 name="trash" color="#FFAC4A" size={24}></FontAwesome5> 
                        <IsuzuIdText className='font-sm'>Hapus</IsuzuIdText>
                    </View>
                </Pressable>
            </BottomSheet>
        )
    }

    const ButtonCameraAndDocument = ({
        onPress,
        nameIcon,
        title,
        isUseIcon,
        isUseSource,
        classImage,
        source = '@Assets/ic_camerapng.png',
    } : {
        title: string;
        onPress: () => void;
        classImage?: ViewProps['className']
        isUseIcon: boolean;
        nameIcon?: 'camera' | 'alt-pencil' | string;
        isUseSource: boolean;
        source?: string;
    }) => {
        return ( 
            <Pressable
                className="bg-white p-4 rounded-xl border border-zinc-300 flex flex-col gap-y-4 justify-center items-center mt-2"
                onPress={onPress}
            >
                {/* State when isUseIcon is true */}
                <RenderIf condition={isUseIcon}>
                    <FontAwesome5 name={nameIcon} color="#FA5674" size={32}></FontAwesome5>
                </RenderIf>
        
                {/* State when isUseSource is true */}
                <RenderIf condition={isUseSource}>
                <Image
                    className={
                        [
                            'self-center',
                            classImage,
                        ].join(' ')
                    }
                    source={source}
                />
                </RenderIf>
        
                <IsuzuIdText className="font-sm">{title}</IsuzuIdText>
          </Pressable>
        )
    }

    function renderBottomSheetDocumentCamera () {
        return (
            <BottomSheet
                {...setAccessibility(CREATE_SPK_LABEL.BOTTOM_SHEET_DOKUMEN)}
                visible={showBottomSheetDocumentCamera}
                onDismiss={() => setShowBottomSheetDocumentCamera(false)}
                containerStyle={{
                    position:'relative', 
                    flexDirection:'row', 
                    height:'auto',
                    justifyContent:'space-around',
                    padding: 32
                }}
                transparent 
                >   
                <View className="bg-[#E7E7E7] h-1.5 w-20 rounded-md mb-3.5 absolute top-4 right-[50%]" />
                <ButtonCameraAndDocument 
                    nameIcon=""
                    isUseIcon={false}
                    isUseSource={true}
                    // classImage='w-[20px] h-[18px]'
                    onPress={
                        () => {
                            onOpenCamera(selectedDocument?.id || '', selectedDocument?.name)
                            setShowBottomSheetDocumentCamera(false)
                        }
                    }
                    title='Pilih Camera'
                    source={require('@Assets/ic_camerapng.png')}
                />

                <ButtonCameraAndDocument 
                    nameIcon=""
                    isUseIcon={false}
                    isUseSource={true}
                    // classImage='w-[24px] h-[20px]'
                    onPress={
                        () => {
                            onAttachFile(selectedDocument?.id || '', selectedDocument?.name)
                            setShowBottomSheetDocumentCamera(false)
                        }
                    }                        
                    title='Pilih Document'
                    source={require('@Assets/ic_uploadfilepng.png')}
                />        
            </BottomSheet>
        )
    }  

    function renderOthersCategoryDocument () {
        const itemDocument = checkingDocument(13)
        if(itemDocument && itemDocument.length > 0){
            return itemDocument.map((item,index) => (
                <View className='pl-6 pr-4 py-3 border border-[#E7E7E7] flex flex-row justify-between h-[70px]' key={index}>
                    <View className='flex flex-row space-x-2.5 self-center'> 
                        <Image
                            className="self-center w-[18px] h-[18px]"
                            source={require('../../../../../../assets/icon-circle-checklist.png')}
                        />
                        <View className='flex flex-col space-y-1 w-[150px]'>
                            <IsuzuIdText className='text-[#5B5B5B] text-sm'>Lainnya ({index+1})</IsuzuIdText>
                            <IsuzuIdText className='text-[#71717A] text-xs'>{item.fileName}</IsuzuIdText>
                        </View>
                    </View>
                    <View className='flex flex-row space-x-4 items-center'>
                        <Pressable 
                            onPress={() => {
                                setSelectedDetailDocument(item)
                                setShowBottomSheetDocument(true)
                            }} 
                            className='border border-[#ADB5BB] rounded-lg p-2.5'
                        >
                            <FontAwesome5 name="ellipsis-h" color="#242424" size={24}></FontAwesome5> 
                        </Pressable>
                    </View>
                </View>
            ))
        }
    }

    const renderPreviewContent = () => {
		return (
			<Modal
				visible={showPreviewModal}
				onDismiss={() => setShowPreviewModal(false)}
				contentContainerStyle={styles.modalPreview}
			>
				<PreviewModalContent
					docId={previewDocId}
					mimeType={previewDocMimeType}
					onPressClose={() => setShowPreviewModal(false)}
				/>
			</Modal>
		);
	};

    const renderSnackbarSuccess = () => {
		return (
			<Snackbar
				className="rounded-full w-[70%] self-center"
				duration={2000}
				visible={successSnack}
				onDismiss={() => {
					setSuccessSnack(false);
				}}
			>
				<View className="flex-1 flex-row items-center justify-between">
					<MaterialCommunityIcons name="check-circle-outline" size={24} color="green" />
					<IsuzuIdText className="text-[14px] text-white ml-3">
						{successSnackMessage}
					</IsuzuIdText>
				</View>
			</Snackbar>
		);
	};

    const renderSnackbarErrorUploadFile = () => {
    return (
      <Snackbar
        className="rounded-full"
        duration={2000}
        visible={errorSnack}
        onDismiss={() => {
          setErrorSnack(false);
        }}
      >
        <View className="flex flex-row items-center gap-x-2">
          <MaterialCommunityIcons
            name="close-circle-outline"
            size={24}
            color={IsuzuRed}
          />
          <IsuzuIdText
            numberOfLines={3}
            className="text-[14px] text-white"
            style={{ width: Dimensions.get("window").width - 100 }}
          >
            {errorSnackMessage}
          </IsuzuIdText>
        </View>
      </Snackbar>
    );
  };

    const renderLKPPAttachment = () => {
        const findELKPP = detailDocument.find((e) => e.documentCategoryId === 14)
        if(findELKPP){
            return(
                <View
                    {...setAccessibility(CREATE_SPK_LABEL.ATTACHED_DOCUMENT_ITEM_LKPP)}
                    className="px-5 py-[15] bg-[#F7F7FB] flex-row items-center mt-2.5">
                    <Image source={require('../../../../../../assets/file.png')} />
                    <View className="flex-1 mx-5">
                        <IsuzuIdText bold>{findELKPP.documentCategoryName}</IsuzuIdText>
                        <IsuzuIdText className="text-[#8E8E8E]">{findELKPP.fileName}</IsuzuIdText>
                    </View>
                    <Pressable onPress={() => onDeleteFile(findELKPP)}>
                        <MaterialCommunityIcons name="close" size={20} color="#8E8E8E" />
                    </Pressable>
                </View>
            )
        }
        return (
            <Pressable 
                className='mb-2 flex flex-row space-x-2 w-[131px] h-[36px] rounded-xl bg-[#0479CE] items-center justify-center py-2 px-3.5'
                onPress={() => onAttachFile(14,'LKPP')}
                {...setAccessibility(CREATE_SPK_LABEL.DOCUMENT_E_KATALOG_LKPP)}
            >
                <Image 
                    source={require('../../../../../../assets/icon-upload.png')}
                    style={{
                        width : 20,
                        height : 20
                    }}
                />
                <IsuzuIdText className='text-sm text-white font-medium'>Upload File</IsuzuIdText>
            </Pressable>
        )
    }

    const requiredDokumen = (id:number) => {
        //ktp
        if(id === 1){
            return (
                <View> 
                    {errors.fileKTP && <IsuzuIdText className="text-xs text-red-600 italic">{errors.fileKTP?.message?.toString()}</IsuzuIdText> }
                </View>
            )
        }
        //npwp bpkb
        if(id === 2){
            return (
                <View> 
                    {errors.fileNPWPBPKB && <IsuzuIdText className="text-xs text-red-600 italic">{errors.fileNPWPBPKB?.message?.toString()}</IsuzuIdText> }
                </View>
            )
        }
        //npwp
        if(id === 3){
            return (
                <View> 
                    {errors.fileNPWP && <IsuzuIdText className="text-xs text-red-600 italic">{errors.fileNPWP?.message?.toString()}</IsuzuIdText> }
                </View>
            )
        }
        //ktpbpkb
        if(id === 4){
            return (
                <View> 
                    {errors.fileKTPBPKB && <IsuzuIdText className="text-xs text-red-600 italic">{errors.fileKTPBPKB?.message?.toString()}</IsuzuIdText> }
                </View>
            )
        }
        //spk
        if(id === 7){
            return (
                <View> 
                    {errors.fileSPK && <IsuzuIdText className="text-xs text-red-600 italic">{errors.fileSPK?.message?.toString()}</IsuzuIdText> }
                </View>
            )
        }
        //NIB Perusahaan
        if(id === 16){
           return (
                <View> 
                    {errors.fileNIBPerusahaan && <IsuzuIdText className="text-xs text-red-600 italic">{errors.fileNIBPerusahaan?.message?.toString()}</IsuzuIdText> }
                </View>
            )
        }
        //SPJB
        if(id === 9){
            return (
                <View> 
                    {errors.fileSPJB && <IsuzuIdText className="text-xs text-red-600 italic">{errors.fileSPJB?.message?.toString()}</IsuzuIdText> }
                </View>
            )
        }
        return null
    }

    const flagRequired = (id:number) => {
        if(createSPK?.detailCustomer?.title === 'Company'){
            //NIB Perusahaan
            if(id === 16){
            return (
                    <View className='bg-[#FFEFF0] rounded-lg pl-2.5 pr-2.5 h-[20px] pt-1'><IsuzuIdText className='font-extrabold text-[#ED1B26] text-xs'>Wajib</IsuzuIdText></View>
                )
            }
        }
        if(createSPK?.detailCustomer?.title !== 'Company'){
            //ktp
            if(id === 1){
                return (
                    <View className='bg-[#FFEFF0] rounded-lg pl-2.5 pr-2.5 h-[20px] pt-1'><IsuzuIdText className='font-extrabold text-[#ED1B26] text-xs'>Wajib</IsuzuIdText></View>
                )
            }
            //ktpbpkb
            if(id === 4){
                return (
                    <View className='bg-[#FFEFF0] rounded-lg pl-2.5 pr-2.5 h-[20px] pt-1'><IsuzuIdText className='font-extrabold text-[#ED1B26] text-xs'>Wajib</IsuzuIdText></View>
                )
            }
        }
        if(createSPK?.detailPayment?.salesTypeCode === 'CSH'){
            //SPJB
            if(id === 9){
                return (
                    <View className='bg-[#FFEFF0] rounded-lg pl-2.5 pr-2.5 h-[20px] pt-1'><IsuzuIdText className='font-extrabold text-[#ED1B26] text-xs'>Wajib</IsuzuIdText></View>
                )
            }
        }
        //npwp bpkb
        if(id === 2){
            return (
                <View className='bg-[#FFEFF0] rounded-lg pl-2.5 pr-2.5 h-[20px] pt-1'><IsuzuIdText className='font-extrabold text-[#ED1B26] text-xs'>Wajib</IsuzuIdText></View>
            )
        }
        //npwp pengguna
        if(id === 3){
            return (
                <View className='bg-[#FFEFF0] rounded-lg pl-2.5 pr-2.5 h-[20px] pt-1'><IsuzuIdText className='font-extrabold text-[#ED1B26] text-xs'>Wajib</IsuzuIdText></View>
            )
        }
        //spk
        if(id === 7){
            return (
                <View className='bg-[#FFEFF0] rounded-lg pl-2.5 pr-2.5 h-[20px] pt-1'><IsuzuIdText className='font-extrabold text-[#ED1B26] text-xs'>Wajib</IsuzuIdText></View>
            )
        }

        return null
    }

    if(isLoadingProfileProspect || isLoadingDataFileCategories || loadingSendSPK){
        return (
			<View className="flex-1 items-center justify-center">
				<ActivityIndicator size="large" color={IsuzuRed} />
			</View>
		)
    }

    return (
        <View className="flex-1">
            {loadingUpdate &&(
                <View className='h-full bg-white'>
                    <View className="flex-1 items-center justify-center">
                        <ActivityIndicator size="large" color={IsuzuRed} />
                    </View>
                </View>
            )}
            <KeyboardAvoidingView
				behavior={Platform.OS === "ios" ? "padding" : "height"}
				className="flex-1"
			>
            <HeaderStepSPK step={4}/>
            <ScrollView contentContainerStyle={styles.container}>
                <View className='flex-1 mb-5 mt-5'>
                    <IsuzuIdText bold className="text-base font-bold text-[#5B5B5B]">Keterangan SPK Lainnya</IsuzuIdText>
                </View>
                <View className='flex-1 mb-5'>
                    <IsuzuIdText bold className="text-base font-bold text-[#363636]">
                        GSO
                    </IsuzuIdText>
                </View>
                <View className='flex-1 mb-2.5'>
                    <IsuzuIdText bold className="text-sm mb-2">
                        LKPP 
                        {customerGroup === GOVERNMENT || createSPK?.detailPayment?.salesTypeCode === 'GSO' ? 
                        <IsuzuIdText className="text-red-600">*</IsuzuIdText> : null}
                    </IsuzuIdText>
                    <OutlinedDropdownInput {...setAccessibility(CREATE_SPK_LABEL.LKPP)} onPress={navigateToSelectLKPP} value={lkpp || ""} placeholder='Pilih LKPP'/>
                    <View className='mt-5'> 
                        {errors.lkpp && <IsuzuIdText className="mt-[-15] mb-5 text-red-600 italic">{errors.lkpp?.message?.toString()}</IsuzuIdText> }
                    </View>
                </View>
                <View className='flex-1 mb-2.5'>
                    <IsuzuIdText bold className="text-sm mb-2">
                        Total
                        {customerGroup === GOVERNMENT || createSPK?.detailPayment?.salesTypeCode === 'GSO' ? 
                        <IsuzuIdText className="text-red-600">*</IsuzuIdText> : null}
                    </IsuzuIdText>
                    <Controller
                        control={control}
                        name="total"
                        render={({ field: { value, onChange } }) => (
                            <View className="flex-row justify-center items-center mt-2 w-full h-10 bg-white border-[#C2C2C2] rounded-[4px] border-[1px] px-3 focus:border-isuzu-red">
                                <IsuzuIdText className="mr-2">
                                    Rp.
                                </IsuzuIdText>
                                <TextInput
                                    {...setAccessibility(CREATE_SPK_LABEL.TOTAL)}
                                    className="text-input flex-1 font-univers55 text-black"
                                    selectionColor={IsuzuRed}
                                    keyboardType="number-pad"
                                    value={numberFormattersV2(value)}
                                    onChangeText={(prev) => onChange(convertBackNumber(prev))}
                                />
                            </View>
                        )}
                    />
                    <View className='mt-5'> 
                        {errors.total && <IsuzuIdText className="mt-[-15] mb-5 text-red-600 italic">{errors.total?.message?.toString()}</IsuzuIdText> }
                    </View>
                </View>
                <View className='flex-1 mb-2.5'>
                    <IsuzuIdText bold className="text-sm mb-2">
                        E-Katalog LKPP 
                        {customerGroup === GOVERNMENT || createSPK?.detailPayment?.salesTypeCode === 'GSO' ? 
                        <IsuzuIdText className="text-red-600">*</IsuzuIdText> : null}
                    </IsuzuIdText>
                    {renderLKPPAttachment()}
                    <IsuzuIdText className='text-xs text-[#71717A]'>Format file PDF, JPG, JPEG, PNG maks 10 MB</IsuzuIdText>
                    <View className='mt-5'> 
                        {errors.fileELKPP && <IsuzuIdText className="mt-[-15] mb-5 text-red-600 italic">{errors.fileELKPP?.message?.toString()}</IsuzuIdText> }
                    </View>
                </View>
                <View className='flex-1 mb-5'>
                    <IsuzuIdText bold className="text-base font-bold text-[#363636]">SPK</IsuzuIdText>
                </View>
                <View className='flex-1 mb-2.5'>
                    <IsuzuIdText bold className="text-sm mb-2">
                        Nomor SPK<IsuzuIdText className="text-red-600">*</IsuzuIdText>
                    </IsuzuIdText>
                    <OutlinedDropdownInput {...setAccessibility(CREATE_SPK_LABEL.SPK_NUMBER)} onPress={navigateToSelectSPKNumber} value={spkNumber} placeholder='Pilih Nomor SPK'/>
                    <View className='mt-5'> 
                        {errors.spkNumber && <IsuzuIdText className="mt-[-15] mb-5 text-red-600 italic">{errors.spkNumber?.message?.toString()}</IsuzuIdText> }
                    </View>
                </View>
                <View className='flex-1 mb-2.5'>
                    <IsuzuIdText bold className="text-sm mb-2">
                        No. Inquiry IDMS<IsuzuIdText className="text-red-600">*</IsuzuIdText>
                    </IsuzuIdText>
                    <Controller
                        control={control}
                        name="inquiryNo"
                        render={({ field: { value, onChange } }) => (
                            <View className="flex-row justify-center items-center mt-2 w-full h-10 bg-white border-[#C2C2C2] rounded-[4px] border-[1px] px-3 focus:border-isuzu-red">
                                <TextInput
                                    {...setAccessibility(CREATE_SPK_LABEL.INQUIRY_NO)}
                                    className="flex-1 font-univers55 text-black"
                                    selectionColor={IsuzuRed}
                                    keyboardType="number-pad"
                                    value={value}
                                    onChangeText={(prev) => onChange(convertBackNumber(prev))}
                                    placeholder='Masukan No.Inquiry IDMS'
                                />
                            </View>
                        )}
                    />
                    <View className='mt-5'> 
                    {errors.inquiryNo && <IsuzuIdText className="mt-[-15] mb-5 text-red-600 italic">{errors.inquiryNo?.message?.toString()}</IsuzuIdText> }
                    </View>
                </View>
                <View className="flex-1 mb-2.5">
                    <View className="flex-row items-center mb-2.5">
                        <IsuzuIdText bold className="text-[14px] leading-4">Tanggal SPK</IsuzuIdText>
                        <IsuzuIdText bold className="text-[14px] leading-4 text-red-600">*</IsuzuIdText>
                    </View>
                    <Controller
                        {...setAccessibility(CREATE_SPK_LABEL.SPK_DATE)}
                        name="spkDate"
                        control={control}
                        render={() => (
                            <DatePicker
                                inputStyle={styles.datePicker}
                                isModalVisible={datePickerSPKDateVisible}
                                date={spkDate ? new Date(spkDate) : undefined}
                                onConfirm={onConfirmSPKDate}
                                onCancel={() => setDatePickerSPKDateVisible(false)}
                                onPress={() => setDatePickerSPKDateVisible(true)}
                            />
                        )}
                    />
                    <View className='mt-5'> 
                    {errors.spkDate && <IsuzuIdText className="mt-[-15] mb-5 text-red-600 italic">{errors.spkDate?.message?.toString()}</IsuzuIdText> }
                    </View>
                </View>
                <View className="flex-1 mb-2.5">
                    <View className="flex-row items-center mb-2.5">
                        <IsuzuIdText bold className="text-[14px] leading-4">Estimasi DO</IsuzuIdText>
                        <IsuzuIdText bold className="text-[14px] leading-4 text-red-600">*</IsuzuIdText>
                    </View>
                    <Controller
                        {...setAccessibility(CREATE_SPK_LABEL.DO_ESTIMATE)}
                        name="doEstimate"
                        control={control}
                        render={() => (
                            <DatePicker
                                inputStyle={styles.datePicker}
                                isModalVisible={datePickerDOEstimateVisible}
                                date={doEstimate ? new Date(doEstimate) : undefined}
                                onConfirm={onConfirmDoEstimateDate}
                                onCancel={() => setDatePickerDOEstimateVisible(false)}
                                onPress={() => setDatePickerDOEstimateVisible(true)}
                            />
                        )}
                    />
                    <View className='mt-5'> 
                    {errors.doEstimate && <IsuzuIdText className="mt-[-15] mb-5 text-red-600 italic">{errors.doEstimate?.message?.toString()}</IsuzuIdText> }
                    </View>
                </View>
                <View className='flex-1 mb-5'>
                    <IsuzuIdText bold className="text-base font-bold text-[#363636]">Dokumen</IsuzuIdText>
                </View>
                <View className='flex-1 mb-5'>
                    {dataDocumentCategories.map((item,index) => {
                        const checkingItem = checkingDocument(item.id)
                        if(!item.hidden){
                            return (
                                <View className='flex flex-col pl-6 pr-4 py-3 border border-[#E7E7E7] h-min-[80px]' key={index}>
                                    <View className='flex flex-row justify-between'>
                                        <View className='flex flex-row space-x-2.5 self-center'>
                                            {checkingDocumentUploaded('checklist',checkingItem,item.id,item.name)}
                                            <View className='flex flex-col space-y-1 w-[180px]'>
                                                <IsuzuIdText className='text-[#5B5B5B] text-sm'>
                                                    {item.name}
                                                </IsuzuIdText>
                                                {item.id !== 13 && checkingItem && checkingItem?.length > 0 && (
                                                    <IsuzuIdText className='text-[#71717A] text-xs'>
                                                        {checkingItem?.[0].fileName && checkingItem?.[0].fileName.length > 100
                                                        ? `${checkingItem?.[0].fileName.substring(0, 100)}...`
                                                        : checkingItem?.[0].fileName}
                                                    </IsuzuIdText>
                                                )}
                                            </View>
                                        </View>
                                        <View className='flex flex-row space-x-4 items-center'>
                                            {flagRequired(item.id)}
                                            {checkingDocumentUploaded('button',checkingItem,item.id,item.name)}
                                        </View>
                                    </View>
                                    {requiredDokumen(item.id)}
                                </View>
                            )
                        }
                    })}
                    {renderOthersCategoryDocument()}
                </View>
            </ScrollView>
            <View style={styles.buttonContainer}>
                <Button
                    {...setAccessibility(CREATE_SPK_LABEL.PREV_BUTTON)}
                    mode="outlined"
                    style={styles.goBackButton}
                    labelStyle={styles.goBackLabel}
                    uppercase={false}
                    onPress={navigateToBackStep}
                >
                    Sebelumnya
                </Button>
                <Button
                    {...setAccessibility(CREATE_SPK_LABEL.NEXT_BUTTON)}
                    style={styles.nextStepButton}
                    labelStyle={styles.nextLabel}
                    uppercase={false}
                    onPress={handleSubmit(onSubmit)}
                >
                    Simpan
                </Button>
            </View>
            {renderBottomSheetDocument()}
            {renderBottomSheetDocumentCamera()}
            {renderPreviewContent()}
            {renderSnackbarSuccess()}
            {renderSnackbarErrorUploadFile()}
            </KeyboardAvoidingView>
        </View>
    );
};

export default CreateSPKStep4Screen;
Leave a Comment