SpeedLimitSection/index.tsx

src/ui/components/widgets/SpeedLimitSection/index.tsx
mail@pastecode.io avatar
unknown
typescript
a month ago
6.4 kB
3
Indexable
Never
import { useSpeedLimitStore } from '@Contexts'
import { useSearchParams } from '@Hooks'
import { LoadingSpinner, RvTable } from '@Shared'
import { useCallback, useEffect, useState } from 'react'
import { useLocation } from 'react-router-dom'
import SpeedLimitFiller from './components/SpeedLimitFiller'
import { useSpeedLimitFilter } from './hooks'
import { useSpeedLimitReviewTable } from './hooks'
import { useSpeedLimitReducer } from './reducer'
import { ActionTypes, speedLimitItemType } from './types'
import PopupModel from './components/PopupModel'
import { CButton } from '@coreui/react'
import { Icons } from '@Assets/icons/Icons'
import { useDispatch, useSelector } from 'react-redux'
import { fetchZoneSpeedLimitsByRouteId } from '@Redux/slices/portalDataSlice'

interface selectedItemType {
  item: speedLimitItemType
  index: number
}

const SpeedLimitSection = () => {
  const [fakeLoading, setFakeLoading] = useState(false)
  const [isFirstLoad, setIsFirstLoad] = useState(true)

  const location = useLocation()
  const dispatch = useDispatch()
  const searchParams = useSearchParams()
  const { routes } = useSpeedLimitFilter()
  const {
    data: { railroadId }
  } = useSelector((state: any) => state.userInfo)
  const speedLimitStore = useSpeedLimitStore

  const speedLimitData = useSpeedLimitStore.use.speedLimits()
  const fetchData = useSpeedLimitStore.use.fetchData()
  const deleteZoneSpeedLimitItem =
    useSpeedLimitStore.use.deleteZoneSpeedLimitItem()

  const [state, actions] = useSpeedLimitReducer()
  const { fields, customCells, data, loading } = useSpeedLimitReviewTable(
    state,
    actions
  )
  console.log('🚀 ~ SpeedLimitSection ~ loading:', loading)

  const {
    type,
    actionType,
    page,
    routeId,
    isDeleteModal,
    dataDeleteItemSelected
  } = state
  // console.log('🚀 ~ SpeedLimitSection ~ isDeleteModal:', isDeleteModal)
  // console.log('🚀 ~ SpeedLimitSection ~ type:', type)
  // console.log('🚀 ~ SpeedLimitSection ~ page:', page)

  const handleDeleteSpeedLimit = () => {
    const payload = {
      ...dataDeleteItemSelected,
      onSuccess: () => {
        const routeIdParam = searchParams.getSearchParam('route-id')
        const directionParam = searchParams.getSearchParam('direction')
        const endDestinationId = routeIdParam
          ?.split('_')
          .filter(item => item !== directionParam)
        actions.onSelectedDeleteItem(null)
        actions.onChangeIsOpenModalDelete(false)
        if (routeIdParam) {
          console.log('run')
          dispatch(
            fetchZoneSpeedLimitsByRouteId({
              routeId: routeIdParam,
              railroadId: railroadId,
              startDestinationId: directionParam!,
              endDestinationId: endDestinationId![0]
            })
          )
        }
      }
    }
    deleteZoneSpeedLimitItem(payload)
  }

  const showData = useCallback(() => {
    const typeArr = type?.split(',')
    const updateSpeedLimits =
      data?.filter(
        (speedLimit: speedLimitItemType) =>
          typeArr.includes(speedLimit?.type!) || type === ''
      ) || []
    speedLimitStore.setState({ speedLimits: updateSpeedLimits })
    setFakeLoading(true)
    setTimeout(() => {
      setFakeLoading(false)
    }, 300)
  }, [data, type])

  const onChangePage = useCallback(
    (e: any) => {
      if (!isFirstLoad) {
        setTimeout(() => {
          actions.onChangePage(e.toString())
        }, 20)
      }
    },
    [isFirstLoad]
  )

  const handleRowClick = (item: speedLimitItemType, index: number) => {}

  useEffect(() => {
    const pageParam = searchParams.getSearchParam('page')
    pageParam && actions.onChangePage(pageParam)
    if (data && isFirstLoad) {
      setTimeout(() => {
        setIsFirstLoad(false)
      }, 500)
    }

    if (data && !isFirstLoad) {
      setTimeout(() => {
        actions.onChangePage('')
      }, 100)
    }
  }, [data])

  useEffect(() => {
    data && showData()
  }, [data, type])

  useEffect(() => {
    if (actionType === ActionTypes.Add && data) {
      searchParams.delSearchParam('page')
      actions.onChangePage('')
      showData()
    }
  }, [actionType])

  return (
    <div id="rv-portal">
      <h4>Speed limit</h4>
      <SpeedLimitFiller route={routes} state={state} actions={actions} />

      {/* <Modal
        show={isShowModel}
        selectedItem={selectedItem?.item}
        // edit={isEdit}
        onClose={onClose}
        onSubmit={handleClickSubmit}
      /> */}

      {fakeLoading || loading ? (
        <LoadingSpinner classNames="my-5" />
      ) : (
        <RvTable
          items={speedLimitData}
          fields={fields}
          itemsPerPage={5}
          sorter={false}
          striped={false}
          onRowClick={(item, index) => {
            handleRowClick(item, index)
          }}
          customizedCells={customCells}
          sorterValue={undefined}
          onPageChange={onChangePage}
          activePage={parseInt(state.page) ?? 1}
        />
      )}
      <PopupModel isOpen={isDeleteModal}>
        <div className="flex flex-col gap-2  px-4 py-4">
          <div className="flex gap-2 justify-start">
            <Icons.Warning className="w-[42px] h-[42px]" />
            <div>
              <div className=" mb-1">
                <span className="font-medium text-2xl ">
                  Delete Speed Limit
                </span>
              </div>
              <div>
                <span className="w-full font-normal text-[16px]">
                  Are you sure you want to delete speed limit
                </span>
              </div>
            </div>
          </div>
        </div>

        <div className="flex justify-end gap-2 px-4 pb-4">
          <CButton
            color="secondary"
            onClick={() => {
              actions.onChangeIsOpenModalDelete(false)
              actions.onSelectedDeleteItem(null)
            }}
          >
            Cancel
          </CButton>
          <CButton color="danger" onClick={handleDeleteSpeedLimit}>
            Delete
          </CButton>
        </div>
      </PopupModel>
    </div>
  )
}

export default SpeedLimitSection
Leave a Comment